title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Generate IP Addresses | Practice | GeeksforGeeks
Given a string S containing only digits, Your task is to complete the function genIp() which returns a vector containing all possible combinations of valid IPv4 IP addresses and takes only a string S as its only argument. Note: Order doesn't matter. For string 11211 the IP address possible are 1.1.2.11 1.1.21.1 1.12.1.1 11.2.1.1 Example 1: Input: S = 1111 Output: 1.1.1.1 Example 2: Input: S = 55 Output: -1 Your Task: Your task is to complete the function genIp() which returns a vector containing all possible combinations of valid IPv4 IP addresses in sorted order or -1 if no such IP address could be generated through the input string S, the only argument to the function. Expected Time Complexity: O(N * N * N * N) Expected Auxiliary Space: O(N * N * N * N) Constraints: 1<=N<=16 here, N = length of S. S only contains digits(i.e. 0-9) 0 dev1713 weeks ago simple c++ with for loops and conditions checks vector<string> genIp(string &s) { // Your code here vector<string>ans; for(int a=1;a<=3;a++) for(int b=1;b<=3;b++) for(int c=1;c<=3;c++) for(int d=1;d<=3;d++) if(a+b+c+d==s.size()){ int A=stoi(s.substr(0,a)); int B=stoi(s.substr(a,b)); int C=stoi(s.substr(a+b,c)); int D=stoi(s.substr(a+b+c,d)); string temp; if(A<=255 && B<=255 && C<=255 &&D<=255){ temp=to_string(A)+"."+to_string(B)+"."+to_string(C)+"."+to_string(D); if(temp.size()==s.size()+3) ans.push_back(temp); } } return ans; } -1 shashankrustagii3 months ago class Solution{ public: vector<string> genIp(string &s) { vector<string>res; string ans; for(int a=1;a<=3;a++) for(int b=1;b<=3;b++) for(int c=1;c<=3;c++) for(int d=1;d<=3;d++) if(a+b+c+d==s.length()){ int w=stoi(s.substr(0,a)),x=stoi(s.substr(a,b)), y=stoi(s.substr(a+b,c)), z=stoi(s.substr(a+b+c,d)); if(w<=255 and x<=255 and y<=255 and z<=255) if((ans=to_string(w)+"."+to_string(x)+"."+to_string(y)+"."+to_string(z)).size()==s.length()+3) res.push_back(ans); } return res; } }; 0 nikhar25003 months ago c++ codebool check(string s) { if( s != "" and s.size()<4) { if(s[0] == '0' and s.size() > 1) { return false; } else if(stoi(s) >=0 and stoi(s)<=255) { return true; } } return false; } void validip(string&s,int&i, int&j, int&k, vector<string>&temp) { string first = "",second = "",third = "",four = ""; for(int x=0; x<=i; x++) first += s[x]; for(int x=i+1; x<=j; x++) second += s[x]; for(int x=j+1; x<=k; x++) third += s[x]; for(int x=k+1; x<s.size(); x++) four += s[x]; if(check(first) and check(second) and check(third) and check(four) == true) { temp.push_back("T"); temp.push_back(first + "." + second + "." + third + "." + four); return; } else { temp.push_back("F"); return; } } vector<string> genIp(string &s) { // Your code here int n = s.size(); vector<string> ans; for(int i=0; i<n-3; i++) { for(int j=i+1; j<n-2; j++) { for(int k=j+1; k<n-1; k++) { vector<string>temp; validip(s,i,j,k,temp); if(temp[0] == "T") { ans.push_back(temp[1]); } } } } return ans; } }; +2 singhsanskar20003 months ago vector<string> genIp(string &s) { vector<string>res; string ans; for(int a=1;a<=3;a++){ for(int b=1;b<=3;b++){ for(int c=1;c<=3;c++){ for(int d=1;d<=3;d++){ if(a+b+c+d==s.length()){ int w=stoi(s.substr(0,a)); int x=stoi(s.substr(a,b)); int y=stoi(s.substr(a+b,c)); int z=stoi(s.substr(a+b+c,d)); if(w<=255 and x<=255 and y<=255 and z<=255){ if((ans=to_string(w)+"."+to_string(x)+"."+to_string(y)+"."+to_string(z)).size()==s.length()+3){ res.push_back(ans); } } } } } } } return res; } 0 sandeep55213 months ago Easy To Understand Backtracking solution in C++. class Solution{ public: void func(string s,vector<string> &ans,string v,int i,int d) // evolved brute force by backtracking { if(i==s.size() and d==4) // base case { v.pop_back(); ans.push_back(v); return; } if(i==s.size() or d==4) // fail case return; string t; // very useful but temporary string for (int j = i; j < s.size(); j++) { t.push_back(s[j]); if(t.size()==2 and t[0]=='0') // invalid ip return; if(t.size()>3 or stoi(t)>255) // invalid ip return; v.push_back(s[j]); v.push_back('.'); func(s,ans,v,j+1,d+1); v.pop_back(); // backtracking } } vector<string> genIp(string &s) { vector<string> ans; func(s,ans,"",0,0); return ans; } }; 0 himanshujain4574 months ago SIMPLEST CODE: vector<string> genIp(string &s) { vector<string>v; set<string>mp; int n=s.length(); for(int i=0;i<n-3;i++) { for(int j=i+1;j<n-2;j++) { for(int k=j+1;k<n-1;k++) { for(int l=k+1;l<n;l++) { string t1=s.substr(0,j); string t2=s.substr(j,k-j); string t3=s.substr(k,l-k); string t4=s.substr(l); if(t1.length()>3||t2.length()>3||t3.length()>3||t4.length()>3) continue; if(stol(t1)<256 and stol(t2)<256 and stol(t3)<256 and stol(t4)<256) { string temp=t1+'.'+t2+'.'+t3+'.'+t4; if((t1[0]=='0' and t1.length()>1)|| (t2[0]=='0' and t2.length()>1)|| (t3[0]=='0' and t3.length()>1)|| (t4[0]=='0' and t4.length()>1)) continue; else { //v.push_back(temp); mp.insert(temp); } } } } } } for(auto e:mp) v.push_back(e); sort(v.begin(),v.end()); return v; } 0 anutiger4 months ago vector<string> res; void solve(string s,string t,int cnt){ if(s.length() == 0 and cnt == 4){ t.pop_back(); res.push_back(t); return; } for(int i = 0; i < s.length() ; i++){ string d = s.substr(0 , i + 1); if(d[0] == '0' and d.length() > 1) continue; if(stol(d) < 256){ string tmp = s.substr(i + 1); solve(tmp,t + d + '.' , cnt + 1); }else return; } } vector<string> genIp(string &s) { res.clear(); solve(s, "" , 0); return res; } 0 danail kozhuharov This comment was deleted. 0 hunkthanatos5 months ago Can anyone tell me how to optimise this? public ArrayList<String> genIp(String s) { // code here ArrayList<String> arr = new ArrayList<String>(); String op=""; solve(s,0,op,arr); ArrayList<String> res = new ArrayList<String>(); for(String sp: arr){ if(validIP(sp)) res.add(sp); } return res; } public void solve(String s, int i, String op, ArrayList<String> arr){ if(i == s.length()){ arr.add(op); return; } solve(s, i+1, op+s.charAt(i)+".", arr); solve(s, i+1, op+s.charAt(i), arr); } public boolean validIP (String ip) { try { if ( ip == null || ip.isEmpty() ) { return false; } String[] parts = ip.split( "\\." ); if ( parts.length != 4 ) { return false; } for ( String s : parts ) { int i = Integer.parseInt( s ); if ( (i < 0) || (i > 255) ) { return false; } } if ( ip.endsWith(".") ) { return false; } return true; } catch (NumberFormatException nfe) { return false; } } +1 whitewolf057 months ago Can anyOne say what is wrong in this code: class Solution { public ArrayList<String> genIp(String s) { // code here ArrayList<String> al = new ArrayList<>(); int n = s.length(); for(int i =0; i<n-3; i++){ for(int j=i;j<n-2; j++){ for(int k=j; j<n-1;j++){ if(isValid(s,i, j, k)){ al.add(makeIp(s, i, j, k)); } } } } return al; } public boolean isValid(String s, int i, int j, int k){ String A = s.substring(0,i); String B = s.substring(i+1, j); String C = s.substring(j+1, k); String D = s.substring(k+1, s.length()-1); int a = Integer.parseInt(A); int b = Integer.parseInt(B); int c = Integer.parseInt(C); int d = Integer.parseInt(D); if(A.length()>0 && A.length()<=3 || B.length()>0 && B.length()<=3 || C.length()>0 && C.length()<=3 || D.length()>0 && D.length()<=3){ return true; } if(A.charAt(0)=='0' && A.length() == 1 || B.charAt(0)=='0' && B.length() == 1 || C.charAt(0)=='0' && C.length() == 1 || D.charAt(0)=='0' && D.length() == 1 ) return true; if(a>=0 && a<=255 || b>=0 && b<=255 ||c>=0 && c<=255 ||d>=0 && d<=255 ){ return true; } return false; } public String makeIp(String s, int i, int j, int k){ String res=""; for(int a =0; a<s.length(); a++){ if(a==i+1||a==j+1||a==k+1){ res= res+"."; } res+= s.charAt(a); } return res; }} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 571, "s": 238, "text": "Given a string S containing only digits, Your task is to complete the function genIp() which returns a vector containing all possible combinations of valid IPv4 IP addresses and takes only a string S as its only argument.\nNote: Order doesn't matter.\n\nF...
Powershell - Invoke-Expression Cmdlet
Invoke-Expression cmdlet is used to perform a command or expression on local computer. In these example, we're see the Invoke-Expression cmdlet in action. In this example, we'll show how to invoke an expression. > $Command = 'Get-Process' > $Command Get-Process > Invoke-Expression $Command Here you can notice that $Command print the expression where as Invoke-Expression executes the expression. Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ ---- ----------- 78 8 1288 3892 43 0.02 2556 armsvc 119 9 15808 15572 50 600 audiodg 88 8 2512 5860 73 0.02 3144 chrome 186 19 23360 31580 740 0.23 3148 chrome 218 22 28432 44848 769 0.86 3492 chrome 15 Lectures 3.5 hours Fabrice Chrzanowski 35 Lectures 2.5 hours Vijay Saini 145 Lectures 12.5 hours Fettah Ben Print Add Notes Bookmark this page
[ { "code": null, "e": 2121, "s": 2034, "text": "Invoke-Expression cmdlet is used to perform a command or expression on local computer." }, { "code": null, "e": 2189, "s": 2121, "text": "In these example, we're see the Invoke-Expression cmdlet in action." }, { "code": null,...
Mask RCNN implementation on a custom dataset! | by Dhruvil Shah | Towards Data Science
Instance segmentation is the function of pixel-level recognition of object outlines. It’s one of the hardest possible vision tasks relative to equivalent computer vision tasks. Refer to the following terminologies: Classification: There is a horse/man in this image. Semantic Segmentation: These are all the horse/man pixels. Object Detection: There are a horse and a man in this image at these locations. We’re starting to account for objects that overlap. Instance Segmentation: There is a horse and a man at these locations and these are the pixels that belong to each one. You can learn the basics and how Mask RCNN actually works from here. We will implement Mask RCNN for a custom dataset in just one notebook. All you need to do is run all the cells in the notebook. We will perform simple Horse vs Man classification in this notebook. You can change this to your own dataset. I have shared the links at the end of the article. Let’s begin. First, we will clone a repository that contains some of the building code blocks for implementing Mask RCNN. The function copytree() will get the necessary files for you. After cloning the repository we will import the dataset. I am importing the dataset from my drive. !git clone "https://github.com/SriRamGovardhanam/wastedata-Mask_RCNN-multiple-classes.git"import shutil, osdef copytree(src = '/content/wastedata-Mask_RCNN-multiple-classes/main/Mask_RCNN', dst = '/content/', symlinks=False, ignore=None): try: shutil.rmtree('/content/.ipynb_checkpoints') except: pass for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d)copytree()shutil.copytree('/content/drive/MyDrive/MaskRCNN/newdataset','/content/dataset') Let’s talk about the dataset now. The dataset that I imported from my drive is structured as: dataset --train ----21414.JPG ----2r41rfw.JPG ----... ----via_project.json--val ----w2141fq2cr2qrc234.JPG ----2awfr4awawfa1rfw.jpg ----... ----via_project.json The dataset that I have used, is created from VGG Image Annotator (VIA). The annotation file is in .json format which contains the coordinates of all the polygons which I have drawn on my images. The .json file will look something like this: {"00b1f292-23dd-44d4-aad3-c1ffb6a6ad5a___RS_LB 4479.JPG21419":{"filename":"00b1f292-23dd-44d4-aad3-c1ffb6a6ad5a___RS_LB 4479.JPG","size":21419,"regions":[{"shape_attributes":{"name":"polygon","cx":83,"cy":177,"r":43},"region_attributes":{"name":"Horse","image_quality":{"good":true,"frontal":true,"good_illumination":true}}},{"shape_attributes":{'all_points_x': [1,2,4,5], 'all_points_y': [0.2,2,5,7], 'name': 'polygon'},"region_attributes":{"name":"Man","image_quality":{"good":true,"frontal":true,"good_illumination":true}}},{"shape_attributes":{"name":"ellipse","cx":156,"cy":189,"rx":19.3,"ry":10,"theta":-0.289},"region_attributes":{"name":"Horse","image_quality":{"good":true,"frontal":true,"good_illumination":true}}}],"file_attributes":{"caption":"","public_domain":"no","image_url":""}},..., ...} Note: Although I have shown more than one shape in the above snippet, you should only use one shape while annotating the images. For instance, if you choose polygons as I have for the Horse vs Man classifier then you should annotate all the regions with polygons only. We will discuss how you can use multiple shapes for annotations later in this tutorial. Note: This is the most important step for implementing the Mask RCNN architecture without getting any errors. !pip install keras==2.2.5%tensorflow_version 1.x You will face many errors in TensorFlow version 2.x. Also, the Keras version 2.2.5 will save us from many errors. I will not go into detail regarding which kinds of error this resolves. First, we will import a few libraries. Then we will give the path to the trained weights file. This could be the COCO weights file or your last saved weights file (checkpoint). The log directory is where all our data will be stored when training begins. The model weights at every epoch are saved in .h5 format in the directory so if the training gets hindered due to any reason you can always start from where you left off by specifying the path to the last saved model weights. For instance, if I am training my model for 10 epochs and at epoch 3 my training is obstructed then I will have 3 .h5 files stored in my logs directory. And now I do not have to start my training from the beginning. I can simply change my weights path to the last weights file e.g. ‘mask_rcnn_object_0003.h5’. import osimport sysimport jsonimport datetimeimport numpy as npimport skimage.drawimport cv2from mrcnn.visualize import display_instancesimport matplotlib.pyplot as plt# Root directory of the projectROOT_DIR = os.path.abspath("/content/wastedata-Mask_RCNN-multiple-classes/main/Mask_RCNN/")# Import Mask RCNNsys.path.append(ROOT_DIR) # To find local version of the libraryfrom mrcnn.config import Configfrom mrcnn import model as modellib, utils# Path to trained weights fileCOCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")# Directory to save logs and model checkpointsDEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, "logs")class CustomConfig(Config): """Configuration for training on the dataset. Derives from the base Config class and overrides some values. """ # Give the configuration a recognizable name NAME = "object" # We use a GPU with 12GB memory, which can fit two images. # Adjust down if you use a smaller GPU. IMAGES_PER_GPU = 2 # Number of classes (including background) NUM_CLASSES = 1 + 2 # Background + (Horse and Man) # Number of training steps per epoch STEPS_PER_EPOCH = 100 # Skip detections with < 90% confidence DETECTION_MIN_CONFIDENCE = 0.9 CustomConfig class contains our custom configurations for the model. We simply overwrite the data in the original Config class from the config.py file that was imported earlier. The number of classes is supposed to be total_classes + 1 (for background). Steps per epoch are set to 100 but if you want you can increase if you have access to higher computing resources. The detection threshold is 90% that means all the proposals with less than 0.9 confidence will be ignored. This threshold is different than the one while testing an image. Look at the two images below for clarification. The class below contains 3 crucial methods for our custom dataset. This class inherits from “utils.Dataset” which we imported in the 1st step. The ‘load_custom’ method is for saving the annotations along with the image. Here we extract polygons and the respective classes. polygons = [r[‘shape_attributes’] for r in a[‘regions’]] objects = [s[‘region_attributes’][‘name’] for s in a[‘regions’]] Polygons variable contains the coordinates of the masks. Objects variable contains the names of the respective classes. The ‘load_mask’ method loads the masks as per the coordinates of polygons. The mask of an image is nothing but a list containing binary values. Skimage.draw.polygon() does the task for us and returns the indices for the coordinates of the mask. Earlier we discussed that you should not use more than one shape while annotating as it will get intricate when loading masks. Although If you want to use multiple shapes i.e. circle, ellipse, and polygon then you will need to change the load mask function as below. def load_mask(self, image_id): ... ##change the for loop only for i, p in enumerate(info["polygons"]): # Get indexes of pixels inside the polygon and set them to 1 if p['name'] == 'polygon': rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x']) elif p['name'] == 'circle': rr, cc = skimage.draw.circle(p['cx'], p['cy'], p['r']) else: rr, cc = skimage.draw.ellipse(p['cx'], p['cy'], p['rx'], p['ry'], rotation=np.deg2rad(p['theta'])) mask[rr, cc, i] = 1 ... This is one way you can load masks with multiple shapes but this is just speculation and the model will not detect a circle or ellipse unless it captures a perfect circle or ellipse. The dataset that I imported from my drive is structured as: dataset --train ----21414.JPG ----2r41rfw.JPG ----... ----via_project.json --val ----w2141fq2cr2qrc234.JPG ----2awfr4awawfa1rfw.jpg ----... ----via_project.json First, we will create an instance of CustomDataset class for the training dataset. Similarly, create another instance for the validation dataset. Then we will call the load_custom() method by passing in the name of the directory where our data is stored. ‘layers’ parameter is set to ‘heads’ here as I am not planning to train all the layers in the model. This will only train some of the top layers in the architecture. If you want you can set ‘layers’ to ‘all’ for training all the layers in the model. I am running the model for only 10 only as this tutorial is supposed to just guide you. This step is for setting up the model for training and downloading and loading pre-trained weights. You can load the weights of COCO or your last saved model. The call ‘modellib.MaskRCNN()’ is the step where you can get lots of errors if you have not chosen the right versions in the 2nd section. This method has a parameter ‘mode’ which decides whether we want to train the model or test the model. If you want to test set ‘mode’ to ‘inference’. ‘model_dir’ is for saving the data while training for backup. Then, we download the pre-trained COCO weights in the next step. Note: If you want to resume training from a saved point then you need to change ‘weights_path’ to the path where your .h5 file is stored. This step should not throw any error if you have followed the steps above and training should start smoothly. Remember we need to have Keras version 2.2.5 for this step to run error-free. train(model) Note: If you get an error restart runtime and run all the cells again. It may be because of the version of TensorFlow or Keras loaded. Follow step 2 for choosing the right versions. Note: Ignore any warnings you get while training! You can find the instructions in the notebook on how to test our model once training is finished. import osimport sysimport randomimport mathimport reimport timeimport numpy as npimport tensorflow as tfimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.patches as patchesimport matplotlib.image as mpimg# Root directory of the project#ROOT_DIR = os.path.abspath("/")# Import Mask RCNNsys.path.append(ROOT_DIR) # To find local version of the libraryfrom mrcnn import utilsfrom mrcnn import visualizefrom mrcnn.visualize import display_imagesimport mrcnn.model as modellibfrom mrcnn.model import log%matplotlib inline# Directory to save logs and trained modelMODEL_DIR = os.path.join(ROOT_DIR, "logs")# Path to Ballon trained weights# You can download this file from the Releases page# https://github.com/matterport/Mask_RCNN/releasesWEIGHTS_PATH = "/content/wastedata-Mask_RCNN-multiple-classes/main/Mask_RCNN/logs/object20201209T0658/mask_rcnn_object_0010.h5" # TODO: update this path Here, we define the path to our last saved weights file to run the inference on. Then, we define simple configuration terms. Here, confidence is specified again for testing. This is different from the one used in training. config = CustomConfig()CUSTOM_DIR = os.path.join(ROOT_DIR, "/content/dataset/")class InferenceConfig(config.__class__): # Run detection on one image at a time GPU_COUNT = 1 IMAGES_PER_GPU = 1 DETECTION_MIN_CONFIDENCE = 0.7config = InferenceConfig()config.display() # Device to load the neural network on. Useful if you're training a model on the same machine, in which case use CPU and leave the GPU for training.DEVICE = "/gpu:0" # /cpu:0 or /gpu:0# Inspect the model in training or inference modes values: 'inference' or 'training'TEST_MODE = "inference"def get_ax(rows=1, cols=1, size=16): ""Return a Matplotlib Axes array to be used in all visualizations in the notebook. Provide a central point to control graph sizes. Adjust the size attribute to control how big to render images""" _, ax = plt.subplots(rows, cols, figsize=(size*cols, size*rows)) return ax# Load validation datasetCUSTOM_DIR = "/content/dataset"dataset = CustomDataset()dataset.load_custom(CUSTOM_DIR, "val")# Must call before using the datasetdataset.prepare()print("Images: {}\nClasses: {}".format(len(dataset.image_ids), dataset.class_names)) Now we will load the model to run inference. #LOAD MODEL# Create model in inference modewith tf.device(DEVICE): model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config) Now loading the weights in the model. # Load COCO weights Or, load the last model you trainedweights_path = WEIGHTS_PATH# Load weightsprint("Loading weights ", weights_path)model.load_weights(weights_path, by_name=True) Now, we are ready for testing our model on any image. #RUN DETECTIONimage_id = random.choice(dataset.image_ids)print(image_id)image, image_meta, gt_class_id, gt_bbox, gt_mask =\ modellib.load_image_gt(dataset, config, image_id, use_mini_mask=False)info = dataset.image_info[image_id]print("image ID: {}.{} ({}) {}".format(info["source"], info["id"], image_id,dataset.image_reference(image_id)))# Run object detectionresults = model.detect([image], verbose=1)# Display resultsx = get_ax(1)r = results[0]visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], dataset.class_names, r['scores'], ax=ax, title="Predictions")log("gt_class_id", gt_class_id)log("gt_bbox", gt_bbox)log("gt_mask", gt_mask)# This is for predicting images which are not present in datasetpath_to_new_image = '/content/dataset/test/unnamed.jpg'image1 = mpimg.imread(path_to_new_image)# Run object detectionprint(len([image1]))results1 = model.detect([image1], verbose=1)# Display resultsax = get_ax(1)r1 = results1[0]visualize.display_instances(image1, r1['rois'], r1['masks'], r1['class_ids'],dataset.class_names, r1['scores'], ax=ax, title="Predictions1") For fun, you can try the below code which is present in the original implementation of Mask RCNN. This will convert everything grayscale except for the object mask areas. You can call this function as specified below. For video detection, call the second function. splash = color_splash(image, r['masks'])display_images([splash], cols=1) You can learn how Region Proposals work from the latter cells of the notebook. Below are some of the interesting images that might catch your eye if you are curious about how the Region Proposal Networks work. You may want to see how Proposal classification works and how we get our final regions for segmentation. This portion is also covered in the latter part of the notebook.
[ { "code": null, "e": 387, "s": 172, "text": "Instance segmentation is the function of pixel-level recognition of object outlines. It’s one of the hardest possible vision tasks relative to equivalent computer vision tasks. Refer to the following terminologies:" }, { "code": null, "e": 439...
IntStream mapToLong() method in Java
The mapToLong() function in IntStream class returns a LongStream consisting of the results of applying the given function to the elements of this stream. The syntax is as follows. LongStream mapToLong(IntToLongFunction mapper) Here, the parameter mapper is a stateless function to apply to each element. Create an IntStream with some elements in the Stream. IntStream intStream = IntStream.of(50, 100, 150, 200); Now create a LongStream and use the mapToLong() with a condition. LongStream longStream = intStream.mapToLong(num → (long)num); The following is an example to implement IntStream mapToLong() method in Java. import java.util.*; import java.util.stream.IntStream; import java.util.stream.LongStream; public class Demo { public static void main(String[] args) { IntStream intStream = IntStream.of(50, 100, 150, 200); LongStream longStream = intStream.mapToLong(num → (long)num); longStream.forEach(System.out::println); } } 50 100 150 200
[ { "code": null, "e": 1216, "s": 1062, "text": "The mapToLong() function in IntStream class returns a LongStream consisting of the results of applying the given function to the elements of this stream." }, { "code": null, "e": 1242, "s": 1216, "text": "The syntax is as follows." ...
Chained Exceptions in Java - GeeksforGeeks
23 Dec, 2016 Chained Exceptions allows to relate one exception with another exception, i.e one exception describes cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero but the actual cause of exception was an I/O error which caused the divisor to be zero. The method will throw only ArithmeticException to the caller. So the caller would not come to know about the actual cause of exception. Chained Exception is used in such type of situations. Constructors Of Throwable class Which support chained exceptions in java : Throwable(Throwable cause) :- Where cause is the exception that causes the current exception.Throwable(String msg, Throwable cause) :- Where msg is the exception message and cause is the exception that causes the current exception. Throwable(Throwable cause) :- Where cause is the exception that causes the current exception. Throwable(String msg, Throwable cause) :- Where msg is the exception message and cause is the exception that causes the current exception. Methods Of Throwable class Which support chained exceptions in java : getCause() method :- This method returns actual cause of an exception.initCause(Throwable cause) method :- This method sets the cause for the calling exception. getCause() method :- This method returns actual cause of an exception. initCause(Throwable cause) method :- This method sets the cause for the calling exception. Example of using Chained Exception: // Java program to demonstrate working of chained exceptionspublic class ExceptionHandling{ public static void main(String[] args) { try { // Creating an exception NumberFormatException ex = new NumberFormatException("Exception"); // Setting a cause of the exception ex.initCause(new NullPointerException( "This is actual cause of the exception")); // Throwing an exception with cause. throw ex; } catch(NumberFormatException ex) { // displaying the exception System.out.println(ex); // Getting the actual cause of the exception System.out.println(ex.getCause()); } }} Output: java.lang.NumberFormatException: Exception java.lang.NullPointerException: This is actual cause of the exception This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-Exceptions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Stream In Java Stack Class in Java Singleton Class in Java Set in Java Overriding in Java LinkedList in Java Collections in Java Initializing a List in Java
[ { "code": null, "e": 24430, "s": 24402, "text": "\n23 Dec, 2016" }, { "code": null, "e": 24960, "s": 24430, "text": "Chained Exceptions allows to relate one exception with another exception, i.e one exception describes cause of another exception. For example, consider a situation...
Using Lambda Function with Amazon Kinesis
AWS Kinesis service is used to capture/store real time tracking data coming from website clicks, logs, social media feeds. We can trigger AWS Lambda to perform additional processing on this logs. The basic requirements to get started with Kinesis and AWS Lambda are as shown − Create role with required permissions Create data stream in Kinesis Create AWS Lambda function. Add code to AWS Lambda Add data to Kinesis data stream Let us work on an example wherein we will trigger AWS Lambda for processing the data stream from Kinesis and send mail with the data received. A simple block diagram for explaining the process is shown below − Go to AWS console and create a role. Go to AWS console and create data stream in kinesis. There are 4 options as shown. We will work on Create data stream in this example. Click Create data stream. Enter the name in Kinesis stream name given below. Enter number of shards for the data stream. The details of Shards are as shown below − Enter the name and click the Create Kinesis stream button at the bottom. Note that it takes certain time for the stream to go active. Go to AWS console and click Lambda. Create AWS Lambda function as shown − Click Create function button at the end of the screen. Add Kinesis as the trigger to AWS Lambda. Add configuration details to the Kinesis trigger − Add the trigger and now add code to AWS Lambda. For this purpose, we will use nodejs as the run-time. We will send mail once AWS Lambda is triggered with kinesis data stream. const aws = require("aws-sdk"); var ses = new aws.SES({ region: 'us-east-1' }); exports.handler = function(event, context, callback) { let payload = ""; event.Records.forEach(function(record) { // Kinesis data is base64 encoded so decode here payload = new Buffer(record.kinesis.data, 'base64').toString('ascii'); console.log('Decoded payload:', payload); }); var eParams = { Destination: { ToAddresses: ["xxxxxxx@gmail.com"] }, Message: { Body: { Text: { Data:payload } }, Subject: { Data: "Kinesis data stream" } }, Source: "cxxxxxxxxx@gmail.com" }; var email = ses.sendEmail(eParams, function(err, data) { if (err) console.log(err); else { console.log("===EMAIL SENT==="); console.log("EMAIL CODE END"); console.log('EMAIL: ', email); context.succeed(event); callback(null, "email is send"); } }); }; The event param has the data entered in kinesis data stream. The above aws lambda code will get activated once data is entered in kinesis data stream. Here we will use AWS CLI to add data kinesis data stream as shown below. For this purpose, we can use the following command − aws kinesis put-record --stream-name kinesisdemo --data "hello world" -- partition-key "789675" Then, AWS Lambda is activated and the mail is sent. 35 Lectures 7.5 hours Mr. Pradeep Kshetrapal 30 Lectures 3.5 hours Priyanka Choudhary 44 Lectures 7.5 hours Eduonix Learning Solutions 51 Lectures 6 hours Manuj Aggarwal 41 Lectures 5 hours AR Shankar 14 Lectures 1 hours Zach Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2602, "s": 2406, "text": "AWS Kinesis service is used to capture/store real time tracking data coming from website clicks, logs, social media feeds. We can trigger AWS Lambda to perform additional processing on this logs." }, { "code": null, "e": 2683, "s": 2602,...
Creating and Using Virtual Environment on Jupyter Notebook with Python | by Cornellius Yudha Wijaya | Towards Data Science
As a Data Scientist, we would like to experiment with many different packages and codes to create that amazing analysis and superb machine learning model. The problem with this kind of experiment is that many packages dependencies overlap one another, and sometimes it disturbs our working environment. In this case, we need what we called Virtual Environment. A virtual environment, just as the name implies, is an environment that is virtually created. It is an empty place isolated from our local source where we could install and play around with code and packages. It is a best practice to use Virtual Environment where we are testing a new package or creating a new pipeline. While it is a best practice, sometimes people wonder how we implement the newly created virtual environment we create to be used in the Jupyter Notebook. In this case, I want to show you how to create and use the virtual environment in Jupyter Notebook. Creating a Virtual Environment using Python is a simple task, although, in this article, I assume you already installed Python 3. As a starter, we need to install the following package first via pip. pip install virtualvenv In your CLI or Command Prompt, we would type the following code to create the virtual environment. virtualvenv myenv where you could replace myenv with any virtual environment name you want. Creating the virtual environment is not enough; we also need to activate this virtual environment to use it. To do that, try to type the following code. .\myenv\Scripts\activate With that, we already have our virtual environment set. You might want to check your default virtual environment python version and what packages automatically installed. #check the python versionpython --version#check the packagespip list When you think you do not want to be inside the virtual environment anymore, you could type deactivate. Many people installing Anaconda to simplify packages management. With Anaconda, we could create a virtual environment as well. The steps are similar to the one we did previously with Python, but we only rely on the conda command. To create a virtual environment, we only need to run the following code. conda create -n myenv python=3.6 Where myenv is the name of the virtual environment and python= is the version of python you want inside the virtual environment. To use the virtual environment, we need to activate that virtual environment. We can do that by running the following code. conda activate myenv With this, the virtual environment is activated, and you could install any packages dependencies you want inside this virtual environment. If you have finished the task, you might want to get out of the virtual environment by running the following code. conda deactivate If you want to check all the virtual environment you already created in the Anaconda, you can check it using conda env list and if you want to remove any environment, you could run the code conda env remove -n myenv. When you have created a virtual environment, you would realize that the virtual environment is separate from your Jupyter Notebook. We need to set up a few things before we could have our virtual environment in the Jupyter Notebook. First, activate your virtual environment and run this code. pip install --user ipykernel We need to manually add the kernel if we want to have the virtual environment in the Jupyter Notebook. That is why we need to add it by running this code. python -m ipykernel install --user --name=myenv With this, we have set up our virtual environment kernel and ready to be used in the Jupyter Notebook. You could check in your Jupyter Lab interface or when you create a new Jupyter Notebook. The notebook you created based on the virtual environment would have all the packages you already installed in this environment. If you have finished with the virtual environment and did not need it anymore, you could remove it using this code. jupyter kernelspec uninstall myenv I have shown you to create a new virtual environment using Python or Conda. You only need to create a virtual environment, activate it, and add the kernel. I hope it helps! Visit me on my LinkedIn or Twitter If you are not subscribed as a Medium Member, please consider subscribing through my referral.
[ { "code": null, "e": 532, "s": 171, "text": "As a Data Scientist, we would like to experiment with many different packages and codes to create that amazing analysis and superb machine learning model. The problem with this kind of experiment is that many packages dependencies overlap one another, and...
Python Program for factorial of a number
In this article, we will learn about the solution and approach to solve the given problem statement. Problem statement −Our task to compute the factorial of n. Factorial of a non-negative number is given by − n! = n*n-1*n-2*n-3*n-4*.................*3*2*1 We have two possible solutions to the problem Recursive approach Iterative approach Live Demo def factorial(n): # recursive solution if (n==1 or n==0): return 1 else: return n * factorial(n - 1) # main num = 6 print("Factorial of",num,"is", factorial(num)) ('Factorial of', 6, 'is', 720) All the variables are declared in global scope as shown in the image below Approach 2 −Iterative Approach Live Demo def factorial(n):# iterative solution fact=1 for i in range(2,n+1): fact=fact*i return fact # main num = 6 print("Factorial of",num,"is", factorial(num)) ('Factorial of', 6, 'is', 720) All the variables are declared in global scope as shown in the image below In this article, we learned about the approach to compute the factorial of a number n.
[ { "code": null, "e": 1163, "s": 1062, "text": "In this article, we will learn about the solution and approach to solve the given problem statement." }, { "code": null, "e": 1222, "s": 1163, "text": "Problem statement −Our task to compute the factorial of n." }, { "code": ...
Approaching Anomaly Detection in Transactional Data | by Ivan Senilov | Towards Data Science
Usually, people mean financial transactions when they talk about transactional data. However, according to Wikipedia, “Transactional Data is data describing an event (the change as a result of a transaction) and is usually described with verbs. Transaction data always has a time dimension, a numerical value and refers to one or more objects”. In this article, we will use data on requests made to a server (internet traffic data) as an example, but the considered approaches can be applied to most of the datasets falling under the aforementioned definition of transactional data. Anomaly Detection, in simple words, is finding data points that shouldn’t normally occur in a system that generated data. Anomaly detection in transactional data has many applications, here are a couple of examples: Fraud detection in financial transactions. Fault detection in manufacturing. Attack or malfunction detection in a computer network (the case covered in this article). Recommendation of predictive maintenance. Health condition monitoring and alerting. The data we will use as an example looks like this: with columns described below: timestamp: When the event occurred. serverId: A unique identifier of a server being accessed. ip: Either IPv4 address or IPv6 address of the client. timeMs: Time in milliseconds that passes between moments of request and server’s response. clientSSLProtocol: SSL Encryption protocol used for the request. clientHTTPMethod: POST, GET, PUT, PATCH, and DELETE. clientRequestHTTPProtocol: Version of HTTP Protocol, e.g. HTTP/1, HTTP/2. clientRequestPath: The path requested, ex. /v3/article/. userAgent: A characteristic string that lets servers and network peers identify the application, operating system, vendor, and/or version of the requesting user agent. We are not performing classic EDA (Exploratory Data Analysis) here but rather try to understand how the data can be used from the several given examples. The existing features (columns) fall into 3 categories complemented with ways to use them: Real numbers (timeMs, ...). These can be used straight away (in the case of tree-based models) or normalized before feeding to a model. Categorical variables with low cardinality (clientSSLProtocol, clientHTTPScheme, clientHTTPMethod, ...) Can be encoded (one hot, target, etc..) or embedded. Categorical variables with high cardinality and textual data (clientRequestPath, userAgent, ...). These are trickier, one way is to parse the texts and try to infer categories that have lower cardinality or, for example, use text embeddings. 2.3.1 Time features The timestamp can be encoded to features like: Minute of hour Hour of day Day of week etc... To get rid of implicit ordering (i.e. distance between Monday and Sunday is the same as between other consecutive days but if they are encoded as 1 and 7 respectively this property is not true), often Sine and Cosine of normalized values are used. 2.3.2 Processing of IP addresses IP addresses can be translated to a geolocation using dictionary lookup. This location can be then treated as a categorical variable. Additionally, the IP addresses can be checked for being well-known proxy servers and being flagged as such (useful for applying one of the rules from 3.1.1) 2.3.3 userAgent flags userAgent values can be parsed to extract information about the presence of particular substrings like “torrent”, “iphone”, “chrome”, etc... and then the corresponding flags “uaTorrent”, “uaIphone”, “uaChrome”, etc... are set to 1. However, the parsing rules might need maintenance as the relevant keywords tend to change with time. 2.3.4 clientRequestPath flags The same as userAgent, but searching for patterns like “login”, “admin”, etc... The records in the dataset are not labeled in terms of “bad” and “good” actors but we assume the dataset can have those labels for supervised modeling approaches in the next section. In this section, several approaches to modeling the anomalous traffic detector are reviewed, from simplest to more advanced considering their pros and cons. 3.1.1 Simple rules set In this trivial detector, a set of rules is applied to each individual record, and alerting happens if, for example: timeMs > X uaTorrent == 1 And the rules’ logic combinations (AND, OR, ...) Pros: Simple to reason about Easy to implement and test Alerts are explainable A reasonably complex ruleset is the fastest option Cons: Hard to maintain, especially when the ruleset becomes complex Is not (quickly) adaptable to changing behavior Might miss non-obvious cases hence potentially low recall 3.1.2 Supervised classification of records This method assumes labels are available for the data and the problem can be framed as a binary classification. Almost all classification models can be applied here having the features (2.1) as an input vector. The models can be something simple like logistic regression as well as complex like neural networks outputting an “anomaly score” between 0 and 1. However, tree ensembles seem like an optimal choice here, combining natural explainability, good expected prediction performance, support of categorical variables without explicit encoding, and acceptable inference speed. The latter is very important if volumes of the data are big. Pros: Classification is a well-known ML problem with many examples of successful applications (Potentially) high detection performance (see cons as well) Most of the models are explainable Cons: Requires labels and the detection quality is only as good as labels’ quality Labels are most probably imbalanced (much less anomalous traffic) which requires applying special measures like undersampling of the majority class, oversampling of the minority class, data augmentation, SMOTE, etc. Requires infrastructure for model (re-)training, validating and storing 3.1.3 Unsupervised anomaly detection High-quality labels are not always available so unsupervised methods might be handy. The anomaly detection methods/models usually learn the most popular patterns in data then predicting the “anomalousness” of new examples. Pros: No need for labels for model training Cons: Labels are still handy for model validation Requires infrastructure for model (re-)training and storing Using time would allow models to continuously adapt to the changing behavior of potential malicious actors but it would require more preprocessing of the data. This preprocessing would be aggregations over a rolling time window and could be done with something like this pseudo-Spark-code: df ... .groupBy(window(col(“timestamp”), 1.minute), col(“ip”)) .agg( count(col(“*”)) as ‘num_reqs, avg(col(“timeMs”)) as ‘avgTimeMs, skew(col(“timeMs”)) as ‘skewTimeMs, count(when(col(“clientRequestPath”).contains(“login”)) as ‘num_logins), ...) Note: the data is grouped by “ip” but it might be better to group by, for example, a combination of country and/or region (decoded from IP address), depending on the use case. With this query, we can transform the data into a set of time series and apply the time series specific methods described below. 3.2.1 Comparing with historical statistics To add adaptability to the rules “model”, we can use the temporal characteristics of the data with the simple rules set modifying the rules like this: currentTimeMs > avgTimeMs + someConstant where “avgTimeMs” is a continuously updated average value of the metric over the last N timestamps. For categorical features, comparing distributions of categorical variables for the current moment of time and some aggregated distribution from the same last N timestamps can be used. Pros: Does not require model (re-)training but still provides adaptability Cons: Needs additional preprocessing step Note: other pros/cons are the same as for simple rules set. 3.2.2 Forecasting time-series for the task of anomaly detection This method would work as follows: based on a certain time window, the model predicts the next value(s) and compares the prediction with the real observation(s). Underlying forecasting methods may vary from something more traditional like SARIMA to deep learning. Probabilistic forecasting is preferred due to factors described in the cons list. Pros: Is a self-supervised method per se so does not requires labels Can be explainable for a case of multivariate forecasting when metrics that fall out of normal values are returned as anomalous, optionally with distance from normality being anomalous score and data columns used for grouping by In the case of probabilistic models like provided in gluon-ts for example, does not require setting thresholds, only percentiles, falling out of which the observation would be considered anomalous Cons: Requires infrastructure for model (re-)training, validating and storing Inference time can be high, especially for probabilistic models Explainable predictions are important for identifying root causes of the detections which might be very useful for debugging and investigating attacks. Therefore, models that are not easily explainable like neural networks are not recommended. In terms of tooling, there is for example SHAP which is one of the best packages for inferring feature importances even from the black-box models. These two repositories are great sources of information on research and tooling for anomaly detection and time-series forecasting: github.com github.com In this document, we reviewed and summarised several options for data preprocessing, feature engineering, and modeling for the task of anomaly detection applied to transactional data. Depending on system requirements, the number of options can be narrowed down: for example if inference time should be microseconds — the deep learning models are most probably out of the game. The feasible options should be then tested offline as well as online and the optimal one identified based on success metric(s) selected at the beginning of the project. The metric can be precision if false alarms are the concern or recall if missed attacks are costly or even some integral metric that can be weighted combination of those two with various metrics like inference time, training time, compute load, cost of error, etc...
[ { "code": null, "e": 755, "s": 172, "text": "Usually, people mean financial transactions when they talk about transactional data. However, according to Wikipedia, “Transactional Data is data describing an event (the change as a result of a transaction) and is usually described with verbs. Transactio...
How to embed images in New Google Sites ? - GeeksforGeeks
10 Sep, 2020 Introduction: Images are very crucial in a well-developed website as they help to display something that even words can’t express. There are two ways to insert an image in Google sites: Through uploading itUsing iframes to insert it Through uploading it Using iframes to insert it If you insert by the first method, there is not much you can edit in it but if you go with the second you can set the size of the image, add a border to it or even create a clickable image. Method 1: First, click on images option from the insert panel. It will ask you to either upload or choose select upload. After that just select the image you want to upload from your PC and your image will get uploaded. Now on this image, you can insert a link, add alternate or caption text or even resize it. Method 2: Select embed option from the insert panel and then go to embed code division of the dialogue box appeared. Write your code in the space provided. To insert a simple image just add the following code: <img src="https://pbs.twimg.com/profile_images/1138375574726955008/1fNUyEdv.png" /> To add height and width to the image just add the following code: <img src="https://pbs.twimg.com/profile_images/1138375574726955008/1fNUyEdv.png" width="300" height="300" /> To add border-style just add the following code: <img src="https://pbs.twimg.com/profile_images/1138375574726955008/1fNUyEdv.png" style="border:4px solid green;" width="300" height="300" /> There are nine different styles of border available, they are – solid, double, groove, dotted, dashed, inset, outset, ridge, hidden. Google Sites Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Front End Developer Skills That You Need in 2022 How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to redirect to another page in ReactJS ? How to Insert Form Data into Database using PHP ? How to pass data from child component to its parent in ReactJS ? How to execute PHP code using command line ? REST API (Introduction)
[ { "code": null, "e": 24551, "s": 24523, "text": "\n10 Sep, 2020" }, { "code": null, "e": 24737, "s": 24551, "text": "Introduction: Images are very crucial in a well-developed website as they help to display something that even words can’t express. There are two ways to insert an ...
A Python AzureML SDK workflow with VSCode devcontainers | by Luuk van der Velden | Towards Data Science
Microsoft is making great strides in conquering our hearts and mingling with the open source Ecosystem. The same ecosystem they openly worked against in the 00s. I confess I am in the process of being assimilated into the Microsoft world and am feeling good about it. In this blog I describe a development workflow for launching ML models in the cloud (AzureML) and developing code in VSCode remotely. See also: Part 2: Unifying remote and local AzureML environments Being fairly late to VSCode it took me by surprise after my usual period of denial. The remote development functionality introduced in Q2 2019 (vscode-dev-blog) really sealed the deal for me. There are three flavors to this: Deploy the VSCode server within the Windows subsystem for Linux (WSL) and run the client on the Windows desktopDeploy the VSCode server within a Docker container and run the client on the Windows desktopDeploy the VSCode server to an SSH target and run the client locally Deploy the VSCode server within the Windows subsystem for Linux (WSL) and run the client on the Windows desktop Deploy the VSCode server within a Docker container and run the client on the Windows desktop Deploy the VSCode server to an SSH target and run the client locally This is very rich functionality which does not disappoint in reliability. Let us take a closer look. Windows subsystem for Linux (WSL) has been around for a number of years. WSL2 unifies running Linux based docker containers and WSL Linux on the same architecture (docker-wsl2-backend). Importantly it removed complex virtualization from the architecture and WSL Linux runs pretty much natively. VSCode can work on code on the windows filesystem and run its server on WSL; integrating seamlessly with Python interpreters and shells. In this blog we suggest running the VSCode server inside a docker container on the WSL2 backend with the GUI running on the Windows desktop. WSL2 is the future and has benefits, such as Windows Home support (docker-windows-home), resource management and the potential for GPU support (WSL2-dev-blog). What we discuss also works on the historic Docker backend. Microsoft provides well maintained Dockerfiles containing common development tools for language and language agnostic scenarios (vscode-dev-containers). We selected the azure-machine-learning-python-3 container (azureml-dev-container), because of its Conda Python interpreter with the azureml-sdk package installed. The image derives from Ubuntu. If we include the “./.devcontainer” folder in any of our projects VSCode will: detect the presence of “./.devcontainer” and its contentsbuild a container from the “./.devcontainer/Dockerfile`install the VSCode server and optional extensions defined in “decontainer.json”run the container as configured in “devcontainer.json”; defining a.o. bind mounts and startup scripts detect the presence of “./.devcontainer” and its contents build a container from the “./.devcontainer/Dockerfile` install the VSCode server and optional extensions defined in “decontainer.json” run the container as configured in “devcontainer.json”; defining a.o. bind mounts and startup scripts The settings for VSCode container integration are stored in “./.devcontainer/devcontainer.json” and allow any Dockerfile to be integrated without alteration. We can add our favorite development tools to these devcontainers as additional layers in the Dockerfile. Or we can build on top of a base image by calling “FROM” in our custom “Dockerfile”. For instance, adding the Azure CLI with extensions and Terraform with “RUN” commands (my-branch). An image with your favorite development environment can be a good companion to have. We can manage our custom image in one place and provide symbolic links to it from each of our projects. Install docker desktop on windowsInstall git for windows (I suggest adding it to powershell during install)Install VSCode and its “Remote — Containers” extensionChange directory to a suitable dev directory (here “dev”) on the windows filesystemgit clone https://github.com/microsoft/vscode-dev-containers/tree/master/containers/azure-machine-learning-python-3within an existing Python project symlink the .devcontainer in Powershell using New-Item -ItemType Junction -Path “c:\dev\path\to\your\project\.devcontainer\” -Target “c:\dev\vscode-dev-containers\containers\azure-machine-learning-python-3\.devcontainer\”Within the project base folder launch vscode with “code .”VSCode detects the “.devcontainer” and asks to re-open in container -> yesVSCode builds the container and installs its server and re-opensConfirm your environment in the lower left corner, a green square says “Dev Container: Azure Machine Learning” Install docker desktop on windows Install git for windows (I suggest adding it to powershell during install) Install VSCode and its “Remote — Containers” extension Change directory to a suitable dev directory (here “dev”) on the windows filesystem git clone https://github.com/microsoft/vscode-dev-containers/tree/master/containers/azure-machine-learning-python-3 within an existing Python project symlink the .devcontainer in Powershell using New-Item -ItemType Junction -Path “c:\dev\path\to\your\project\.devcontainer\” -Target “c:\dev\vscode-dev-containers\containers\azure-machine-learning-python-3\.devcontainer\” Within the project base folder launch vscode with “code .” VSCode detects the “.devcontainer” and asks to re-open in container -> yes VSCode builds the container and installs its server and re-opens Confirm your environment in the lower left corner, a green square says “Dev Container: Azure Machine Learning” We can develop using fully reproducible Linux tool chains and still work on a windows laptop. This is probably not convincing to a Linux or MacOS user, but if you become comfortable with these tools you will have them available almost anywhere. This is valuable if you work for companies that provide you with the infrastructure and a laptop. Another scenario would be training deep learning models with GPUs with your gaming desktop windows computer, as GPU support for WSL2 has been announced (WSL2-dev-blog). A prerequisite for this section is an active Azure subscription. You can easily get a free azure account with starting credits, if you can get hold of a credit card. Our VSCode runs within a devcontainer featuring Python and the AzureML Python SDK. The SDK contains an elaborate API spanning the entire lifecycle of an ML model. From exploration in notebooks, training and tracking the model to artifact management and deployment. This includes the provisioning and configuration of the compute for model training and the deployment targets for model scoring. Some of the tools (Azure CLI) I will reference were added in my own fork (my-branch). The following diagram shows the workflow we are aiming at. We launch an experiment from VSCode using the AzureML SDK inside our devcontainer and the SDK executes our code on the compute target. The compute target runs our code within a docker container as well. The specifics of the runtime environment are discussed in part 2/2 of this blog. Open a terminal in VSCode: menu Terminal -> New TerminalExecute “az login” on the shell. Go to www.microsoft.com/devicelogin and fill in the secret provided in the console outputWe have now linked our environment with an Azure subscriptionThe account information is stored in “~/.azure/azureProfile.json” within the container. Open a terminal in VSCode: menu Terminal -> New Terminal Execute “az login” on the shell. Go to www.microsoft.com/devicelogin and fill in the secret provided in the console output We have now linked our environment with an Azure subscription The account information is stored in “~/.azure/azureProfile.json” within the container. Let us look at Python AzureML SDK code to: Create an AzureML WorkspaceCreate a compute cluster as a training targetRun a Python script on the compute target Create an AzureML Workspace Create a compute cluster as a training target Run a Python script on the compute target An AzureML workspace consists of a storage account, a docker image registry and the actual workspace with a rich UI on portal.azure.com. A new related Machine Learning studio is in open Beta and looks really good (https://ml.azure.com). The following code creates the workspace and its required services and attaches them to a new resource group. from azureml.core import Workspaceworkspace = Workspace.create( name="learnml", subscription_id="<UUID>", resource_group="ml", create_resource_group=True, location="<location>", sku="basic",) We need compute resources to train our ML model. We can create, orchestrate the compute clusters using the AzureML Python SDK. The workspace to create the resources in is defined by config.json file in the working directory (configure-workspace). AmlCompute stands for Azure Machine Learning Compute and it is the configuration class for the cluster. If the cluster does not exist we create one scaling from 0 to a defined maximum number of virtual machines (VMs). These VMs are running docker. We pass the provisioning configuration to the create method of the ComputeTarget class, which returns a ComputeTarget object. This object is used whenever we want to perform computations. The following code can be wrapped into a function to get the compute_target. from azureml.core import Workspacefrom azureml.core.compute import AmlCompute, ComputeTargetfrom azureml.core.compute_target import ComputeTargetExceptionCLUSTER_NAME = "cpucluster"VM_SIZE = "Standard_D2_V2"MAX_NODES = 1workspace = Workspace.from_config() # local config.json with subscription info# retrieve existing cluster or create a new onetry: cpu_cluster = ComputeTarget(workspace=workspace, name=CLUSTER_NAME) print("Found existing cluster, use it.")except ComputeTargetException: compute_config = AmlCompute.provisioning_configuration( vm_size=VM_SIZE, max_nodes=MAX_NODES )cpu_cluster = ComputeTarget.create(workspace, CLUSTER_NAME, compute_config) We want to run a Python script on our compute cluster. In part 2/2 of this series we will go into configuring the runtime Environment in detail. Here we show the minimum code needed to run a Pyton script on a compute_target (amlcompute-docs). from azureml.core import Experiment, RunConfiguration, ScriptRunConfig, Workspacefrom tools import get_compute_targetCLUSTER_NAME = "cpucluster"EXPERIMENT_FOLDER = "/workspaces/azureml/code"workspace = Workspace.from_config()# get_compute_cluster wraps the code under section 2.2.2cpu_cluster = get_compute_target(workspace, CLUSTER_NAME)# Create a new runconfig objectrun_amlcompute = RunConfiguration()"""Skipping Environment details, treated in Blog Part 2/2, code is still valid"""# Set the compute target for the runrun_amlcompute.target = cpu_cluster# Create a script configscript_config = ScriptRunConfig( source_directory=EXPERIMENT_FOLDER, script="run_experiment.py", run_config=run_amlcompute,)# Submit the experimentexperiment = Experiment(workspace=workspace, name="my-experiment")run = experiment.submit(config=script_config) We have seen how easy it is to create an Azure ML workspace, spinning up a compute cluster and running a Python script on it. All this is tracked as an experiment within the ML studio. Microsoft is all-in on Machine Learning and Python and this shows. For our workflow we have added Docker/WSL2 into the mix. From a developer perspective it is important that all the pieces work together reliably to allow actual work getting done. I am impressed with the quality of the various parts of the eco-system: Docker/WSL2, VSCode and AzureML and their integration into a workflow. Of course, there are some pitfalls along the way which are summarized below. File permission mapping between Linux and Windows filesystem is odd (wsl-chmod-dev-blog); Bind mounts are under root:root Crontab users might have to touch windows Task Scheduler (wsl-scheduling) GPU support is on the way but not there yet (2020) Linux GUI application is on the roadmap but not there yet (2021) Originally published at https://codebeez.nl.
[ { "code": null, "e": 573, "s": 171, "text": "Microsoft is making great strides in conquering our hearts and mingling with the open source Ecosystem. The same ecosystem they openly worked against in the 00s. I confess I am in the process of being assimilated into the Microsoft world and am feeling go...
Compare date strings in MySQL
To compare date strings, use STR_TO_DATE() from MySQL. Let us first create a table − mysql> create table DemoTable712 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, ArrivalDate varchar(100) ); Query OK, 0 rows affected (0.65 sec) Insert some records in the table using insert command − mysql> insert into DemoTable712(ArrivalDate) values('10.01.2019'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable712(ArrivalDate) values('11.12.2018'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable712(ArrivalDate) values('01.11.2017'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable712(ArrivalDate) values('20.06.2016'); Query OK, 1 row affected (0.23 sec) Display all records from the table using select statement − mysql> select *from DemoTable712; This will produce the following output - +----+-------------+ | Id | ArrivalDate | +----+-------------+ | 1 | 10.01.2019 | | 2 | 11.12.2018 | | 3 | 01.11.2017 | | 4 | 20.06.2016 | +----+-------------+ 4 rows in set (0.00 sec) Following is the query to compare date strings − mysql> select *from DemoTable712 where str_to_date(ArrivalDate,'%d.%m.%Y')='2017-11-01'; This will produce the following output - +----+-------------+ | Id | ArrivalDate | +----+-------------+ | 3 | 01.11.2017 | +----+-------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1117, "s": 1062, "text": "To compare date strings, use STR_TO_DATE() from MySQL." }, { "code": null, "e": 1147, "s": 1117, "text": "Let us first create a table −" }, { "code": null, "e": 1297, "s": 1147, "text": "mysql> create table DemoTa...
Make a palindromic string from given string - GeeksforGeeks
11 Aug, 2021 Given a string S consisting of lower-case English alphabets only, we have two players playing the game. The rules are as follows: The player can remove any character from the given string S and write it on paper on any side(left or right) of an empty string. The player wins the game, if at any move he can get a palindromic string first of length > 1. If a palindromic string cannot be formed, Player-2 is declared the winner. Both play optimally with player-1 starting the game. The task is to find the winner of the game. Examples: Input: S = “abc” Output: Player-2 Explanation: There are all unique characters due to which there is no way to form a palindromic string of length > 1 Input: S = “abccab” Output: Player-2 Explanation: Initially, newString = “” is empty. Let Player-1 choose character ‘a’ and write it on paper. Then, S = “bccab” and newString = “a”. Now Player-2 chooses character ‘a’ from S and writes it on the left side of newString. Thus, S = “bccb” and newString = “aa”. Now, newString = “aa” is a palindrome of length 2. Hence, Player-2 wins. Approach: The idea is to formulate a condition in which Player-1 is always going to be the winner. If the condition fails, then Player-2 will win the game. If there is only one unique character occurring once in the given string, and the rest of the characters occurring more than 1, then Player-1 is going to be the winner, else Player-2 will always win. If we have all characters that are occurring more than once in the given string, then Player-2 can always copy the Player-1 move in his first turn and wins. Also, if we have more than one character in the string occurring one time only, then a palindrome string can never be formed(in the optimal case). Hence, again, Player-2 wins. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Implementation to find// which player can form a palindromic// string first in a game #include <bits/stdc++.h> using namespace std; // Function to find// winner of the gameint palindromeWinner(string& S){ // Array to Maintain frequency // of the characters in S int freq[26]; // Initialise freq array with 0 memset(freq, 0, sizeof freq); // Maintain count of all // distinct characters int count = 0; // Finding frequency of each character for (int i = 0; i < (int)S.length(); ++i) { if (freq[S[i] - 'a'] == 0) count++; freq[S[i] - 'a']++; } // Count unique duplicate // characters int unique = 0; int duplicate = 0; // Loop to count the unique // duplicate characters for (int i = 0; i < 26; ++i) { if (freq[i] == 1) unique++; else if (freq[i] >= 2) duplicate++; } // Condition for Player-1 // to be winner if (unique == 1 && (unique + duplicate) == count) return 1; // Else Player-2 is // always winner return 2;} // Driven Codeint main(){ string S = "abcbc"; // Function call cout << "Player-" << palindromeWinner(S) << endl; return 0;} // Java implementation to find which// player can form a palindromic// string first in a gameimport java.util.*; class GFG{ // Function to find// winner of the gamestatic int palindromeWinner(String S){ // Array to maintain frequency // of the characters in S int freq[] = new int[26]; // Initialise freq array with 0 Arrays.fill(freq, 0); // Maintain count of all // distinct characters int count = 0; // Finding frequency of each character for(int i = 0; i < (int)S.length(); ++i) { if (freq[S.charAt(i) - 'a'] == 0) count++; freq[S.charAt(i) - 'a']++; } // Count unique duplicate // characters int unique = 0; int duplicate = 0; // Loop to count the unique // duplicate characters for(int i = 0; i < 26; ++i) { if (freq[i] == 1) unique++; else if (freq[i] >= 2) duplicate++; } // Condition for Player-1 // to be winner if (unique == 1 && (unique + duplicate) == count) return 1; // Else Player-2 is // always winner return 2;} // Driver Codepublic static void main(String s[]){ String S = "abcbc"; // Function call System.out.println("Player-" + palindromeWinner(S));}} // This code is contributed by rutvik_56 # Python3 implementation to find# which player can form a palindromic# string first in a game # Function to find# winner of the gamedef palindromeWinner(S): # Array to Maintain frequency # of the characters in S # initialise freq array with 0 freq = [0 for i in range(0, 26)] # Maintain count of all # distinct characters count = 0 # Finding frequency of each character for i in range(0, len(S)): if (freq[ord(S[i]) - 97] == 0): count += 1 freq[ord(S[i]) - 97] += 1 # Count unique duplicate # characters unique = 0 duplicate = 0 # Loop to count the unique # duplicate characters for i in range(0, 26): if (freq[i] == 1): unique += 1 elif (freq[i] >= 2): duplicate += 1 # Condition for Player-1 # to be winner if (unique == 1 and (unique + duplicate) == count): return 1 # Else Player-2 is # always winner return 2 # Driven CodeS = "abcbc"; # Function callprint("Player-", palindromeWinner(S)) # This code is contributed by Sanjit_Prasad // C# implementation to find which// player can form a palindromic// string first in a gameusing System;class GFG{ // Function to find// winner of the gamestatic int palindromeWinner(string S){ // Array to maintain frequency // of the characters in S int[] freq = new int[26]; // Maintain count of all // distinct characters int count = 0; // Finding frequency of // each character for (int i = 0; i < (int)S.Length; ++i) { if (freq[S[i] - 'a'] == 0) count++; freq[S[i] - 'a']++; } // Count unique duplicate // characters int unique = 0; int duplicate = 0; // Loop to count the unique // duplicate characters for (int i = 0; i < 26; ++i) { if (freq[i] == 1) unique++; else if (freq[i] >= 2) duplicate++; } // Condition for Player-1 // to be winner if (unique == 1 && (unique + duplicate) == count) return 1; // Else Player-2 is // always winner return 2;} // Driver Codepublic static void Main(string[] s){ string S = "abcbc"; // Function call Console.Write("Player-" + palindromeWinner(S));}} // This code is contributed by Chitranayal <script>// Javascript implementation to find which// player can form a palindromic// string first in a game // Function to find// winner of the gamefunction palindromeWinner(S){ // Array to maintain frequency // of the characters in S let freq = new Array(26); // Initialise freq array with 0 for(let i=0;i<26;i++) { freq[i]=0; } // Maintain count of all // distinct characters let count = 0; // Finding frequency of each character for(let i = 0; i < S.length; ++i) { if (freq[S[i].charCodeAt(0) - 'a'.charCodeAt(0)] == 0) count++; freq[S[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // Count unique duplicate // characters let unique = 0; let duplicate = 0; // Loop to count the unique // duplicate characters for(let i = 0; i < 26; ++i) { if (freq[i] == 1) unique++; else if (freq[i] >= 2) duplicate++; } // Condition for Player-1 // to be winner if (unique == 1 && (unique + duplicate) == count) return 1; // Else Player-2 is // always winner return 2;} // Driver Codelet S = "abcbc";// Function calldocument.write("Player-" + palindromeWinner(S)); // This code is contributed by avanitrachhadiya2155</script> Player-1 Time Complexity: O(N) Sanjit_Prasad rutvik_56 ukasp avanitrachhadiya2155 singghakshay palindrome Game Theory Greedy Strings Strings Greedy Game Theory palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find winner in game of N balls, in which a player can remove any balls in range [A, B] in a single move Find winner when players remove multiples of A or B from Array in each turn Classification of Algorithms with Examples Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number Find the player who will win by choosing a number in range [1, K] with sum total N Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Program for array rotation Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 24869, "s": 24841, "text": "\n11 Aug, 2021" }, { "code": null, "e": 25001, "s": 24869, "text": "Given a string S consisting of lower-case English alphabets only, we have two players playing the game. The rules are as follows: " }, { "code": null, ...
Decision Tree in Machine Learning | by Prince Yadav | Towards Data Science
A decision tree is a flowchart-like structure in which each internal node represents a test on a feature (e.g. whether a coin flip comes up heads or tails) , each leaf node represents a class label (decision taken after computing all features) and branches represent conjunctions of features that lead to those class labels. The paths from root to leaf represent classification rules. Below diagram illustrate the basic flow of decision tree for decision making with labels (Rain(Yes), No Rain(No)). Decision tree is one of the predictive modelling approaches used in statistics, data mining and machine learning. Decision trees are constructed via an algorithmic approach that identifies ways to split a data set based on different conditions. It is one of the most widely used and practical methods for supervised learning. Decision Trees are a non-parametric supervised learning method used for both classification and regression tasks. Tree models where the target variable can take a discrete set of values are called classification trees. Decision trees where the target variable can take continuous values (typically real numbers) are called regression trees. Classification And Regression Tree (CART) is general term for this. Throughout this post i will try to explain using the examples. Data comes in records of forms. (x,Y)=(x1,x2,x3,....,xk,Y) The dependent variable, Y, is the target variable that we are trying to understand, classify or generalize. The vector x is composed of the features, x1, x2, x3 etc., that are used for that task. Example training_data = [ ['Green', 3, 'Apple'], ['Yellow', 3, 'Apple'], ['Red', 1, 'Grape'], ['Red', 1, 'Grape'], ['Yellow', 3, 'Lemon'], ] # Header = ["Color", "diameter", "Label"] # The last column is the label. # The first two columns are features. While making decision tree, at each node of tree we ask different type of questions. Based on the asked question we will calculate the information gain corresponding to it. Information gain is used to decide which feature to split on at each step in building the tree. Simplicity is best, so we want to keep our tree small. To do so, at each step we should choose the split that results in the purest daughter nodes. A commonly used measure of purity is called information. For each node of the tree, the information value measures how much information a feature gives us about the class. The split with the highest information gain will be taken as the first split and the process will continue until all children nodes are pure, or until the information gain is 0. class Question: """A Question is used to partition a dataset. This class just records a 'column number' (e.g., 0 for Color) and a 'column value' (e.g., Green). The 'match' method is used to compare the feature value in an example to the feature value stored in the question. See the demo below. """ def __init__(self, column, value): self.column = column self.value = value def match(self, example): # Compare the feature value in an example to the # feature value in this question. val = example[self.column] if is_numeric(val): return val >= self.value else: return val == self.value def __repr__(self): # This is just a helper method to print # the question in a readable format. condition = "==" if is_numeric(self.value): condition = ">=" return "Is %s %s %s?" % ( header[self.column], condition, str(self.value)) Lets try querying questions and its outputs. Question(1, 3) ## Is diameter >= 3?Question(0, "Green") ## Is color == Green? Now we will try to Partition the dataset based on asked question. Data will be divided into two classes at each steps. def partition(rows, question): """Partitions a dataset. For each row in the dataset, check if it matches the question. If so, add it to 'true rows', otherwise, add it to 'false rows'. """ true_rows, false_rows = [], [] for row in rows: if question.match(row): true_rows.append(row) else: false_rows.append(row) return true_rows, false_rows # Let's partition the training data based on whether rows are Red. true_rows, false_rows = partition(training_data, Question(0, 'Red')) # This will contain all the 'Red' rows. true_rows ## [['Red', 1, 'Grape'], ['Red', 1, 'Grape']] false_rows ## [['Green', 3, 'Apple'], ['Yellow', 3, 'Apple'], ['Yellow', 3, 'Lemon']] Algorithm for constructing decision tree usually works top-down, by choosing a variable at each step that best splits the set of items. Different algorithms use different metrices for measuring best. First let’s understand the meaning of Pure and Impure. Pure means, in a selected sample of dataset all data belongs to same class (PURE). Impure means, data is mixture of different classes. Gini Impurity is a measurement of the likelihood of an incorrect classification of a new instance of a random variable, if that new instance were randomly classified according to the distribution of class labels from the data set. If our dataset is Pure then likelihood of incorrect classification is 0. If our sample is mixture of different classes then likelihood of incorrect classification will be high. Calculating Gini Impurity. def gini(rows): """Calculate the Gini Impurity for a list of rows. There are a few different ways to do this, I thought this one was the most concise. See: https://en.wikipedia.org/wiki/Decision_tree_learning#Gini_impurity """ counts = class_counts(rows) impurity = 1 for lbl in counts: prob_of_lbl = counts[lbl] / float(len(rows)) impurity -= prob_of_lbl**2 return impurity Example # Demo 1: # Let's look at some example to understand how Gini Impurity works. # # First, we'll look at a dataset with no mixing. no_mixing = [['Apple'], ['Apple']] # this will return 0 gini(no_mixing) ## output=0 ## Demo 2: # Now, we'll look at dataset with a 50:50 apples:oranges ratio some_mixing = [['Apple'], ['Orange']] # this will return 0.5 - meaning, there's a 50% chance of misclassifying # a random example we draw from the dataset. gini(some_mixing) ##output=0.5 ## Demo 3: # Now, we'll look at a dataset with many different labels lots_of_mixing = [['Apple'], ['Orange'], ['Grape'], ['Grapefruit'], ['Blueberry']] # This will return 0.8 gini(lots_of_mixing) ##output=0.8 ####### Get list of rows (dataset) which are taken into consideration for making decision tree (recursively at each nodes). Calculate uncertanity of our dataset or Gini impurity or how much our data is mixed up etc. Generate list of all question which needs to be asked at that node. Partition rows into True rows and False rows based on each question asked. Calculate information gain based on gini impurity and partition of data from previous step. Update highest information gain based on each question asked. Update best question based on information gain (higher information gain). Divide the node on best question. Repeat again from step 1 again until we get pure node (leaf nodes). Code for Above Steps def find_best_split(rows): """Find the best question to ask by iterating over every feature / value and calculating the information gain.""" best_gain = 0 # keep track of the best information gain best_question = None # keep train of the feature / value that produced it current_uncertainty = gini(rows) n_features = len(rows[0]) - 1 # number of columns for col in range(n_features): # for each feature values = set([row[col] for row in rows]) # unique values in the column for val in values: # for each value question = Question(col, val) # try splitting the dataset true_rows, false_rows = partition(rows, question) # Skip this split if it doesn't divide the # dataset. if len(true_rows) == 0 or len(false_rows) == 0: continue # Calculate the information gain from this split gain = info_gain(true_rows, false_rows, current_uncertainty) # You actually can use '>' instead of '>=' here # but I wanted the tree to look a certain way for our # toy dataset. if gain >= best_gain: best_gain, best_question = gain, question return best_gain, best_question ####### # Demo: # Find the best question to ask first for our toy dataset. best_gain, best_question = find_best_split(training_data) best_question ## output - Is diameter >= 3? Now build the Decision tree based on step discussed above recursively at each node. def build_tree(rows): """Builds the tree. Rules of recursion: 1) Believe that it works. 2) Start by checking for the base case (no further information gain). 3) Prepare for giant stack traces. """ # Try partitioning the dataset on each of the unique attribute, # calculate the information gain, # and return the question that produces the highest gain. gain, question = find_best_split(rows) # Base case: no further info gain # Since we can ask no further questions, # we'll return a leaf. if gain == 0: return Leaf(rows) # If we reach here, we have found a useful feature / value # to partition on. true_rows, false_rows = partition(rows, question) # Recursively build the true branch. true_branch = build_tree(true_rows) # Recursively build the false branch. false_branch = build_tree(false_rows) # Return a Question node. # This records the best feature / value to ask at this point, # as well as the branches to follow # dependingo on the answer. return Decision_Node(question, true_branch, false_branch) Let’s build decision tree based on training data. training_data = [ ['Green', 3, 'Apple'], ['Yellow', 3, 'Apple'], ['Red', 1, 'Grape'], ['Red', 1, 'Grape'], ['Yellow', 3, 'Lemon'], ] # Header = ["Color", "diameter", "Label"] # The last column is the label. # The first two columns are features. my_tree = build_tree(training_data) print_tree(my_tree) Output Is diameter >= 3? --> True: Is color == Yellow? --> True: Predict {'Lemon': 1, 'Apple': 1} --> False: Predict {'Apple': 1} --> False: Predict {'Grape': 2} From above output we can see that at each steps data is divided into True and False rows. This process keep repeated until we reach leaf node where information gain is 0 and further split of data is not possible as nodes are Pure. Advantage of Decision Tree Easy to use and understand. Can handle both categorical and numerical data. Resistant to outliers, hence require little data preprocessing. Disadvantage of Decision Tree Prone to overfitting. Require some kind of measurement as to how well they are doing. Need to be careful with parameter tuning. Can create biased learned trees if some classes dominate. Overfitting is one of the major problem for every model in machine learning. If model is overfitted it will poorly generalized to new samples. To avoid decision tree from overfitting we remove the branches that make use of features having low importance. This method is called as Pruning or post-pruning. This way we will reduce the complexity of tree, and hence imroves predictive accuracy by the reduction of overfitting. Pruning should reduce the size of a learning tree without reducing predictive accuracy as measured by a cross-validation set. There are 2 major Pruning techniques. Minimum Error: The tree is pruned back to the point where the cross-validated error is a minimum. Smallest Tree: The tree is pruned back slightly further than the minimum error. Technically the pruning creates a decision tree with cross-validation error within 1 standard error of the minimum error. An alternative method to prevent overfitting is to try and stop the tree-building process early, before it produces leaves with very small samples. This heuristic is known as early stopping but is also sometimes known as pre-pruning decision trees. At each stage of splitting the tree, we check the cross-validation error. If the error does not decrease significantly enough then we stop. Early stopping may underfit by stopping too early. The current split may be of little benefit, but having made it, subsequent splits more significantly reduce the error. Early stopping and pruning can be used together, separately, or not at all. Post pruning decision trees is more mathematically rigorous, finding a tree at least as good as early stopping. Early stopping is a quick fix heuristic. If used together with pruning, early stopping may save time. After all, why build a tree only to prune it back again? Selecting a flight to travel Suppose you need to select a flight for your next travel. How do we go about it? We check first if the flight is available on that day or not. If it is not available, we will look for some other date but if it is available then we look for may be the duration of the flight. If we want to have only direct flights then we look whether the price of that flight is in your pre-defined budget or not. If it is too expensive, we look at some other flights else we book it! Handling late night cravings There are many more application of decision tree in real life. You can check this and this for more applications of decision tree. From this article i tried to explains basics of decision tree and how basically it works. You can find the source code used in this article at github. Hope you liked this article. For any changes, suggestion please message me directly on this article or on LinkedIn. Happy Learning — Cheers :)
[ { "code": null, "e": 672, "s": 172, "text": "A decision tree is a flowchart-like structure in which each internal node represents a test on a feature (e.g. whether a coin flip comes up heads or tails) , each leaf node represents a class label (decision taken after computing all features) and branche...
Bash Scripting - How to Run Bash Scripting in Terminal - GeeksforGeeks
28 Nov, 2021 In this article, we are going to see how to run bash script in terminal. For example, we create a bash file set of instructions or commands ( known as bash script ), and through command, we can run this file in terminal. Let see how to run bash script in terminal. Example 1 : In this example we print or echo some text on screen with the help of a terminal. $ echo "Geeks For Geeks" Output : Print the text using echo command Note : ” echo” this command will display the text on screen. Example 2 : In this example, we print the date of command execution with the help of terminal. $ date Print date using date command in terminal Example 3 : In this example, we will see that how to run a bash script file through a terminal. First, create a bash file named ” welcome.sh ” by the following command. $ touch welcome.sh Here, you can see that the file name is ” welcome.sh “. Whenever you create a bash script file use “.sh ” extension. Note : ” touch “ is used to create file. Now to write bash script, we should open this file in text editor using terminal. $ nano welcome.sh Note : ” nano ” is used to open file in text editor ( i.e. GNU nano ) Now, the text editor is opened. Write the following bash script into ” welcome.sh “ #!/bin/sh echo "Enter Your Name : " read name echo "Hello $name ! Welcome to our Geeks for Geeks site." Note : Where, #! : It is known as shebang. /bin/sh : It is executable path of the system shell. read : It will read the data from user. Now, save and run this file using terminal. $ chmod +x ./welcome.sh $ ./welcome.sh Note : Where, chmod +x : It is used to make file executable. ./welcome : Here, “./” will run the bash script file. Output : Output Of above bash script Here, we can see clearly that how to run bash script in terminal. Bash-Script Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Named Pipe or FIFO with example C program Thread functions in C/C++ SED command in Linux | Set 2 Array Basics in Shell Scripting | Set 1 Introduction to Linux Shell and Shell Scripting Linux system call in Detail Looping Statements | Shell Script chown command in Linux with Examples mv command in Linux with examples Basic Shell Commands in Linux
[ { "code": null, "e": 24326, "s": 24298, "text": "\n28 Nov, 2021" }, { "code": null, "e": 24547, "s": 24326, "text": "In this article, we are going to see how to run bash script in terminal. For example, we create a bash file set of instructions or commands ( known as bash script ...
Reading and displaying images using OpenCV
In this article, we will learn how to read and display images using the OpenCV library. OpenCV is a library of programming functions mainly aimed at real time computer vision. Before reading an image, make sure that the image is in the same directory as your program. Step 1: Import OpenCV. Step 2: Read an image using imread(). Step 3: Display the image using imshow(). import cv2 as cv image = cv.imread ('ronaldo.jpg') cv.imshow('Cristiano Ronaldo', image)
[ { "code": null, "e": 1150, "s": 1062, "text": "In this article, we will learn how to read and display images using the OpenCV library." }, { "code": null, "e": 1330, "s": 1150, "text": "OpenCV is a library of programming functions mainly aimed at real time computer vision. Before...
Python | os.uname() method - GeeksforGeeks
20 May, 2019 os.uname() method in python is used to get information about current operating system. This method returns information like name, release and version of current operating system, name of machine on network and hardware identifier in the form of attributes of a tuple-like object. Syntax: os.uname() Parameters: Not required Return Type: This method returns a tuple-like object which has five attributes: sysname – operating system name nodename – name of machine on network (implementation-defined) release – operating system release version – operating system version machine – hardware identifier Code #1: use of os.uname() method # Python program to explain os.uname() method # importing os module import os # Get the information of current# operating systemos_info = os.uname() # print the informationprint(os_info) posix.uname_result(sysname='Linux', nodename='pppContainer', release='4.4.0-1075-aws', version='#85-Ubuntu SMP Thu Jan 17 17:15:12 UTC 2019', machine='x86_64') python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Python | Get dictionary keys as a list Bar Plot in Matplotlib Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method loops in python Python - Call function from another file Ways to filter Pandas DataFrame by column values Python | Convert set into a list Python program to find number of days between two given dates
[ { "code": null, "e": 23901, "s": 23873, "text": "\n20 May, 2019" }, { "code": null, "e": 24181, "s": 23901, "text": "os.uname() method in python is used to get information about current operating system. This method returns information like name, release and version of current op...
Cerner Interview Experience | On-Campus 2020 (Virtual) - GeeksforGeeks
16 Nov, 2020 The Hiring process of Cerner consisted of 4 rounds and the eligibility criteria was a minimum CGPA of 8.0, and they offered the role of Software Engineer and the job location is Bangalore. Round 1(Verbal & Aptitude): Aptitude: 30 Aptitude questions to be solved in 40 minutes MCQ’s. Questions spanned various topics such as: Time, Speed, and Work: https://www.geeksforgeeks.org/work-and-wages/Ratio and Proportion: https://www.geeksforgeeks.org/ratio-and-proportion-gq/ Partnership: https://www.geeksforgeeks.org/ratio-proportion-and-partnership/Percentages: https://www.geeksforgeeks.org/percentages/2 puzzle based questions were also present Time, Speed, and Work: https://www.geeksforgeeks.org/work-and-wages/ Ratio and Proportion: https://www.geeksforgeeks.org/ratio-and-proportion-gq/ Partnership: https://www.geeksforgeeks.org/ratio-proportion-and-partnership/ Percentages: https://www.geeksforgeeks.org/percentages/ 2 puzzle based questions were also present Verbal: 20 questions to be solved in 20 minutes. Questions were mostly general and included : Error DetectionPassage Based Fill in the blanks Error Detection Passage Based Fill in the blanks Note: No negative marking in both verbal and aptitude. Result: Qualified Round 2(Coding): Cerner’s style of conducting coding round was probably the best I have come across in the entire placement season. This was not a usual coding round wherein a problem would be given and you need to solve it, pass multiple test cases, and then scored on the basis of it. They followed a unique method as mentioned below. The process of the second round was as if you were speaking to an interviewer, but in this case, your camera is your interviewer. 7 questions would flash on the screen and you need to record your answer within a stipulated time period. Basically, THINK ALOUD. They were trying to understand how you were approaching a problem. Questions 1: I was asked to discuss a problem that I faced during my projects and the way in which I handled in order to overcome it Questions 2: A problem was given, and I was expected to discuss the way I would approach it Questions 3: I had to implement my mentioned solution in an editor. Questions 4: Don’t worry if you were not able to solve it, because question 4 is about the mistakes you made. Suppose your code did not pass the test cases, you were expected to identify the mistakes and rectify them and if it had passed the test cases, then good for you ! Questions 5,6 AND 7 ARE SAME AS 2,3 AND 4 with a different problem altogether. So basically 2 Programming Questions which primarily focuses on the way you think to arrive at a solution. Sample: Given an array of real numbers in an unsorted manner, find the number of ways in choosing 4 numbers such that their sum results in 0. Input: [1,2,3,-6,-1,-2] Output: 2 [ (1,2,3,-6) AND (1,2,-1,-2) ] Note: You can record your answer only once for every question. No retakes! Result: Qualified Round 3(Technical + HR Interview): Since the videos of around 80-100 students had to be scrutinized, my interview call letter came after almost 3 weeks and around 30 students were shortlisted for the interview. My interviewer began the interview by discussing the approaches I made for various problems during round 2. Logic, Time complexities, and Space complexities were discussed in detail. My Interviewer had actually analyzed my submissions from round 2 and had also gone through my resume thoroughly before interviewing me, and I was actually surprised to know it. He then directly jumped into the technical questions which were mostly from Java and OOPS concepts as I had mentioned Android, Data Structures and Cloud computing as my areas of interest. These were some questions from the interview : Explain every term in “public static void main ( String args[] )”Explain the term “System.out.println();”How is a java program compiled and runExplain about JVMExplain the various OOPS conceptsDifference between Run-time Polymorphism and Compile-time PolymorphismHow would you achieve Multiple Inheritance in Java? Explain every term in “public static void main ( String args[] )” Explain the term “System.out.println();” How is a java program compiled and run Explain about JVM Explain the various OOPS concepts Difference between Run-time Polymorphism and Compile-time Polymorphism How would you achieve Multiple Inheritance in Java? Reference: https://www.geeksforgeeks.org/java/ I answered all the questions up to this point and the interviewer was happy with my answers. Then finally, he asked a programming question which is as follows : Given an array of numbers in Arithmetic progression, one number would be missing in that array. Find that number. This was a pretty easy question and I explained my logic clearly, and he was happy with it but while implementing the solution, out of nervousness, I made a blunder in indexing, and even after guidance from my interviewer, I happened to make 2 more mistakes and I was not able to produce the desired output. He also fired a couple of usual HR Questions and my interview lasted a total of 90 minutes and told that further communication would be initiated by the company. Result: Qualified 20 students were selected from across all 3 campuses for the role of Software Engineer. Apparently, my interview did not end there. Since the Interviewer felt that I was pretty good with my knowledge of Java, he had actually recommended 3 people for the role of Systems Engineers and I was one of them. I was informed this news by the Company’s HR team 3 days after the results of Software Engineer were published. I had to attend another technical Interview for the role of Systems Engineers and this role demanded knowledge of Java, Operating Systems, and SQL. Unlike the first technical interview, this interview lasted just 20 minutes and the following questions were asked : What is an AMI (Cloud Computing)How does S3 work and what are the other storage services you are aware ofWrite a query to concatenate First Name and Last Name from a Table.Write a query to display the second highest salary in a particular departmentBasic Java questions and HR questions What is an AMI (Cloud Computing) How does S3 work and what are the other storage services you are aware of Write a query to concatenate First Name and Last Name from a Table. Write a query to display the second highest salary in a particular department Basic Java questions and HR questions Result: Qualified Round 4 (Versant Speaking & Written skills Test): This round is to check our fluency in speaking and writing skills in English. This was pretty much a basic test and you need to score a minimum cut-off to clear this round. Refer to the below-mentioned link on how the test would look like. https://youtu.be/w3mUDKaoNC4 Result: Qualified And finally, 2 days later, the results were announced, and I was Selected as a Systems Engineer and was offered an Intern and Full-time offer at Cerner. Cerner Marketing On-Campus Interview Experiences Cerner Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience for SDE-1 (On-Campus) Amazon Interview Experience for SDE-1 Infosys Interview Experience for DSE - System Engineer | On-Campus 2022 Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Amazon Interview Experience for SDE-1(Off-Campus) Amazon Interview Experience (Off-Campus) 2022 Oracle Interview Experience | Set 69 (Application Engineer) Amazon Interview Experience for SDE-1 Microsoft Interview Experience for SDE-1 (Hyderabad)
[ { "code": null, "e": 24663, "s": 24635, "text": "\n16 Nov, 2020" }, { "code": null, "e": 24852, "s": 24663, "text": "The Hiring process of Cerner consisted of 4 rounds and the eligibility criteria was a minimum CGPA of 8.0, and they offered the role of Software Engineer and the j...
Tryit Editor v3.7
Tryit: The transition property
[]
Adding Pagination in APIs - Django REST Framework - GeeksforGeeks
16 Mar, 2021 Imagine you have huge amount of details in your database. Do you think that it is wise to retrieve all at once while making an HTTP GET request? Here comes the importance of the Django REST framework pagination feature. It facilitates splitting the large result set into individual pages of data for each HTTP request. So when we make an HTTP request, we must specify the details for the specific pages that we want to retrieve, and it will be based on predefined pagination schemes. Apart from retrieving data as pages, it also provides information about the total number of data, the next page, and the previous one in the response section. PageNumberPagination LimitOffsetPagination CursorPagination Note: You can refer The Browsable API section for Models, Serializers, and Views of Project used in the article The PageNumberPagination style accepts a single number page number in the request query parameters. To enable this pagination style globally, you can set rest_framework.pagination.PageNumberPagination class to DEFAULT_PAGINATION_CLASS and also set the PAGE_SIZE as desired. You can open the settings.py file and add the below configuration settings. Python3 REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2,} You can also modify the pagination style by overriding the attributes included in the PageNumberPagination class. Let’s look at the available attributes. django_paginator_class – The default is django.core.paginator.Paginator. page_size – It indicates the page size (numeric value). If set, this overrides the PAGE_SIZE setting. Defaults to the same value as the PAGE_SIZE settings key. page_query_param – The name of the query parameter (string value) to use for the pagination control. page_size_query_param – It indicates the name of a query parameter (string value) that allows the client to set the page size on a per-request basis. Defaults to None. max_page_size – It indicates the maximum allowable requested page size (numeric value). This attribute is only valid if page_size_query_param is also set. last_page_strings – It is used with the page_query_param to request the final page in the set. Defaults to (‘last’,) template – The name of a template to use when rendering pagination controls in the browsable API. Let’s add a few more robot details to our database. The HTTPie commands are: http POST :8000/robot/ name=”M-10iD/8L” robot_category=”Articulated Robots” currency=”USD” price=20000 manufacturer=”Fanuc” manufacturing_date=”2020-02-12 00:00:00+00:00′′ http POST :8000/robot/ name=”SR-6iA” robot_category=”SCARA Robots” currency=”USD” price=10000 manufacturer=”Fanuc” manufacturing_date=”2020-02-12 00:00:00+00:00′′ Now, let’s compose and send an HTTP GET request and analyze the paginated results. http :8000/robot/ Output HTTP/1.1 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Length: 531 Content-Type: application/json Date: Mon, 01 Feb 2021 05:53:29 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 Vary: Accept, Cookie X-Content-Type-Options: nosniff X-Frame-Options: DENY { "count": 4, "next": "http://localhost:8000/robot/?page=2", "previous": null, "results": [ { "currency": "USD", "currency_name": "US Dollar", "manufacturer": "Fanuc", "manufacturing_date": "2019-10-12T00:00:00Z", "name": "FANUC M-710ic/50", "price": 37000, "robot_category": "Articulated Robots", "url": "http://localhost:8000/robot/1/" }, { "currency": "USD", "currency_name": "US Dollar", "manufacturer": "ABB", "manufacturing_date": "2020-05-10T00:00:00Z", "name": "IRB 910SC", "price": 27000, "robot_category": "SCARA Robots", "url": "http://localhost:8000/robot/2/" } ] } Sharing the command prompt screenshot for your reference. You can notice that the response looks different from the previous HTTP GET request. The response has the following keys: count: total number of resources on all pages next: link to the next page previous: link to the previous page results: an array of JSON representations of instances. Let’s retrieve the results on page 2. The HTTPie command is http :8000/robot/?page=2 Output HTTP/1.1 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Length: 516 Content-Type: application/json Date: Mon, 01 Feb 2021 05:52:36 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 Vary: Accept, Cookie X-Content-Type-Options: nosniff X-Frame-Options: DENY { "count": 4, "next": null, "previous": "http://localhost:8000/robot/", "results": [ { "currency": "USD", "currency_name": "US Dollar", "manufacturer": "Fanuc", "manufacturing_date": "2020-02-12T00:00:00Z", "name": "M-10iD/8L", "price": 20000, "robot_category": "Articulated Robots", "url": "http://localhost:8000/robot/4/" }, { "currency": "USD", "currency_name": "US Dollar", "manufacturer": "Fanuc", "manufacturing_date": "2020-02-12T00:00:00Z", "name": "SR-6iA", "price": 10000, "robot_category": "SCARA Robots", "url": "http://localhost:8000/robot/5/" } ] } Sharing the command prompt screenshot In LimitOffsetPagination style, client includes both a “limit” and an “offset” query parameter. The limit indicates the maximum number of items to return, same as that of the page_size. The offset indicates the starting position of the query w.r.t unpaginated items. To enable the LimitOffsetPagination style globally, you can set rest_framework.pagination.LimitOffsetPagination class to DEFAULT_PAGINATION_CLASS. The configuration as follows: Python3 REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 2,} You can skip setting the PAGE_SIZE. If set, then the client can omit the limit query parameter. If you want to modify the pagination style, you can override the attributes of the LimitOffsetPagination class. default_limit – It indicates (numeric value) the limit. Defaults to the same value as the PAGE_SIZE settings key. limit_query_param – It indicates the name of the “limit” query parameter. Defaults to ‘limit’. offset_query_param – It indicates the name of the “offset” query parameter. Defaults to ‘offset’. max_limit – It indicates the maximum allowable limit that the client may request. Defaults to None. template – The template name to use when rendering pagination controls in the browsable API The HTTPie command is http :8000/robot/ Output HTTP/1.1 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Length: 541 Content-Type: application/json Date: Mon, 01 Feb 2021 06:47:42 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 Vary: Accept, Cookie X-Content-Type-Options: nosniff X-Frame-Options: DENY { "count": 4, "next": "http://localhost:8000/robot/?limit=2&offset=2", "previous": null, "results": [ { "currency": "USD", "currency_name": "US Dollar", "manufacturer": "Fanuc", "manufacturing_date": "2019-10-12T00:00:00Z", "name": "FANUC M-710ic/50", "price": 37000, "robot_category": "Articulated Robots", "url": "http://localhost:8000/robot/1/" }, { "currency": "USD", "currency_name": "US Dollar", "manufacturer": "ABB", "manufacturing_date": "2020-05-10T00:00:00Z", "name": "IRB 910SC", "price": 27000, "robot_category": "SCARA Robots", "url": "http://localhost:8000/robot/2/" } ] } Let’s try another HTTPie command based on the next field value from the above output. The HTTPie command is http GET “:8000/robot/?limit=2&offset=2” Output HTTP/1.1 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Length: 524 Content-Type: application/json Date: Mon, 01 Feb 2021 06:52:35 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 Vary: Accept, Cookie X-Content-Type-Options: nosniff X-Frame-Options: DENY { "count": 4, "next": null, "previous": "http://localhost:8000/robot/?limit=2", "results": [ { "currency": "USD", "currency_name": "US Dollar", "manufacturer": "Fanuc", "manufacturing_date": "2020-02-12T00:00:00Z", "name": "M-10iD/8L", "price": 20000, "robot_category": "Articulated Robots", "url": "http://localhost:8000/robot/4/" }, { "currency": "USD", "currency_name": "US Dollar", "manufacturer": "Fanuc", "manufacturing_date": "2020-02-12T00:00:00Z", "name": "SR-6iA", "price": 10000, "robot_category": "SCARA Robots", "url": "http://localhost:8000/robot/5/" } ] } Sharing the command prompt screenshot for your reference Let’s try with limit=1 and offset=0. The HTTPie command is: http GET “:8000/robot/?limit=1&offset=0” Output HTTP/1.1 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Length: 325 Content-Type: application/json Date: Mon, 01 Feb 2021 10:36:19 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 Vary: Accept, Cookie X-Content-Type-Options: nosniff X-Frame-Options: DENY { "count": 4, "next": "http://localhost:8000/robot/?limit=1&offset=1", "previous": null, "results": [ { "currency": "USD", "currency_name": "US Dollar", "manufacturer": "Fanuc", "manufacturing_date": "2019-10-12T00:00:00Z", "name": "FANUC M-710ic/50", "price": 37000, "robot_category": "Articulated Robots", "url": "http://localhost:8000/robot/1/" } ] } Sharing the command prompt screenshot The CursorPagination provides a cursor indicator to page through the result set. It provides only forward or reverse controls and doesn’t permit the client to navigate to arbitrary positions. The CursorPagination style assumes that there must be a created timestamp field on the model instance and it orders the results by ‘-created’. To enable the CursorPagination style you can mention rest_framework.pagination.CursorPagination class in DEFAULT_PAGINATION_CLASS. Python3 REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination', 'PAGE_SIZE': 2,} Let’s do a look at the set of attributes that we can modify in CursorPagination class. They are as follows: page_size – It indicates the page size (numeric value). Defaults to the same value as the PAGE_SIZE settings key. cursor_query_param – It indicates the name of the “cursor” query parameter (string value). Defaults to ‘cursor’. ordering – This should be a string, or list of strings, indicating the field against which the cursor-based pagination will be applied. Defaults to -created. This value may also be overridden by using OrderingFilter on the view. template – The name of a template to use when rendering pagination controls in the browsable API. Let’s see how to customize the CursorPagination class. Here we will override the ordering attribute. By default, it will order based on the created timestamp. Here, we will use the id field instead of the created field for ordering. Let’s create a new file named custompagination.py file in the apps (robots) folder and add the below code Python3 from rest_framework.pagination import CursorPaginationclass CursorPaginationWithOrdering(CursorPagination): # order based on id ordering = 'id' Here we override the ordering attribute provided by the CursorPagination class. Next, you can mention the customized class in the DEFAULT_PAGINATION_CLASS as shown below. Python3 REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'robots.custompagination.CursorPaginationWithOrdering', 'PAGE_SIZE': 2,} Let’s analyze the output. You can send the below HTTP command. http :8000/robot/ Output HTTP/1.1 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Length: 526 Content-Type: application/json Date: Mon, 01 Feb 2021 11:09:45 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 Vary: Accept, Cookie X-Content-Type-Options: nosniff X-Frame-Options: DENY { "next": "http://localhost:8000/robot/?cursor=cD0y", "previous": null, "results": [ { "currency": "USD", "currency_name": "US Dollar", "manufacturer": "Fanuc", "manufacturing_date": "2019-10-12T00:00:00Z", "name": "FANUC M-710ic/50", "price": 37000, "robot_category": "Articulated Robots", "url": "http://localhost:8000/robot/1/" }, { "currency": "USD", "currency_name": "US Dollar", "manufacturer": "ABB", "manufacturing_date": "2020-05-10T00:00:00Z", "name": "IRB 910SC", "price": 27000, "robot_category": "SCARA Robots", "url": "http://localhost:8000/robot/2/" } ] } Sharing the command prompt screenshot Now, let’s compose an HTTP request based on the next value from the above output (cursor=cD0y). The HTTPie command is: http :8000/robot/?cursor=cD0y Output HTTP/1.1 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Length: 530 Content-Type: application/json Date: Mon, 01 Feb 2021 11:10:38 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 Vary: Accept, Cookie X-Content-Type-Options: nosniff X-Frame-Options: DENY { "next": null, "previous": "http://localhost:8000/robot/?cursor=cj0xJnA9NA%3D%3D", "results": [ { "currency": "USD", "currency_name": "US Dollar", "manufacturer": "Fanuc", "manufacturing_date": "2020-02-12T00:00:00Z", "name": "M-10iD/8L", "price": 20000, "robot_category": "Articulated Robots", "url": "http://localhost:8000/robot/4/" }, { "currency": "USD", "currency_name": "US Dollar", "manufacturer": "Fanuc", "manufacturing_date": "2020-02-12T00:00:00Z", "name": "SR-6iA", "price": 10000, "robot_category": "SCARA Robots", "url": "http://localhost:8000/robot/5/" } ] } Sharing the command prompt screenshot Django-REST Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n16 Mar, 2021" }, { "code": null, "e": 24220, "s": 23901, "text": "Imagine you have huge amount of details in your database. Do you think that it is wise to retrieve all at once while making an HTTP GET request? Here comes the imp...
Rearrange array in alternating positive & negative items with O(1) extra space in C++
We are given an integer type array containing both positive and negative numbers, let's say, arr[] of any given size. The task is to rearrange an array in such a manner that there will be a positive number that will be surrounded by negative numbers. If there are more positive and negative numbers, then they will be arranged at the end of an array. Input − int arr[] = {-1, -2, -3, 1, 2, 3} Output − Array before Arrangement: -1 -2 -3 1 2 3 Rearrangement of an array in alternating positive & negative items with O(1) extra space is: -1 1 -2 2 -3 3 Explanation − we are given an integer array of size 6 containing both positive and negative elements. Now, we will rearrange the array in such a manner that all the positive elements will be surrounded by the negative elements and all the extra elements will be added in the end of an array i.e -1 1 -2 2 -3 3 will be the final result. Input − int arr[] = {-1, -2, -3, 1, 2, 3, 5, 5, -5, 3, 1, 1}; Output − Array before Arrangement: -1 -2 -3 1 2 3 5 5 -5 3 1 1 Rearrangement of an array in alternating positive & negative items with O(1) extra space is: -1 1 -2 2 -3 3 -5 5 5 3 1 1 Explanation − we are given an integer array of size 12 containing both positive and negative elements. Now, we will rearrange the array in such a manner that all the positive elements will be surrounded by the negative elements and all the extra elements will be added in the end of an array i.e -1 1 -2 2 -3 3 -5 5 5 3 1 1 will be the final result. Input an array of integer type elements and calculate the size of an array. Input an array of integer type elements and calculate the size of an array. Print an array before performing the rearrangement action using the FOR loop. Print an array before performing the rearrangement action using the FOR loop. Call to the function Rearrangement(arr, size) by passing array and size of an array as a parameter. Call to the function Rearrangement(arr, size) by passing array and size of an array as a parameter. Inside the function Rearrangement(arr, size)Declare an integer variable ‘ptr’ and initialize it with -1.Start loop FOR from i to 0 till i less than size. Inside the loop, check IF ptr greater than 0 then check IF arr[i] greater than 0 AND arr[ptr] less than 0 OR arr[i] less than 0 AND arr[ptr] greater than 0 then call to the function move_array(arr, size, ptr, i) and check IF i - ptr greater than 2 then set ptr to ptr + 2. ELSE, set ptr to -1.Check IF ptr to -1 then check arr[i] greater than 0 AND !(i & 0x01) OR (arr[i] less than 0) AND (i & 0x01) then set ptr to i. Inside the function Rearrangement(arr, size) Declare an integer variable ‘ptr’ and initialize it with -1. Declare an integer variable ‘ptr’ and initialize it with -1. Start loop FOR from i to 0 till i less than size. Inside the loop, check IF ptr greater than 0 then check IF arr[i] greater than 0 AND arr[ptr] less than 0 OR arr[i] less than 0 AND arr[ptr] greater than 0 then call to the function move_array(arr, size, ptr, i) and check IF i - ptr greater than 2 then set ptr to ptr + 2. ELSE, set ptr to -1. Start loop FOR from i to 0 till i less than size. Inside the loop, check IF ptr greater than 0 then check IF arr[i] greater than 0 AND arr[ptr] less than 0 OR arr[i] less than 0 AND arr[ptr] greater than 0 then call to the function move_array(arr, size, ptr, i) and check IF i - ptr greater than 2 then set ptr to ptr + 2. ELSE, set ptr to -1. Check IF ptr to -1 then check arr[i] greater than 0 AND !(i & 0x01) OR (arr[i] less than 0) AND (i & 0x01) then set ptr to i. Check IF ptr to -1 then check arr[i] greater than 0 AND !(i & 0x01) OR (arr[i] less than 0) AND (i & 0x01) then set ptr to i. Inside the function move_array(int arr[], int size, int ptr, int temp)Declare a variable as ‘ch’ of type character and set it with arr[temp].Start loop FOR from i to temp till i greater than ptr. Inside the loop, set arr[i] with arr[i - 1].Set arr[ptr] to ch. Inside the function move_array(int arr[], int size, int ptr, int temp) Declare a variable as ‘ch’ of type character and set it with arr[temp]. Declare a variable as ‘ch’ of type character and set it with arr[temp]. Start loop FOR from i to temp till i greater than ptr. Inside the loop, set arr[i] with arr[i - 1]. Start loop FOR from i to temp till i greater than ptr. Inside the loop, set arr[i] with arr[i - 1]. Set arr[ptr] to ch. Set arr[ptr] to ch. #include <iostream> #include <assert.h> using namespace std; void move_array(int arr[], int size, int ptr, int temp){ char ch = arr[temp]; for(int i = temp; i > ptr; i--){ arr[i] = arr[i - 1]; } arr[ptr] = ch; } void Rearrangement(int arr[], int size){ int ptr = -1; for(int i = 0; i < size; i++){ if (ptr >= 0){ if(((arr[i] >= 0) && (arr[ptr] < 0)) || ((arr[i] < 0) && (arr[ptr] >= 0))){ move_array(arr, size, ptr, i); if(i - ptr >= 2){ ptr = ptr + 2; } else{ ptr = -1; } } } if(ptr == -1){ if (((arr[i] >= 0) && (!(i & 0x01))) || ((arr[i] < 0) && (i & 0x01))){ ptr = i; } } } } int main(){ //input an array int arr[] = {-1, -2, -3, 1, 2, 3}; int size = sizeof(arr) / sizeof(arr[0]); //print the original Array cout<<"Array before Arrangement: "; for (int i = 0; i < size; i++){ cout << arr[i] << " "; } //calling the function to rearrange the array Rearrangement(arr, size); //print the array after rearranging the values cout<<"\nRearrangement of an array in alternating positive & negative items with O(1) extra space is: "; for(int i = 0; i < size; i++){ cout<< arr[i] << " "; } return 0; } If we run the above code it will generate the following Output Array before Arrangement: -1 -2 -3 1 2 3 Rearrangement of an array in alternating positive & negative items with O(1) extra space is: -1 1 -2 2 -3 3
[ { "code": null, "e": 1413, "s": 1062, "text": "We are given an integer type array containing both positive and negative numbers, let's say, arr[] of any given size. The task is to rearrange an array in such a manner that there will be a positive number that will be surrounded by negative numbers. If...
mcopy - Unix, Linux Command
The mcopy command is used to copy MS-DOS files to and from Unix. It uses the following syntax: mcopy [-bspanvmQT] [-D clash_option] sourcefile targetfile mcopy [-bspanvmQT] [-D clash_option] sourcefile [ sourcefiles... ] targetdirectory mcopy [-tnvm] MSDOSsourcefile Mcopy copies the specified file to the named file, or copies multiple files to the named directory. The source and target can be either MS-DOS or Unix files. The use of a drive letter designation on the MS-DOS files, ’a:’ for example, determines the direction of the transfer. A missing drive designation implies a Unix file whose path starts in the current directory. If a source drive letter is specified with no attached file name (e.g. mcopy a: .), all files are copied from that drive. If only a single, MS-DOS source parameter is provided (e.g. "mcopy a:foo.exe"), an implied destination of the current directory (‘.’) is assumed. A filename of ‘-’ means standard input or standard output, depending on its position on the command line. Mcopy accepts the following command line options: mtype a:file1 a:file2 a:file3 >unixfile mtype a:file1 a:file2 a:file3 | mcopy - a:msdosfile ./configure; make dvi; dvips mtools.dvi ./configure; make html A premade html can be found at: oohttp://mtools.linux.luI and also at: oohttp://www.tux.org/pub/knaff/mtoolsI ./configure; make info Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10683, "s": 10586, "text": "\nThe mcopy command is used to copy MS-DOS files to and from\nUnix. It uses the following syntax:\n" }, { "code": null, "e": 10861, "s": 10687, "text": "\nmcopy [-bspanvmQT] [-D clash_option] sourcefile targetfile\nmcopy [-bspanvmQ...
Groovy - Database
Groovy’s groovy-sql module provides a higher-level abstraction over the current Java’s JDBC technology. The Groovy sql API supports a wide variety of databases, some of which are shown below. HSQLDB Oracle SQL Server MySQL MongoDB In our example, we are going to use MySQL DB as an example. In order to use MySQL with Groovy, the first thing to do is to download the MySQL jdbc jar file from the mysql site. The format of the MySQL will be shown below. mysql-connector-java-5.1.38-bin Then ensure to add the above jar file to the classpath in your workstation. Before connecting to a MySQL database, make sure of the followings − You have created a database TESTDB. You have created a table EMPLOYEE in TESTDB. This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. User ID "testuser" and password "test123" are set to access TESTDB. Ensure you have downloaded the mysql jar file and added the file to your classpath. You have gone through MySQL tutorial to understand MySQL Basics The following example shows how to connect with MySQL database "TESTDB". import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', 'test123', 'com.mysql.jdbc.Driver') // Executing the query SELECT VERSION which gets the version of the database // Also using the eachROW method to fetch the result from the database sql.eachRow('SELECT VERSION()'){ row -> println row[0] } sql.close() } } While running this script, it is producing the following result − 5.7.10-log The Sql.newInstance method is used to establish a connection to the database. The next step after connecting to the database is to create the tables in our database. The following example shows how to create a table in the database using Groovy. The execute method of the Sql class is used to execute statements against the database. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', 'test123', 'com.mysql.jdbc.Driver') def sqlstr = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )""" sql.execute(sqlstr); sql.close() } } It is required when you want to create your records into a database table. The following example will insert a record in the employee table. The code is placed in a try catch block so that if the record is executed successfully, the transaction is committed to the database. If the transaction fails, a rollback is done. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', 'test123', 'com.mysql.jdbc.Driver') sql.connection.autoCommit = false def sqlstr = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)""" try { sql.execute(sqlstr); sql.commit() println("Successfully committed") }catch(Exception ex) { sql.rollback() println("Transaction rollback") } sql.close() } } Suppose if you wanted to just select certain rows based on a criteria. The following codeshows how you can add a parameter placeholder to search for values. The above example can also be written to take in parameters as shown in the following code. The $ symbol is used to define a parameter which can then be replaced by values when the sql statement is executed. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', 'test123', 'com.mysql.jdbc.Driver') sql.connection.autoCommit = false def firstname = "Mac" def lastname ="Mohan" def age = 20 def sex = "M" def income = 2000 def sqlstr = "INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) VALUES " + "(${firstname}, ${lastname}, ${age}, ${sex}, ${income} )" try { sql.execute(sqlstr); sql.commit() println("Successfully committed") } catch(Exception ex) { sql.rollback() println("Transaction rollback") } sql.close() } } READ Operation on any database means to fetch some useful information from the database. Once our database connection is established, you are ready to make a query into this database. The read operation is performed by using the eachRow method of the sql class. eachRow(GString gstring, Closure closure) Performs the given SQL query calling the given Closure with each row of the result set. Parameters Gstring − The sql statement which needs to be executed. Gstring − The sql statement which needs to be executed. Closure − The closure statement to process the rows retrived from the read operation. Performs the given SQL query calling the given Closure with each row of the result set. Closure − The closure statement to process the rows retrived from the read operation. Performs the given SQL query calling the given Closure with each row of the result set. The following code example shows how to fetch all the records from the employee table. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', 'test123', 'com.mysql.jdbc.Driver') sql.eachRow('select * from employee') { tp -> println([tp.FIRST_NAME,tp.LAST_NAME,tp.age,tp.sex,tp.INCOME]) } sql.close() } } The output from the above program would be − [Mac, Mohan, 20, M, 2000.0] UPDATE Operation on any database means to update one or more records, which are already available in the database. The following procedure updates all the records having SEX as 'M'. Here, we increase AGE of all the males by one year. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args){ // Creating a connection to the database def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', 'test@123', 'com.mysql.jdbc.Driver') sql.connection.autoCommit = false def sqlstr = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M'" try { sql.execute(sqlstr); sql.commit() println("Successfully committed") }catch(Exception ex) { sql.rollback() println("Transaction rollback") } sql.close() } } DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', 'test@123', 'com.mysql.jdbc.Driver') sql.connection.autoCommit = false def sqlstr = "DELETE FROM EMPLOYEE WHERE AGE > 20" try { sql.execute(sqlstr); sql.commit() println("Successfully committed") }catch(Exception ex) { sql.rollback() println("Transaction rollback") } sql.close() } } Transactions are a mechanism that ensures data consistency. Transactions have the following four properties − Atomicity − Either a transaction completes or nothing happens at all. Atomicity − Either a transaction completes or nothing happens at all. Consistency − A transaction must start in a consistent state and leave the system in a consistent state. Consistency − A transaction must start in a consistent state and leave the system in a consistent state. Isolation − Intermediate results of a transaction are not visible outside the current transaction. Isolation − Intermediate results of a transaction are not visible outside the current transaction. Durability − Once a transaction was committed, the effects are persistent, even after a system failure. Durability − Once a transaction was committed, the effects are persistent, even after a system failure. Here is a simple example of how to implement transactions. We have already seen this example from our previous topic of the DELETE operation. def sqlstr = "DELETE FROM EMPLOYEE WHERE AGE > 20" try { sql.execute(sqlstr); sql.commit() println("Successfully committed") }catch(Exception ex) { sql.rollback() println("Transaction rollback") } sql.close() The commit operation is what tells the database to proceed ahead with the operation and finalize all changes to the database. In our above example, this is achieved by the following statement − sql.commit() If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use rollback method. In our above example, this is achieved by the following statement − sql.rollback() To disconnect Database connection, use the close method. sql.close() 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2430, "s": 2238, "text": "Groovy’s groovy-sql module provides a higher-level abstraction over the current Java’s JDBC technology. The Groovy sql API supports a wide variety of databases, some of which are shown below." }, { "code": null, "e": 2437, "s": 2430, ...
Difference Between System.out.print() and System.out.println() Function in Java - GeeksforGeeks
07 Oct, 2021 In Java, we have the following functions to print anything in the console. System.out.print() and System.out.println() But there is a slight difference between both of them, i.e. System.out.println() prints the content and switch to the next line after execution of the statement whereas System.out.print() only prints the content without switching to the next line after executing this statement. The following examples will help you in understanding the difference between them more prominently. Example 1: Java import java.io.*; class GFG { public static void main(String[] args) { System.out.println("Welcome to JAVA (1st line)"); // this print statement will be printed in a new line. System.out.print("Welcome to GeeksforGeeks (2nd line) "); // this print statement will be printed in the same line. System.out.print("Hello Geeks (2nd line)"); }} Welcome to JAVA (1st line) Welcome to GeeksforGeeks (2nd line) Hello Geeks (2nd line) Example 2: Java import java.io.*; class GFG { public static void main(String[] args) { System.out.print("Welcome to JAVA (1st line) "); // this print statement will be printed in the same line. System.out.println("Welcome to GeeksforGeeks (1st line)"); // this print statement will be printed in a new line. System.out.print("Hello Geeks (2nd line)"); }} Welcome to JAVA (1st line) Welcome to GeeksforGeeks (1st line) Hello Geeks (2nd line) Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Informed and Uninformed Search in AI Difference between HashMap and HashSet Difference between Internal and External fragmentation Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24467, "s": 24439, "text": "\n07 Oct, 2021" }, { "code": null, "e": 24542, "s": 24467, "text": "In Java, we have the following functions to print anything in the console." }, { "code": null, "e": 24565, "s": 24542, "text": "System.out.prin...
How to synchronize Elasticsearch with MySQL | by Redouane Achouri | Towards Data Science
Repository on GitHub: sync-elasticsearch-mysql. MySQL as a main database (version 8.0.22) Elasticsearch as a text search engine (version 7.9.3) Logstash as a connector or data pipe from MySQL to Elasticsearch (version 7.9.3) Kibana for monitoring and data visualization (version 7.9.3) JDBC Connector/J (version 8.0.22) Problem Statement Solution- Benefits from using Logstash- Use Cases Implementing a proof of concept- Creating a host directory for the project- Setup a MySQL database- Setup Elasticsearch and Kibana- Setup Logstash to pipe data from MySQL to Elasticsearch: * First Scenario — Creating an Elasticsearch index from scratch * Second Scenario — Replicating changes on the database records to Elasticsearch Conclusion Resources A common scenario for tech companies is to start building their core business functionalities around one or more databases, and then start connecting services to those databases to perform searches on text data, such as searching for a street name in the user addresses column of a users table, or searching for book titles and author names in the catalog of a library. So far everything is fine. The company keeps growing and acquires more and more customers. But then searches start to become slower and slower, which tends to irritate their customers and makes it hard to convince new prospects to buy in. Looking under the hood, the engineers realize that MySQL’s FULLTEXT indexes are not ideal for text look-ups on large datasets, and in order to scale up their operations, the engineers decide to move on to a more dedicated and battle-tested text search engine. Enters Elasticsearch and its underlying Lucene search engine. Elasticsearch indexes data using an inverted document index, and this results in a blazing-fast full-text search. A new challenge then comes in: How to get the data that is in a MySQL database into an Elasticsearch index, and how to keep the latter synchronized with the former? The modern data plumber’s toolkit contains a plethora of software for any data manipulation task. In this article, we’ll focus on Logstash from the ELK stack in order to periodically fetch data from MySQL, and mirror it on Elasticsearch. This will take into consideration any changes on the MySQL data records, such as create , update , and delete , and have the same replicated on Elasticsearch documents. The problem we are trying to solve here — sending data periodically from MySQL to Elasticsearch for syncing the two — can be solved with a Shell or Python script ran by a cron job or any job scheduler, BUT this would deprive us from the benefits otherwise acquired by configuring Logstash and its plugin-based setup: Although we focus on MySQL here, Logstash can ingest data from many sources, making it a centralized data input node. Logstash offers the possibility to parse, transform, and filter data on the fly, as it passes from source to destination. As for the input sources, there are many output destinations available — Elasticsearch being the go-to output. As part of the ELK Stack, everything will come together nice and smoothly later with Elasticsearch and Kibana for metrics and visualization. We will cover two scenarios in the following steps: Creating an Elasticsearch index and indexing database records from scratch.Incremental update of the Elasticsearch index based on changes occurring on the database records (creation, update, deletion). Creating an Elasticsearch index and indexing database records from scratch. Incremental update of the Elasticsearch index based on changes occurring on the database records (creation, update, deletion). Imagine you are opening an online library where avid readers can search your catalog of books to find their next reading. Your catalog contains millions of titles, ranging from scientific literature volumes to pamphlets about exotic adventures. We will create an initial database table books with a few thousands of records with book titles, authors, ISBN and publication date. We’ll use the Goodreads book catalog that can be found on Kaggle. This initial table will serve prototyping the use case (1) Building an index from scratch. We will create triggers on the table books that will populate a journal table books_journal with all changes on the books table (e.g. create , update , delete ). This means that whenever a record on the books table is created, updated, or deleted, this action will be recorded on the books_journal table, and the same action will be done on the corresponding Elasticsearch document. This will serve prototyping the use case (2) Incremental update of the Elasticsearch index. We’ll prototype and test the above concepts by defining a micro-services architecture using docker-compose. Install Docker and Docker Compose Full source code can be found on GitHub at sync-elasticsearch-mysql. Start by creating a directory to host this project (named e.g. sync-elasticsearch-mysql) and create a docker-compose.yaml file inside that directory with the following initial setup: Start by creating a directory to host this project (named e.g. sync-elasticsearch-mysql) and create a docker-compose.yaml file inside that directory with the following initial setup: version: "3"services:...# Here will come the services definition... 2. Setup a MySQL database: Create a directory data/ where we’ll store MySQL dump files with the pre-cleaned books data for the books table, as well as the triggers for the books table (on create, update, and delete), and a new_arrivals table with books we will add to our catalog to simulate new records, and the table books_journal . You can find these dump files in the project repository. Please copy them to the data/ directory so that the MySQL container will add them to the books database during the startup process. version: "3"services: # add this: mysql: image: mysql:8 container_name: sem_mysql ports: - 3306:3306 environment: MYSQL_RANDOM_ROOT_PASSWORD: "yes" MYSQL_DATABASE: books MYSQL_USER: avid_reader MYSQL_PASSWORD: i_love_books volumes: # Dump files for initiating tables - ./data/:/docker-entrypoint-initdb.d/ Note that storing usernames and passwords in plain text in your source code is not advised. The above is done for the sake of prototyping this project only and is not in any case a recommended practice. To start MySQL and check that data has been added successfully, from you project’s directory run on a terminal: docker-compose up -d mysql # -d is for detached mode# Once container started, log into the MySQL containerdocker exec -it sem_mysql bash# Start a MySQL promptmysql -uavid_reader -pi_love_books# Check that tables have been loaded from dump filesuse books;show tables; To show the triggers with a JSON-like formatting, use command: SHOW TRIGGERS \G;# To exit the MySQL prompt press CTRL+D# To logout from the MySQL container, press CTRL+D Now that we have our database properly set up, we can move on to the meat and potatoes of this project. 3. Setup Elasticsearch and Kibana: To setup Elasticsearch (without indexing any document yet), add this to your docker-compose.yaml file: version: "3"services:... elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:7.9.3 container_name: sem_elasticsearch environment: - discovery.type=single-node - bootstrap.memory_lock=true - "ES_JAVA_OPTS=-Xms512m -Xmx512m" volumes: - ./volumes/elasticsearch:/usr/share/elasticsearch/data logging: driver: "json-file" options: max-size: "10k" max-file: "10" kibana: image: docker.elastic.co/kibana/kibana:7.9.3 container_name: sem_kibana environment: - "ELASTICSEARCH_URL=http://elasticsearch:9200" - "SERVER_NAME=127.0.0.1" ports: - 5601:5601 depends_on: - elasticsearch Note that the volumes definition is recommended in order to mount the Elasticsearch index data from the docker volume to your directory file system. To get Elasticsearch and Kibana started, run the following from your project directory: docker-compose up -d elasticsearch kibana # -d is for detached mode# To check if everything so far is running as it should, run:docker-compose ps Let’s check if there is any index in our Elasticsearch node so far: # On your terminal, log into the Elasticsearch containerdocker exec -it sem_elasticsearch bash# Once logged in, use curl to request a listing of the indexescurl localhost:9200/_cat/indices If Kibana is up and running, you’ll see a list of indices used for metrics and visualization, but nothing related to our books yet — and if Kibana hasn’t been started, the list of indices will be empty. 4. Setup Logstash to pipe data from MySQL to Elasticsearch: To connect Logstash to MySQL, we will use the official JDBC driver available at this address. Let’s create a Dockerfile (named Dockerfile-logstash in the same directory) to pull a Logstash image, download the JDBC connector, and start a Logstash container. Add these lines to your Dockerfile: FROM docker.elastic.co/logstash/logstash:7.9.3# Download JDBC connector for LogstashRUN curl -L --output "mysql-connector-java-8.0.22.tar.gz" "https://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-8.0.22.tar.gz" \ && tar -xf "mysql-connector-java-8.0.22.tar.gz" "mysql-connector-java-8.0.22/mysql-connector-java-8.0.22.jar" \ && mv "mysql-connector-java-8.0.22/mysql-connector-java-8.0.22.jar" "mysql-connector-java-8.0.22.jar" \ && rm -r "mysql-connector-java-8.0.22" "mysql-connector-java-8.0.22.tar.gz"ENTRYPOINT ["/usr/local/bin/docker-entrypoint"] Then add the following snippet to your docker-compose.yaml file: version: "3"services:... logstash: build: context: . dockerfile: Dockerfile-logstash container_name: sem_logstash depends_on: - mysql - elasticsearch volumes: # We will explain why and how to add volumes below Logstash uses defined pipelines to know where to get data from, how to filter it, and where should it go. We will define two pipelines: one for creating an Elasticsearch index from scratch (first scenario), and one for incremental updates on changes to the database records (second scenario). Please check documentation for an explanation of each of the fields used in the pipeline definition: Input: JDBC Input Plugin Filter: Mutate remove_field Output: Elasticsearch Output Plugin 4.a. First Scenario — Creating an Elasticsearch index from scratch: In your project directory, create a volumes folder (if not already created) then create a directory to host our Logstash configuration: mkdir -p volumes/logstash/config Then in this config directory, create a file pipelines.yml containing: - pipeline.id: from-scratch-pipeline path.config: "/usr/share/logstash/pipeline/from-scratch.conf" We then create a folder pipeline to host our pipelines definitions: mkdir volumes/logstash/pipeline and there create a file from-scratch.conf with the following content: input { jdbc { jdbc_driver_library => "/usr/share/logstash/mysql-connector-java-8.0.22.jar" jdbc_driver_class => "com.mysql.jdbc.Driver" jdbc_connection_string => "jdbc:mysql://mysql:3306" jdbc_user => "avid_reader" jdbc_password => "i_love_books" clean_run => true record_last_run => false statement_filepath => "/usr/share/logstash/config/queries/from-scratch.sql" }}filter { mutate { remove_field => ["@version", "@timestamp"] }}output { # stdout { codec => rubydebug { metadata => true } } elasticsearch { hosts => ["http://elasticsearch:9200"] index => "books" action => "index" document_id => "%{isbn}" }} We define where to find the JDBC connector in jdbc_driver_library , setup where to find MySQL in jdbc_connection_string , instruct the plugin to run from scratch in clean_run , and we define where to find the SQL statement to fetch and format the data records in statement_filepath . The filter basically removes extra fields added by the plugin. In the output, we define where to find the Elasticsearch host, set the name of the index to books (can be a new or an existing index), define which action to perform (can be index , create , update , delete — see docs), and setup which field will serve as a unique ID in the books index — ISBN is an internationally unique ID for books. To add the SQL query referenced by statement_filepath , let’s create a folder queries : mkdir volumes/logstash/config/queries/ Then add file from-scratch.sql with as little as: SELECT * FROM books.books to get our index built with all the records available so far in our books table. Note that the query should NOT end with a semi-colon (;). Now to mount the configuration files and definitions created above, add the following to your docker-compose.yaml file: version: "3"services:... logstash: ... volumes: - ./volumes/logstash/pipeline/:/usr/share/logstash/pipeline/ - ./volumes/logstash/config/pipelines.yml:/usr/share/logstash/config/pipelines.yml - ./volumes/logstash/config/queries/:/usr/share/logstash/config/queries/ Note that volumes directives are a way to tell Docker to mount a directory or file inside the container (right hand side of the :) onto a directory or file on your machine or server (left hand side of the :). Checkout the official Docker Compose documentation on volumes. Testing In order to test the implementation for this first scenario, run on your terminal: docker-compose up logstash If the run is successful, you will see a message similar to Logstash shut down and the container will exit with error code 0. Now head to Kibana on you browser (to this link for example) and let’s start playing around to see if we have a books index and how we can search for books. In the Dev Tools panel, you can run custom queries to fetch documents by field value. For example, let’s search for books with the word “magic” in their title. Paste this query on the Dev Tools console: GET books/_search{ "query": { "match": { "title": "magic" } }} We get 9 documents: 4.b. Second Scenario — Replicating changes on the database records to Elasticsearch: Most of the configuring and tweaking has been done in the previous part. We will simply add another pipeline that will take charge of the incremental update (replication). In the file volumes/logstash/config/pipelines.yml, add these two line: - pipeline.id: incremental-pipeline path.config: "/usr/share/logstash/pipeline/incremental.conf" In the same file, you may want to comment out the two previous lines related to the “from-scratch” part (first scenario) in order to instruct Logstash to run this incremental pipeline only. Let’s create a file incremental.conf in the directory volumes/logstash/pipeline/ with the following content: input { jdbc { jdbc_driver_library => "/usr/share/logstash/mysql-connector-java-8.0.22.jar" jdbc_driver_class => "com.mysql.jdbc.Driver" jdbc_connection_string => "jdbc:mysql://mysql:3306" jdbc_user => "avid_reader" jdbc_password => "i_love_books" statement_filepath => "/usr/share/logstash/config/queries/incremental.sql" use_column_value => true tracking_column => "journal_id" tracking_column_type => "numeric" schedule => "*/5 * * * * *" }}filter { if [action_type] == "create" or [action_type] == "update" { mutate { add_field => { "[@metadata][action]" => "index" } } } else if [action_type] == "delete" { mutate { add_field => { "[@metadata][action]" => "delete" } } }mutate { remove_field => ["@version", "@timestamp", "action_type"] }}output { # stdout { codec => rubydebug { metadata => true } } elasticsearch { hosts => ["http://elasticsearch:9200"] index => "books" action => "%{[@metadata][action]}" document_id => "%{isbn}" }} We see a few extra parameters compared to the previous pipeline definition. The schedule parameter has a cron-like syntax (with a resolution down to the second when adding one more value the left), and uses the Rufus Scheduler behind the scene. Here we instruct Logstash to run this pipeline every 5 seconds with */5 * * * * * . The website crontab.guru can help you read crontab expressions. During each periodic run, the parameter tracking_column instructs Logstash to store the journal_id value of the last record fetched and store it somewhere on the filesystem (See documentation here for last_run_metadata_path ). In the following run, Logstash will fetch records starting from journal_id + 1 , where journal_id is the value stored in the current run. In the filter section, when the database action type is “create” or “update”, we set the Elasticsearch action to “index” so that new documents get indexed, and existing documents get re-indexed to update their value. Another approach to avoid re-indexing existing documents is to write a custom “update” script and to use the “upsert” action. For “delete” actions, the document on Elasticsearch gets deleted. Let’s create and populate the file incremental.sql in directory volumes/logstash/config/queries/ with this query: SELECT j.journal_id, j.action_type, j.isbn, b.title, b.authors, b.publication_dateFROM books.books_journal jLEFT JOIN books.books b ON b.isbn = j.isbnWHERE j.journal_id > :sql_last_value AND j.action_time < NOW()ORDER BY j.journal_id Testing Let’s have a look at the table books.new_arrival . It contains books that just got delivered to us and we didn’t have time to add them to our main books.books table. As we can see, none of the books in that table are in our Elasticsearch index. Let’s try with the 3 book in the table above “The Rocky Road to Romance (Elsie Hawkins #4)”, ISBN 9780060598891: Now let’s transfer that book from the new arrivals table to our main books table: INSERT INTO booksSELECT * FROM new_arrival WHERE isbn = 9780060598891; Running the same search on Elasticsearch, we are happy to see that the document is now available: The sync is working! Let’s test with an update of the same ISBN: UPDATE booksSET title = "The Rocky what ??"WHERE isbn = 9780060598891; ...and a delete of the same ISBN: DELETE from books WHERE isbn = 9780060598891; We managed to get a proof of concept up and running in a short amount of time of how to index data into Elasticsearch from a MySQL database, and how to keep Elasticsearch in sync with the database. The technologies we used are a gold standard in the industry and many businesses rely on them daily to serve their customer, and it’s very likely that many have encountered or will encounter the same problem we solved in this project. If you’d like to get in touch or you just want to let me know your thoughts about this project, don’t hesitate to reach out via email or via LinkedIn. A first take at building an inverted index Data in: documents and indices How to keep Elasticsearch synchronized with a relational database using Logstash and JDBC. This article has been an inspiration, however it does not deal with indexing from scratch and deleted records. Data used for this project is available in the Kaggle dataset Goodreads-books. Logstash JDBC input plugin Logstash Mutate filter plugin Logstash Elasticsearch output plugin
[ { "code": null, "e": 220, "s": 172, "text": "Repository on GitHub: sync-elasticsearch-mysql." }, { "code": null, "e": 262, "s": 220, "text": "MySQL as a main database (version 8.0.22)" }, { "code": null, "e": 316, "s": 262, "text": "Elasticsearch as a text sea...
A Quick Primer on JustPy for Data Science Projects | by John Naujoks | Towards Data Science
You know what’s great? Making a new model and showing it off to test it more. You know what isn’t great? Making a new model and not having a great way to show it off. It is increasingly easy to pull up some data and make a model (whether shitty or profound). You can train and test (and test some more), but like anything you make, it can be hard to tell how useful it is until its out there working with new data. I have definitely made some models, thought they scored well, and then when tested with new input showed their true colors. The trouble you can sometimes run into is taking that model and putting it into a usable version, like a website. You don’t want a lame text only page, but coding a website can take time and an entirely different set of skills. Don’t get me wrong, I think HTML, CSS, and Javascript are generally great languages for everyone to know as they are handy for pretty much every field in our modern world, but having extensive web design experience shouldn’t be a prerequisite for making a useful data science project. There are web frameworks to leverage your Python skills (like Flask and Django), but both to me have their own unique complexities. Enter JustPy. This handy Python package offers you the ability to quickly create a webpage in a Python file. It does not eliminate the need for some familiarity with web design languages, but can simplify things significantly, especially for spinning up a test of a model. It also plays very nicely with pandas and sharing data visualizations. I have spent some time creating a basic template that you can use for your own data science projects, but wanted to share an overview of the basics. Before anything else, let’s get to those two magic coding words. You will first need to just install JustPy, which can be done easily via pip: pip install justpy Next, you create a Python file and here is your basic page: import justpy as jpdef hello_world(): wp = jp.WebPage() p = jp.P() p.text = 'Hello!' return wpjp.justpy(hello_world) Let’s go line by line and get an overview. First, we started with importing JustPy and using their preferred abbreviation jp. Next, we put the entire page in one function, making it clear and easily callable. Inside the function, we start with creating an instance of a webpage with jp.WebPage(). The important thing to know is we are always going to create that instance of a page, and then add things to it. Just like the webpage, all of our other standard web components exist as classes as well. For this example, we create an instance of paragraph tag, jp.P() and then setting its text property with a value. With all that in place, we then just return that webpage instance. At the end, we use jp.justpy to call our function and we have a page! So something I noticed was helpful to understand was the many options of the tag classes. Let’s look at one div tag: main = jp.Div( classes='bg-gray-400 italic', text="My main div", a=wp) This entails the three main instance variables you will be updating: classes, text, and a. classes are the classes you want to add to your tag. An important thing to note with JustPy is that it has Tailwind CSS integrated, a utility-first CSS framework that can be used to easily format and style page elements. Unlike some other CSS frameworks, Tailwind is fairly low-level, so getting the look you are aiming for may take a number of combined classes. text is fairly obvious, but important to know. a is the tag your are nesting your tag in. Since you aren’t nesting tags like HTML, you have to tell each tag instance where it needs to be placed. In the example above, I’m just placing this div in our main webpage instance. I think one of the things that first drew me to testing this out was how seamlessly it could work with input, which can sometimes feel like a chore when connecting Python and HTML. There is the ability to use forms, but for a simple text input example, you can have something like this: in = jp.Input(placeholder='Please type here') Boom, input! The value entered will be stored in the class instance, in this scenario it would be in in.value. You can see live what is input with an asynchronous function or store and submit for processing. Okay, so we have some understanding of the basics, let’s get to an example! Let’s say you’re tasked with creating a spam detector for corporate email accounts. You have a nice labeled set of emails, and built a pretty straight forward logistic regression model that you feel pretty good about. And then it happens, someone says “Can I try it out?”. Instead of panicking, pickle that model, and roll it into a new Python file with your webpage! To help ease the design, I found a site with Tailwind templates and used that as a base. I created two main functions, one to process input and one for the webpage. So in just one Python file, viola: Looks pretty good! On top of that, it doesn’t require an extensive directory of files or dependencies. My entire page is built with one Python file, and has one other where I built my model. I set it up to just automatically process input as it comes, but you can see it does alright with looking for spam. The good: And the bad: You can jump off from my repo here and create your own easy JustPy model webpage to test our your own data science projects. Enjoy!
[ { "code": null, "e": 194, "s": 171, "text": "You know what’s great?" }, { "code": null, "e": 249, "s": 194, "text": "Making a new model and showing it off to test it more." }, { "code": null, "e": 276, "s": 249, "text": "You know what isn’t great?" }, { ...
Can a method local inner class access the local final variables in Java?
Yes, we can access the local final variables using the method local inner class because the final variables are stored on the heap and live as long as the method local inner class object may live. A local inner class instance can be delivered as an argument and retrieved from the methods and it is available inside a valid scope. The only limitation in method local inner class is that a local parameter can be executed only when it is defined as final. The method executing the local parameters can be called after the execution of the method, within which the local inner class was declared. As a result, the local parameters will no longer retain their values. The values must be fixed before creating the local inner class object. If required, a non-final variable can be copied into a final variable which is subsequently executed by the local inner class. Live Demo class MainClassTest { private int x = 10; public void sampleMethod() { final int y = 20; class MethodLocalInnerClassTest { public void accessMainClassVar() { System.out.println(x); // accessing the final variable System.out.println(c); } } MainClassTest mainTest = new MethodLocalInnerClassTest(); mainTest.accessMainClassVar(); } } // Test.java public class Test { public static void main(String args[]) { MainClassTest test = new MainClassTest(); test.sampleMethod(); } } 10 20
[ { "code": null, "e": 1259, "s": 1062, "text": "Yes, we can access the local final variables using the method local inner class because the final variables are stored on the heap and live as long as the method local inner class object may live." }, { "code": null, "e": 1393, "s": 1259...
Display Sequence of Numbers in SQL Using LEVEL - GeeksforGeeks
30 Jan, 2019 The term LEVEL refers to a Pseudocolumn in Oracle which is used in a hierarchical query to identify the hierarchy level (parent->child) in numeric format. The LEVEL returns 1 for root row, 2 for child of root row and so on, as tree like structure. LEVEL must be used with CONNECT BY Clause. The CONNECT BY clause defines the hierarchical relationship between the parent rows and the child rows of the hierarchy. DUAL is a dummy table automatically generated by Oracle database along with data dictionary. Example-1: SELECT Level AS Sequence FROM DualCONNECT BY Level <= 5 Explanation:Above query will execute Level having initial value 1 from dual, which is dummy table. ‘Sequence’ act as an ALias Name i.e., Temporary name of column. In query, condition will be checked and relationship created using Connect By between Level having value 1 and the specified condition. It will display values till it pass that specified condition. Output: Start Sequence from specific number:Level can be helpful to start a sequence of number from any particular initial value. Only need to add up one less than that value to Level with having condition in Connect By. Syntax: SELECT Level+(n-1) AS Alias NameFROM DualCONNECT BY Level <= 10 Where n is initial specific number and Alias Name is temporary defined name of column. Example-2: SELECT Level+(6-1) AS Sequence FROM DualCONNECT BY Level <= 10 Explanation:For display of sequence of numbers from 6 to 10. In above example, add up one less than 6 to Level and having condition till 10 using Connect By. It will execute and display range specified value as column name ‘Sequence’ from dummy table Dual. Output: Example-3: SELECT Level AS Sequence, Sysdate AS System_date FROM DualCONNECT BY Level <= 5 Explanation:Above query will execute and display both Sequence of Numbers as well as Date. Level have Temporary column name Sequence and Date have column name System_date, as defined. It will retrieve data from dummy table called Dual. It will have 5 numbers of rows according to the condition specified in Connect By, from 1 to 5 in Sequence column and have Same date in all 5 rows in System_date column. Output: DBMS-SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL | Views CTE in SQL Difference between DELETE, DROP and TRUNCATE How to Update Multiple Columns in Single Update Statement in SQL? Difference between DDL and DML in DBMS SQL Interview Questions What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter Difference between Where and Having Clause in SQL SQL - ORDER BY
[ { "code": null, "e": 23573, "s": 23545, "text": "\n30 Jan, 2019" }, { "code": null, "e": 24078, "s": 23573, "text": "The term LEVEL refers to a Pseudocolumn in Oracle which is used in a hierarchical query to identify the hierarchy level (parent->child) in numeric format. The LEVE...
Minimum operations to make Array equal by repeatedly adding K from an element and subtracting K from other - GeeksforGeeks
05 Aug, 2021 Given an array arr[] and an integer K, the task is to find the minimum number of operations to make all the elements of the array arr[] equal. In one operation, K is subtracted from an element and this K is added into other element. If it is not possible then print -1. Examples: Input: arr[] = {5, 8, 11}, K = 3Output: 1Explanation:Operation 1: Subtract 3 from arr[2](=11) and add 3 to arr[0](=5).Now, all the elements of the array arr[] are equal. Input: arr[] = {1, 2, 3, 4}, K = 2Output: -1 Approach: This problem can be solved using the Greedy algorithm. First check the sum of all elements of the array arr[] is divisible by N or not. If it is not divisible that means it is impossible to make all elements of the array arr[] equal. Otherwise, try to add or subtract the value of K to make every element equal to sum of arr[] / N. Follow the steps below to solve this problem: Initialize a variable sum as 0 to store sum of all elements of the array arr[]. Iterate in the range [0, N-1] using the variable i and update sum as sum + arr[i]. If sum % N is not equal to 0, then print -1 and return. Initialize a variable valueAfterDivision as sum/N to store that this much value, each element of array arr[] is store and count as 0 to store the minimum number of operation needed to make all array element equal. Iterate in the range [0, N-1] using the variable i:If abs of valueAfterDivision – arr[i] % K is not equal to 0, then print -1 and return.Update count as count + abs of valueAfterDivision – arr[i] / K. If abs of valueAfterDivision – arr[i] % K is not equal to 0, then print -1 and return. Update count as count + abs of valueAfterDivision – arr[i] / K. After completing the above steps, print count/2 as the answer. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum number of// operations to make all the elements of// the array equalvoid miniOperToMakeAllEleEqual(int arr[], int n, int k){ // Store the sum of the array arr[] int sum = 0; // Traverse through the array for (int i = 0; i < n; i++) { sum += arr[i]; } // If it is not possible to make all // array element equal if (sum % n) { cout << -1; return; } int valueAfterDivision = sum / n; // Store the minimum number of operations needed int count = 0; // Traverse through the array for (int i = 0; i < n; i++) { if (abs(valueAfterDivision - arr[i]) % k != 0) { cout << -1; return; } count += abs(valueAfterDivision - arr[i]) / k; } // Finally, print the minimum number operation // to make array elements equal cout << count / 2 << endl;} // Driver Codeint main(){ // Given Input int n = 3, k = 3; int arr[3] = { 5, 8, 11 }; // Function Call miniOperToMakeAllEleEqual(arr, n, k); // This code is contributed by Potta Lokesh return 0;} // Java Program for the above approachimport java.io.*; class GFG{ // Function to find the minimum number of // operations to make all the elements of // the array equal static void miniOperToMakeAllEleEqual(int arr[], int n, int k) { // Store the sum of the array arr[] int sum = 0; // Traverse through the array for (int i = 0; i < n; i++) { sum += arr[i]; } // If it is not possible to make all // array element equal if (sum % n != 0) { System.out.println(-1); return; } int valueAfterDivision = sum / n; // Store the minimum number of operations needed int count = 0; // Traverse through the array for (int i = 0; i < n; i++) { if (Math.abs(valueAfterDivision - arr[i]) % k != 0) { System.out.println(-1); return; } count += Math.abs(valueAfterDivision - arr[i]) / k; } // Finally, print the minimum number operation // to make array elements equal System.out.println((int)count / 2); } // Driver Code public static void main (String[] args) { // Given Input int n = 3, k = 3; int arr[] = { 5, 8, 11 }; // Function Call miniOperToMakeAllEleEqual(arr, n, k); }} // This code is contributed by Potta Lokesh # Python3 program for the above approach # Function to find the minimum number of# operations to make all the elements of# the array equaldef miniOperToMakeAllEleEqual(arr, n, k): # Store the sum of the array arr[] sum = 0 # Traverse through the array for i in range(n): sum += arr[i] # If it is not possible to make all # array element equal if (sum % n): print(-1) return valueAfterDivision = sum // n # Store the minimum number of operations needed count = 0 # Traverse through the array for i in range(n): if (abs(valueAfterDivision - arr[i]) % k != 0): print(-1) return count += abs(valueAfterDivision - arr[i]) // k # Finally, print the minimum number operation # to make array elements equal print(count // 2) # Driver Codeif __name__ == '__main__': # Given Input n = 3 k = 3 arr = [ 5, 8, 11 ] # Function Call miniOperToMakeAllEleEqual(arr, n, k) # This code is contributed by ipg2016107 // C# program for the above approachusing System; class GFG{ // Function to find the minimum number of // operations to make all the elements of // the array equal static void miniOperToMakeAllEleEqual(int[] arr, int n, int k) { // Store the sum of the array arr[] int sum = 0; // Traverse through the array for (int i = 0; i < n; i++) { sum += arr[i]; } // If it is not possible to make all // array element equal if (sum % n != 0) { Console.WriteLine(-1); return; } int valueAfterDivision = sum / n; // Store the minimum number of operations needed int count = 0; // Traverse through the array for (int i = 0; i < n; i++) { if (Math.Abs(valueAfterDivision - arr[i]) % k != 0) { Console.WriteLine(-1); return; } count += Math.Abs(valueAfterDivision - arr[i]) / k; } // Finally, print the minimum number operation // to make array elements equal Console.WriteLine((int)count / 2); } static void Main() { // Given Input int n = 3, k = 3; int[] arr = { 5, 8, 11 }; // Function Call miniOperToMakeAllEleEqual(arr, n, k); }} // This code is contributed by abhinavjain194 <script> // JavaScript program for the above approach // Function to find the minimum number of // operations to make all the elements of // the array equal function miniOperToMakeAllEleEqual(arr, n, k) { // Store the sum of the array arr[] let sum = 0; // Traverse through the array for (let i = 0; i < n; i++) { sum += arr[i]; } // If it is not possible to make all // array element equal if (sum % n) { document.write(-1); return; } let valueAfterDivision = sum / n; // Store the minimum number of operations needed let count = 0; // Traverse through the array for (let i = 0; i < n; i++) { if (Math.abs(valueAfterDivision - arr[i]) % k != 0) { document.write(-1); return; } count += Math.abs(valueAfterDivision - arr[i]) / k; } // Finally, print the minimum number operation // to make array elements equal document.write(Math.floor(count / 2)); } // Driver Code // Given Input let n = 3, k = 3; let arr = [5, 8, 11]; // Function Call miniOperToMakeAllEleEqual(arr, n, k); // This code is contributed by Potta Lokesh </script> 1 Time Complexity: O(N)Auxiliary Space: O(1) lokeshpotta20 abhinavjain194 ipg2016107 surinderdawra388 Arrays Greedy Arrays Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string
[ { "code": null, "e": 24431, "s": 24403, "text": "\n05 Aug, 2021" }, { "code": null, "e": 24702, "s": 24431, "text": "Given an array arr[] and an integer K, the task is to find the minimum number of operations to make all the elements of the array arr[] equal. In one operation, K ...
Unraveling the Staged Execution in Apache Spark | by Ajay Gupta | Towards Data Science
A Spark stage can be understood as a compute block to compute data partitions of a distributed collection, the compute block being able to execute in parallel in a cluster of computing nodes. Spark builds parallel execution flow for a Spark application using single or multiple stages. Stages provides modularity, reliability and resiliency to spark application execution. Below are the various important aspects related to Spark Stages: Stages are created, executed and monitored by DAG scheduler: Every running Spark application has a DAG scheduler instance associated with it. This scheduler create stages in response to submission of a Job, where a Job essentially represents a RDD execution plan (also called as RDD DAG) corresponding to a action taken in a Spark application. Multiple Jobs could be submitted to DAG scheduler if multiple actions are taken in a Spark application. For each of Job submitted to it, DAG scheduler creates one or more stages, builds a stage DAG to list out the stage dependency graph, and then plan execution schedule for the created stages in accordance with stage DAG. Also, the scheduler monitors the status of the stage execution completion which could turn out to be success, partial-success, or failure. Accordingly, the scheduler attempt for stage re-execution, conclude Job failure/success, or schedule dependent stages as per stage DAG. Below is a sample RDD execution plan (DAG) against a Job: (200) MapPartitionsRDD[36] | ShuffledRowRDD[35] +-(500) MapPartitionsRDD[34] | MapPartitionsRDD[33] | MapPartitionsRDD[32] | ShuffledRowRDD[31] +-(3) MapPartitionsRDD[30] | MapPartitionsRDD[29] | FileScanRDD[28] Below three stages are created by DAG scheduler for the above RDD execution plan: Below is stage DAG created by the DAG scheduler against the above stages which clearly indicates the inter stage dependencies: Every stage created by the DAG scheduler bears a unique ID across Jobs in a Spark application. Further, a stage is scheduled for execution in accordance with stage DAG, meaning a stage is scheduled for execution after all the dependent stages (as listed in stage DAG) are already computed. Two stages can be executed simultaneously if they are not inter dependent on each other and their all other dependent stages are already computed. Stages are created on shuffle boundaries: DAG scheduler creates multiple stages by splitting a RDD execution plan/DAG (associated with a Job) at shuffle boundaries indicated by ShuffleRDD’s in the plan. In this splitting process, therefore, a segment of RDD execution plan,essentially a RDD pipeline, becomes the part of a stage. Shuffle is necessitated for wide transformations mentioned in a Spark application, examples of which includes aggregation, join, or repartition operations. Below is a illustration of stage creation at various shuffle boundaries. Also, in the example shown in Fig (1), there are two shuffles happening as indicated by two ShuffleRowRDD’s in the RDD execution plan, and therefore three stages are created as shown in Fig (2). As evident from Fig (2), each of three stage contains a RDD pipeline (segment of Job’s original RDD execution plan/DAG). In case there is no shuffle required in a submitted Job, DAG scheduler will only create and schedule a single stage for the Job Stages are of either type, ShuffleMapStage or ResultStage: Stages of type ShuffleMapStage are intermediate stages of a Job execution plan, the Job being triggered against an action mentioned in a Spark application. A ShuffleMapStage essentially produces shuffle data files which are consumed by ShuffledRDD in the subsequent stage(s). But, before producing the output data, a ShuffleMapStage has to execute the segment of Job’s RDD execution plan (essentially a RDD pipeline) contained in the ShuffleMapStage. The amount of shuffle data produced by a ShuffleMapStage is available as a stage metric called as ShuffleWrite. Also, since SortShuffle process is mostly used to produce shuffle data files, the number of shuffle data files produced by a ShuffleMapStage is equal to number of data partitions computed by the RDD pipeline of the stage. A ResultStage is a final stage in a Job execution plan, in which a function (corresponding to the action initiating the Job) is applied to all or some partitions, the partitions being computed by executing the segment of RDD execution plan contained in the ResultStage. This function produces the final desired output expected from the execution of corresponding action in a spark application. A list of possible actions for a spark application are listed here. A Job, triggered by an action in a Spark application, either consists of a single ResultStage only, or a combination of intermediate ShuffleMapStage(s) along with a single ResultStage. However, for adaptive query planning or adaptive scheduling, some special Jobs consisting of only ShuffleMapStage(s) could be executed by DAG scheduler on request(s). Data to a ShuffleMapStage or ResultStage is fed individually or in combination from input files, shuffle files from previous ShuffleMap stages, or cached RDDs. Each Stage has a associated Taskset(s) for execution: For an execution attempt of a stage, DAG scheduler creates a corresponding Taskset. A stage Taskset is basically a collection of tasks, where each task executes the stage RDD pipeline for a specific data partition and produces the desired output. Similar to stage types, a task in a stage Taskset is of either type, ShuffleMapTask or ResultTask. ShuffleMapTasks are created for ShuffleMapStage while ResultTasks are created for ResultStage. Taskset, created for an execution attempt of stage, is submitted to Task scheduler instance of the Spark application. Task scheduler, in turn, schedules the execution of each task (contained in the Taskset) at an appropriate location in the cluster. After all the tasks in the Taskset are executed, the corresponding execution status of each task in the Taskset is reported back to the DAG scheduler. Accordingly, the DAG scheduler marks the stage execution as complete success, partial success or complete failure. In case of partial success, stage execution is re-attempted with a partial Taskset consisting of only those tasks that were failed earlier. In case of complete failure, stage execution is re-attempted with a full-fledged Taskset. A Stage is re-attempted only for a certain number of times, and when all the re-attempts together could not mark the stage execution as complete success, the stage execution is marked as failed leading to execution failure of the corresponding Job submitted to the DAG scheduler. Also, most of the times, a stage gets failed partially due to unavailability of some or all of the shuffle data files produced by the parent stage(s). This leads to partial re-execution of parent stage(s) (in order to compute the missing shuffle files) before the stage reported for failure is reattempted again. Further, this re-execution could also reach to stages present at deeper levels into the parental stage ancestry if there are missed shuffle files at successive levels in the ancestry. Shuffle files become unavailable when the executors hosting the files may get lost due to memory overruns or forced killing by cluster manager. Also, the shuffle files remain unavailable when the corresponding ShuffledRDD gets garbage collected. Stages computation can be skipped at times: DAG scheduler could decide to skip the computation of a ShuffleMap stage in a submitted Job if a similar stage is already being computed against a previous job submitted to the scheduler. The two stages are deemed to be similar if they are executing the same RDD pipeline. This skipping is possible because the shuffle output files are retained in the disk until the shuffled RDD reference is retained in the Spark application. Also, in another instance, DAG scheduler could decide on skipping the computation of a ShuffleMap stage if the Shuffled RDD required by the dependent downstream stage(s) is already cached, the caching being done during the execution of another stage against a previous job submitted to the scheduler. Below is a sample Spark application for illustration of stage skipping by DAG scheduler, this particular application caches a re-partitioned dataset (on line 10) which is being used in two File write actions, on line 15 and 20 respectively : Below are the RDD execution plans (with marking of stages) belonging to two different Jobs (triggered by two actions) in the above Spark application. In the application, dataset ‘ds’ is cached causing the corresponding ‘ShuffledRowRDD[11]’ to be cached. Below are the stage computation DAGs built by DAG scheduler for the two Jobs: As clear from stages computation DAGs of the two Jobs, in stage computation DAG of Job-2, stage 4 is skipped for computation (Skipped stage is greyed out ) since ‘ShuffledRowRDD[11]’ used in stage 5 of Job-2 is already computed and cached in stage 2 of Job-1, Job-1 bring submitted earlier for execution. Summary: It should be evident now, how the staging of execution flow in Spark provide modularization and resiliency to the overall execution of Spark application. Users can track stage wise progress of Spark application, can access several stage wise metrics to assess the stage execution efficiency. And finally, most importantly, the stage wise progress and associated metrics can lead to clues to Spark application optimization. In case of further queries/doubts about Spark stages , or for any feedback for this story, please do write in the comments section.
[ { "code": null, "e": 610, "s": 172, "text": "A Spark stage can be understood as a compute block to compute data partitions of a distributed collection, the compute block being able to execute in parallel in a cluster of computing nodes. Spark builds parallel execution flow for a Spark application us...
iOS - Text Field
A text field is a UI element that enables the app to get user input. A UITextfield is shown below. Placeholder text which is shown when there is no user input Normal text Auto correction type Key board type Return key type Clear button mode Alignment Delegate You can change the text field properties in xib in the attributes inspector in the utilities area (right side of the Window). We can set delegate in interface builder by right-clicking on the UIElement and connect it to the file owner as shown below. Step 1 − Set delegate as shown in the above figure. Step 2 − Add delegate to which your class responds to. Step 3 − Implement the textField Delegates, the important text field delegates are as follows − - (void)textFieldDidBeginEditing:(UITextField *)textField - (void)textFieldDidEndEditing:(UITextField *)textField Step 4 − As the name suggests, the above two delegates are called once we begin editing the text field and end editing respectively. Step 5 − For other delegates, please refer UITextDelegate Protocol reference. Step 1 − We'll use the sample application created for UI elements. Step 2 − Our ViewController class will adopt UITextFieldDelegate and our ViewController.h file is updated as follows − #import <UIKit/UIKit.h> // You can notice the adddition of UITextFieldDelegate below @interface ViewController : UIViewController<UITextFieldDelegate> @end Step 3 − Then we add a method addTextField to our ViewController.m file. Step 4 − Then we call this method in our viewDidLoad method. Step 5 − Update viewDidLoad in ViewController.m as follows − #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //The custom method to create our textfield is called [self addTextField]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)addTextField { // This allocates a label UILabel *prefixLabel = [[UILabel alloc]initWithFrame:CGRectZero]; //This sets the label text prefixLabel.text =@"## "; // This sets the font for the label [prefixLabel setFont:[UIFont boldSystemFontOfSize:14]]; // This fits the frame to size of the text [prefixLabel sizeToFit]; // This allocates the textfield and sets its frame UITextField *textField = [[UITextField alloc] initWithFrame: CGRectMake(20, 50, 280, 30)]; // This sets the border style of the text field textField.borderStyle = UITextBorderStyleRoundedRect; textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; [textField setFont:[UIFont boldSystemFontOfSize:12]]; //Placeholder text is displayed when no text is typed textField.placeholder = @"Simple Text field"; //Prefix label is set as left view and the text starts after that textField.leftView = prefixLabel; //It set when the left prefixLabel to be displayed textField.leftViewMode = UITextFieldViewModeAlways; // Adds the textField to the view. [self.view addSubview:textField]; // sets the delegate to the current class textField.delegate = self; } // pragma mark is used for easy access of code in Xcode #pragma mark - TextField Delegates // This method is called once we click inside the textField -(void)textFieldDidBeginEditing:(UITextField *)textField { NSLog(@"Text field did begin editing"); } // This method is called once we complete editing -(void)textFieldDidEndEditing:(UITextField *)textField { NSLog(@"Text field ended editing"); } // This method enables or disables the processing of return key -(BOOL) textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } - (void)viewDidUnload { label = nil; [super viewDidUnload]; } @end Step 6 − When we run the application, we'll get the following output. Step 7 − The delegate methods are called based on user action. See the console output to know when the delegates are called. 23 Lectures 1.5 hours Ashish Sharma 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson 69 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2160, "s": 2091, "text": "A text field is a UI element that enables the app to get user input." }, { "code": null, "e": 2190, "s": 2160, "text": "A UITextfield is shown below." }, { "code": null, "e": 2250, "s": 2190, "text": "Placeholder ...
Given an array of pairs, find all symmetric pairs in it - GeeksforGeeks
04 May, 2021 Two pairs (a, b) and (c, d) are said to be symmetric if c is equal to b and a is equal to d. For example, (10, 20) and (20, 10) are symmetric. Given an array of pairs find all symmetric pairs in it. It may be assumed that the first elements of all pairs are distinct.Example: Input: arr[] = {{11, 20}, {30, 40}, {5, 10}, {40, 30}, {10, 5}} Output: Following pairs have symmetric pairs (30, 40) (5, 10) We strongly recommend you to minimize your browser and try this yourself first.A Simple Solution is to go through every pair, and check every other pair for symmetric. This solution requires O(n2) time.A Better Solution is to use sorting. Sort all pairs by the first element. For every pair, do a binary search for the second element in the given array, i.e., check if the second element of this pair exists as the first element in the array. If found, then compare the first element of pair with the second element. Time Complexity of this solution is O(nLogn).An Efficient Solution is to use Hashing. The first element of pair is used as key and the second element is used as the value. The idea is to traverse all pairs one by one. For every pair, check if its second element is in the hash table. If yes, then compare the first element with the value of the matched entry of the hash table. If the value and the first element match, then we found symmetric pairs. Else, insert the first element as a key and second element as value.Following is the implementation of this idea. C++ Java Python3 C# Javascript #include<bits/stdc++.h>using namespace std; // A C++ program to find all symmetric pairs in a given array of pairs// Print all pairs that have a symmetric counterpartvoid findSymPairs(int arr[][2], int row){ // Creates an empty hashMap hM unordered_map<int, int> hM; // Traverse through the given array for (int i = 0; i < row; i++) { // First and second elements of current pair int first = arr[i][0]; int sec = arr[i][1]; // If found and value in hash matches with first // element of this pair, we found symmetry if (hM.find(sec) != hM.end() && hM[sec] == first) cout << "(" << sec << ", " << first << ")" <<endl; else // Else put sec element of this pair in hash hM[first] = sec; }} // Driver methodint main(){ int arr[5][2]; arr[0][0] = 11; arr[0][1] = 20; arr[1][0] = 30; arr[1][1] = 40; arr[2][0] = 5; arr[2][1] = 10; arr[3][0] = 40; arr[3][1] = 30; arr[4][0] = 10; arr[4][1] = 5; findSymPairs(arr, 5);} //This is contributed by Chhavi // A Java program to find all symmetric pairs in a given array of pairsimport java.util.HashMap; class SymmetricPairs { // Print all pairs that have a symmetric counterpart static void findSymPairs(int arr[][]) { // Creates an empty hashMap hM HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>(); // Traverse through the given array for (int i = 0; i < arr.length; i++) { // First and second elements of current pair int first = arr[i][0]; int sec = arr[i][1]; // Look for second element of this pair in hash Integer val = hM.get(sec); // If found and value in hash matches with first // element of this pair, we found symmetry if (val != null && val == first) System.out.println("(" + sec + ", " + first + ")"); else // Else put sec element of this pair in hash hM.put(first, sec); } } // Driver method public static void main(String arg[]) { int arr[][] = new int[5][2]; arr[0][0] = 11; arr[0][1] = 20; arr[1][0] = 30; arr[1][1] = 40; arr[2][0] = 5; arr[2][1] = 10; arr[3][0] = 40; arr[3][1] = 30; arr[4][0] = 10; arr[4][1] = 5; findSymPairs(arr); }} # A Python3 program to find all symmetric# pairs in a given array of pairs. # Print all pairs that have# a symmetric counterpartdef findSymPairs(arr, row): # Creates an empty hashMap hM hM = dict() # Traverse through the given array for i in range(row): # First and second elements # of current pair first = arr[i][0] sec = arr[i][1] # If found and value in hash matches with first # element of this pair, we found symmetry if (sec in hM.keys() and hM[sec] == first): print("(", sec,",", first, ")") else: # Else put sec element of # this pair in hash hM[first] = sec # Driver Codeif __name__ == '__main__': arr = [[0 for i in range(2)] for i in range(5)] arr[0][0], arr[0][1] = 11, 20 arr[1][0], arr[1][1] = 30, 40 arr[2][0], arr[2][1] = 5, 10 arr[3][0], arr[3][1] = 40, 30 arr[4][0], arr[4][1] = 10, 5 findSymPairs(arr, 5) # This code is contributed by Mohit Kumar // C# program to find all symmetric// pairs in a given array of pairsusing System;using System.Collections.Generic; public class SymmetricPairs{ // Print all pairs that have a symmetric counterpart static void findSymPairs(int [,]arr) { // Creates an empty hashMap hM Dictionary<int,int> hM = new Dictionary<int,int>(); int val = 0; // Traverse through the given array for (int i = 0; i < arr.GetLength(0); i++) { // First and second elements of current pair int first = arr[i, 0]; int sec = arr[i, 1]; // Look for second element of this pair in hash if(hM.ContainsKey(sec)) val = hM[sec]; // If found and value in hash matches with first // element of this pair, we found symmetry if (val != 0 && val == first) Console.WriteLine("(" + sec + ", " + first + ")"); else // Else put sec element of this pair in hash hM.Add(first, sec); } } // Driver code public static void Main(String []arg) { int [,]arr = new int[5, 2]; arr[0, 0] = 11; arr[0, 1] = 20; arr[1, 0] = 30; arr[1, 1] = 40; arr[2, 0] = 5; arr[2, 1] = 10; arr[3, 0] = 40; arr[3, 1] = 30; arr[4, 0] = 10; arr[4, 1] = 5; findSymPairs(arr); }} // This code has been contributed by 29AjayKumar <script>// A Javascript program to find all symmetric pairs in a given array of pairs // Print all pairs that have a symmetric counterpart function findSymPairs(arr) { // Creates an empty hashMap hM let hM = new Map(); // Traverse through the given array for (let i = 0; i < arr.length; i++) { // First and second elements of current pair let first = arr[i][0]; let sec = arr[i][1]; // Look for second element of this pair in hash let val = hM.get(sec); // If found and value in hash matches with first // element of this pair, we found symmetry if (val != null && val == first) document.write("(" + sec + ", " + first + ")<br>"); else // Else put sec element of this pair in hash hM.set(first, sec); } } // Driver method let arr = new Array(5); for(let i = 0; i < arr.length; i++) { arr[i] = new Array(2); for(let j = 0; j < 2; j++) { arr[i][j] = 0; } } arr[0][0] = 11; arr[0][1] = 20; arr[1][0] = 30; arr[1][1] = 40; arr[2][0] = 5; arr[2][1] = 10; arr[3][0] = 40; arr[3][1] = 30; arr[4][0] = 10; arr[4][1] = 5; findSymPairs(arr); // This code is contributed by unknown2108</script> Output: Following pairs have symmetric pairs (30, 40) (5, 10) Time Complexity of this solution is O(n) under the assumption that hash search and insert methods work in O(1) time.This article is contributed by Shivam Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 29AjayKumar mohit kumar 29 nidhi_biet unknown2108 Hash Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Hashing | Set 2 (Separate Chaining) Counting frequencies of array elements Most frequent element in an array Double Hashing Check if two arrays are equal or not Sort string of characters Quadratic Probing in Hashing Sorting a Map by value in C++ STL Rearrange an array such that arr[i] = i Implementing our Own Hash Table with Separate Chaining in Java
[ { "code": null, "e": 24816, "s": 24788, "text": "\n04 May, 2021" }, { "code": null, "e": 25094, "s": 24816, "text": "Two pairs (a, b) and (c, d) are said to be symmetric if c is equal to b and a is equal to d. For example, (10, 20) and (20, 10) are symmetric. Given an array of pa...
Kotlin Higher-Order Functions
14 Apr, 2022 Kotlin language has superb support for functional programming. Kotlin functions can be stored in variables and data structures, passed as arguments to and returned from other higher-order functions. In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas. Frequently, lambdas are passed as parameter in Kotlin functions for the convenience. We can pass a lambda expression as a parameter to Higher-Order Function. There are two types of lambda expression which can be passed- Lambda expression which return Unit Lambda expression which return any of the value integer,string etc Kotlin program of lambda expression which returns Unit- Kotlin // lambda expressionvar lambda = {println("GeeksforGeeks: A Computer Science portal for Geeks") } // higher-order functionfun higherfunc( lmbd: () -> Unit ) { // accepting lambda as parameter lmbd() //invokes lambda expression}fun main(args: Array<String>) { //invoke higher-order function higherfunc(lambda) // passing lambda as parameter} Output: GeeksforGeeks: A Computer Science portal for Geeks Explanation: Let’s understand the above program step by step:In the top, we define a lambda expression which contains print() to print string to the standard output. var lambda = {println("GeeksforGeeks: A Computer Science portal for Geeks") } then, we define a higher-order function which contains one parameter. lmbd: () -> Unit lmbd is local name for the receiving lambda parameter. () represents that the function does not accept any arguments. Unit represents that function does not return any value.In main function, we have invoked the higher-order function by passing the lambda expression as parameter. higherfunc(lambda) Kotlin program of lambda expression which returns Integer value – Kotlin // lambda expressionvar lambda = {a: Int , b: Int -> a + b } // higher order functionfun higherfunc( lmbd: (Int, Int) -> Int) { // accepting lambda as parameter var result = lmbd(2,4) // invokes the lambda expression by passing parameters println("The sum of two numbers is: $result")} fun main(args: Array<String>) { higherfunc(lambda) //passing lambda as parameter} Output: The sum of two numbers is: 6 Explanation: Let’s understand the above program step by step:In the top, we define a lambda expression defined which returns Integer value. var lambda = {a: Int , b: Int -> a + b } Then,we have defined higher-order function which accepts the lambda expression as parameter. lmbd: (Int, Int) -> Int lmbd is local name for the receiving lambda parameter. (Int,Int) represents that function accepts two integer type parameters. -> Int represents that function returns an integer value.In main function, we have invoked the higher-order function by passing the lambda as parameter. higherfunc(lambda) We can pass a function as a parameter in Higher-Order function. There are two types of functions which can be passed- function which return Unit function which return any of the value integer, string etc Kotlin program of passing function which returns Unit- Kotlin // regular function definitionfun printMe(s:String): Unit{ println(s)} // higher-order function definitionfun higherfunc( str : String, myfunc: (String) -> Unit){ // invoke regular function using local name myfunc(str)}fun main(args: Array<String>) { // invoke higher-order function higherfunc("GeeksforGeeks: A Computer Science portal for Geeks",::printMe)} Output: GeeksforGeeks: A Computer Science portal for Geeks Explanation: In the top, we define a regular function printMe() which accepts a parameter of String type and return Unit. fun printMe(s:String): Unit (s: String) is the only parameter Unit represents the return typeThen, we define the Higher-order function as fun higherfunc( str : String, myfunc: (String) -> Unit) it receives two parameters one is String type and another one is function str: String represents string parameter myfunc: (String) -> Unit represents that it accept function as a parameter which returns Unit.From main function, higher function is invoked by passing the string and function as arguments. higherfunc("GeeksforGeeks: A Computer Science portal for Geeks",::printMe) Kotlin program of passing function which returns integer value- Kotlin // regular function definitionfun add(a: Int, b: Int): Int{ var sum = a + b return sum} // higher-order function definitionfun higherfunc(addfunc:(Int,Int)-> Int){ // invoke regular function using local name var result = addfunc(3,6) print("The sum of two numbers is: $result")}fun main(args: Array<String>) { // invoke higher-order function higherfunc(::add)} Output: The sum of two numbers is: 9 Explanation: In the top, we define the regular function as fun add(a: Int, b: Int): Int{ var sum = a + b return sum } it accepts two parameters of Integer type, and return the sum of both the integersThen, we define the higher-order function as fun higherfunc(addfunc:(Int,Int)-> Int) it accepts a function which contains two parameters and call the regular function addfunc(3,6) by passing the parameters.From main function, we invoke the higher-order function by passing the regular function as parameter higherfunc(::add) We can return a function from higher-order function. While returning the function, we have to specify the parameter types and return type of regular function in the return type of the higher-order function. Kotlin program of a function returning another function- Kotlin // function declarationfun mul(a: Int, b: Int): Int{ return a*b} //higher-order function declarationfun higherfunc() : ((Int,Int)-> Int){ return ::mul}fun main(args: Array<String>) { // invoke function and store the returned function into a variable val multiply = higherfunc() // invokes the mul() function by passing arguments val result = multiply(2,4) println("The multiplication of two numbers is: $result")} Output: The multiplication of two numbers is: 8 Explanation: In the top of program we define mul() function which accepts two parameters and its return type is also an integer. fun mul(a: Int, b: Int): Int Then, we define the higher-order function having return type is a function. fun higherfunc5() : ((Int,Int)-> Int){ return ::mul } ::mul represents that it return mul() function (Int,Int) represents that mul accepts two integer type parameters Int represents that mul returns an integer value.In main function, we have called the higher function which returns another function and store this in a variable multiply . val multiply = higherfunc() then we invoke the mul() function using local variable multiply(2,4) by passing two arguments. ruhelaa48 rajeev0719singh Roopkishore Kotlin Functions Picked Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Apr, 2022" }, { "code": null, "e": 254, "s": 54, "text": "Kotlin language has superb support for functional programming. Kotlin functions can be stored in variables and data structures, passed as arguments to and returned from other...
Scraping Javascript Enabled Websites using Scrapy-Selenium
05 Sep, 2020 Scrapy-selenium is a middleware that is used in web scraping. scrapy do not support scraping modern sites that uses javascript frameworks and this is the reason that this middleware is used with scrapy to scrape those modern sites.Scrapy-selenium provide the functionalities of selenium that help in working with javascript websites. Other advantages provided by this is driver by which we can also see what is happening behind the scenes. As selenium is automated tool it also provides us to how to deal with input tags and scrape according to what you pass in input field. Passing inputs in input fields became easier by using selenium.First time scrapy-selenium was introduced in 2018 and its an opensource. The alternative to this can be scrapy-splash Install and Setup Scrapy –Install scrapyRunscrapy startproject projectname (projectname is name of project)Now, let’s Run,scrapy genspider spidername example.com(replace spidername with your preferred spider name and example.com with website that you want to scrape). Note: Later also url can be changed, inside your scrapy spider.scrapy spider: Install scrapy Runscrapy startproject projectname (projectname is name of project) scrapy startproject projectname (projectname is name of project) Now, let’s Run,scrapy genspider spidername example.com(replace spidername with your preferred spider name and example.com with website that you want to scrape). Note: Later also url can be changed, inside your scrapy spider.scrapy spider: scrapy genspider spidername example.com (replace spidername with your preferred spider name and example.com with website that you want to scrape). Note: Later also url can be changed, inside your scrapy spider. scrapy spider: Integrating scrapy-selenium in scrapy project:Install scrapy-selenium and add this in your settings.py file# for firefox from shutil import which SELENIUM_DRIVER_NAME = 'firefox'SELENIUM_DRIVER_EXECUTABLE_PATH = which('geckodriver')SELENIUM_DRIVER_ARGUMENTS=['-headless'] # for chrome driver from shutil import which SELENIUM_DRIVER_NAME = 'chrome'SELENIUM_DRIVER_EXECUTABLE_PATH = which('chromedriver')SELENIUM_DRIVER_ARGUMENTS=['--headless'] DOWNLOADER_MIDDLEWARES = { 'scrapy_selenium.SeleniumMiddleware': 800 }In this project chrome driver is used.Chrome driver is to be downloaded according to version of chrome browser. Go to help section in your chrome browser then click about Google chrome and check your version.Download chrome driver from website as referred here To download chrome driverWhere to add chromedriver:Addition in settings.py file:Change to be made in spider file:To run project:command- scrapy crawl spidername (scrapy crawl integratedspider in this project) spider code before scrapy-selenium:import scrapy class IntegratedspiderSpider(scrapy.Spider): name = 'integratedspider' # name of spider allowed_domains = ['example.com'] start_urls = ['http://example.com/'] def parse(self, response): pass Install scrapy-selenium and add this in your settings.py file# for firefox from shutil import which SELENIUM_DRIVER_NAME = 'firefox'SELENIUM_DRIVER_EXECUTABLE_PATH = which('geckodriver')SELENIUM_DRIVER_ARGUMENTS=['-headless'] # for chrome driver from shutil import which SELENIUM_DRIVER_NAME = 'chrome'SELENIUM_DRIVER_EXECUTABLE_PATH = which('chromedriver')SELENIUM_DRIVER_ARGUMENTS=['--headless'] DOWNLOADER_MIDDLEWARES = { 'scrapy_selenium.SeleniumMiddleware': 800 } # for firefox from shutil import which SELENIUM_DRIVER_NAME = 'firefox'SELENIUM_DRIVER_EXECUTABLE_PATH = which('geckodriver')SELENIUM_DRIVER_ARGUMENTS=['-headless'] # for chrome driver from shutil import which SELENIUM_DRIVER_NAME = 'chrome'SELENIUM_DRIVER_EXECUTABLE_PATH = which('chromedriver')SELENIUM_DRIVER_ARGUMENTS=['--headless'] DOWNLOADER_MIDDLEWARES = { 'scrapy_selenium.SeleniumMiddleware': 800 } In this project chrome driver is used.Chrome driver is to be downloaded according to version of chrome browser. Go to help section in your chrome browser then click about Google chrome and check your version.Download chrome driver from website as referred here To download chrome driver Where to add chromedriver: Addition in settings.py file: Change to be made in spider file: To run project:command- scrapy crawl spidername (scrapy crawl integratedspider in this project) command- scrapy crawl spidername (scrapy crawl integratedspider in this project) spider code before scrapy-selenium:import scrapy class IntegratedspiderSpider(scrapy.Spider): name = 'integratedspider' # name of spider allowed_domains = ['example.com'] start_urls = ['http://example.com/'] def parse(self, response): pass import scrapy class IntegratedspiderSpider(scrapy.Spider): name = 'integratedspider' # name of spider allowed_domains = ['example.com'] start_urls = ['http://example.com/'] def parse(self, response): pass Important fields in scrapy-selenium:name- name is a variable where name of spider is written and each spider is recognizedby this name. The command to run spider is, scrapy crawl spidername (Here spidername isreferred to that name which is defined in the spider).function start_requests- The first requests to perform are obtained by calling the start_requests() method which generates Request for the URL specified in the url field in yield SeleniumRequest and the parse method as callback function for the Requestsurl- Here url of the site is provided.screenshot- You can take a screenshot of a web page with the method get_screenshot_as_file() with as parameter the filename and screenshot will save in project.callback- The function that will be called with the response of this request as its first parameter.dont_filter- indicates that this request should not be filtered by the scheduler. if same url is send to parse it will not give exception of same url already accessed. What it means is same url can be accessed more then once.default value is false.wait_time- Scrapy doesn’t wait a fixed amount of time between requests. But by this field we can assign it during callback. name- name is a variable where name of spider is written and each spider is recognizedby this name. The command to run spider is, scrapy crawl spidername (Here spidername isreferred to that name which is defined in the spider).function start_requests- The first requests to perform are obtained by calling the start_requests() method which generates Request for the URL specified in the url field in yield SeleniumRequest and the parse method as callback function for the Requestsurl- Here url of the site is provided.screenshot- You can take a screenshot of a web page with the method get_screenshot_as_file() with as parameter the filename and screenshot will save in project.callback- The function that will be called with the response of this request as its first parameter.dont_filter- indicates that this request should not be filtered by the scheduler. if same url is send to parse it will not give exception of same url already accessed. What it means is same url can be accessed more then once.default value is false.wait_time- Scrapy doesn’t wait a fixed amount of time between requests. But by this field we can assign it during callback. name- name is a variable where name of spider is written and each spider is recognizedby this name. The command to run spider is, scrapy crawl spidername (Here spidername isreferred to that name which is defined in the spider). function start_requests- The first requests to perform are obtained by calling the start_requests() method which generates Request for the URL specified in the url field in yield SeleniumRequest and the parse method as callback function for the Requests url- Here url of the site is provided. screenshot- You can take a screenshot of a web page with the method get_screenshot_as_file() with as parameter the filename and screenshot will save in project. callback- The function that will be called with the response of this request as its first parameter. dont_filter- indicates that this request should not be filtered by the scheduler. if same url is send to parse it will not give exception of same url already accessed. What it means is same url can be accessed more then once.default value is false. wait_time- Scrapy doesn’t wait a fixed amount of time between requests. But by this field we can assign it during callback. General structure of scrapy-selenium spider:import scrapyfrom scrapy_selenium import SeleniumRequest class IntegratedspiderSpider(scrapy.Spider): name = 'integratedspider' def start_requests(self): yield SeleniumRequest( url ="https://www.geeksforgeeks.org/", wait_time = 3, screenshot = True, callback = self.parse, dont_filter = True ) def parse(self, response): pass import scrapyfrom scrapy_selenium import SeleniumRequest class IntegratedspiderSpider(scrapy.Spider): name = 'integratedspider' def start_requests(self): yield SeleniumRequest( url ="https://www.geeksforgeeks.org/", wait_time = 3, screenshot = True, callback = self.parse, dont_filter = True ) def parse(self, response): pass Project of Scraping with scrapy-selenium:scraping online courses names from geeksforgeeks site using scrapy-seleniumGetting X-path of element we need to scrap –Code to scrap Courses Data from Geeksforgeeks –import scrapyfrom scrapy_selenium import SeleniumRequest class IntegratedspiderSpider(scrapy.Spider): name = 'integratedspider' def start_requests(self): yield SeleniumRequest( url = "https://practice.geeksforgeeks.org/courses/online", wait_time = 3, screenshot = True, callback = self.parse, dont_filter = True ) def parse(self, response): # courses make list of all items that came in this xpath # this xpath is of cards containing courses details courses = response.xpath('//*[@id ="active-courses-content"]/div/div/div') # course is each course in the courses list for course in courses: # xpath of course name is added in the course path # text() will scrape text from h4 tag that contains course name course_name = course.xpath('.//a/div[2]/div/div[2]/h4/text()').get() # course_name is a string containing \n and extra spaces # these \n and extra spaces are removed course_name = course_name.split('\n')[1] course_name = course_name.strip() yield { 'course Name':course_name }Output – Getting X-path of element we need to scrap – Code to scrap Courses Data from Geeksforgeeks – import scrapyfrom scrapy_selenium import SeleniumRequest class IntegratedspiderSpider(scrapy.Spider): name = 'integratedspider' def start_requests(self): yield SeleniumRequest( url = "https://practice.geeksforgeeks.org/courses/online", wait_time = 3, screenshot = True, callback = self.parse, dont_filter = True ) def parse(self, response): # courses make list of all items that came in this xpath # this xpath is of cards containing courses details courses = response.xpath('//*[@id ="active-courses-content"]/div/div/div') # course is each course in the courses list for course in courses: # xpath of course name is added in the course path # text() will scrape text from h4 tag that contains course name course_name = course.xpath('.//a/div[2]/div/div[2]/h4/text()').get() # course_name is a string containing \n and extra spaces # these \n and extra spaces are removed course_name = course_name.split('\n')[1] course_name = course_name.strip() yield { 'course Name':course_name } Output – Official link github repo Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Sep, 2020" }, { "code": null, "e": 808, "s": 52, "text": "Scrapy-selenium is a middleware that is used in web scraping. scrapy do not support scraping modern sites that uses javascript frameworks and this is the reason that this mid...
Peripherals Devices in Computer Organization
21 Aug, 2019 A Peripheral Device is defined as the device which provides input/output functions for a computer and serves as an auxiliary computer device without computing-intensive functionality. Generally peripheral devices, however, are not essential for the computer to perform its basic tasks, they can be thought of as an enhancement to the user’s experience. A peripheral device is a device that is connected to a computer system but is not part of the core computer system architecture. Generally, more people use the term peripheral more loosely to refer to a device external to the computer case. Classification of Peripheral devices:It is generally classified into 3 basic categories which are given below: Input Devices:The input devices is defined as it converts incoming data and instructions into a pattern of electrical signals in binary code that are comprehensible to a digital computer.Example:Keyboard, mouse, scanner, microphone etc. Output Devices:An output device is generally reverse of the input process and generally translating the digitized signals into a form intelligible to the user. The output device is also performed for sending data from one computer system to another. For some time punched-card and paper-tape readers were extensively used for input, but these have now been supplanted by more efficient devices.Example:Monitors, headphones, printers etc. Storage Devices:Storage devices are used to store data in the system which is required for performing any operation in the system. The storage device is one of the most requirement devices and also provide better compatibility.Example:Hard disk, magnetic tape, Flash memory etc. Input Devices:The input devices is defined as it converts incoming data and instructions into a pattern of electrical signals in binary code that are comprehensible to a digital computer.Example:Keyboard, mouse, scanner, microphone etc. Keyboard, mouse, scanner, microphone etc. Output Devices:An output device is generally reverse of the input process and generally translating the digitized signals into a form intelligible to the user. The output device is also performed for sending data from one computer system to another. For some time punched-card and paper-tape readers were extensively used for input, but these have now been supplanted by more efficient devices.Example:Monitors, headphones, printers etc. Monitors, headphones, printers etc. Storage Devices:Storage devices are used to store data in the system which is required for performing any operation in the system. The storage device is one of the most requirement devices and also provide better compatibility.Example:Hard disk, magnetic tape, Flash memory etc. Hard disk, magnetic tape, Flash memory etc. Advantage of Peripherals Devices:Peripherals devices provides more feature due to this operation of the system is easy. These are given below: It is helpful for taking input very easily. It is also provided a specific output. It has a storage device for storing information or data It also improves the efficiency of the system. Computer Organization & Architecture Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Control Characters Direct Access Media (DMA) Controller in Computer Architecture Pin diagram of 8086 microprocessor Architecture of 8085 microprocessor Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) I2C Communication Protocol Difference between Hardwired and Micro-programmed Control Unit | Set 2 8259 PIC Microprocessor Cache Coherence Difference between SRAM and DRAM
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Aug, 2019" }, { "code": null, "e": 236, "s": 52, "text": "A Peripheral Device is defined as the device which provides input/output functions for a computer and serves as an auxiliary computer device without computing-intensive funct...
JavaScript window.open() Method
13 Jun, 2022 The Javascript window.open() method is used to open a new tab or window with the specified URL and name. It supports various parameters that can be used to specify the type and URL location of the window to be opened. Syntax: window.open(url, windowName, windowFeatures) Parameters: It has the following parameters as mentioned above and described below: URL: It accepts the URL that will be open in the new window. If an empty string is provided then it will open a blank new tab. windowName: It can be used to provide the name of the window. This is not associated with the title of the window in any manner. It can accept values like _blank, _self, _parent, etc. windowFeatures: It is used to provide features to the window that will open, for example, the dimension and position of the window. Example 1: In this example, we will open a new window on a button click with the specified parameters. HTML <!DOCTYPE html> <head> <style> body { background-color: #272727; display: flex; justify-content: center; align-items: center; margin-top: 20%; } .main { width: 50%; height: 100%; display: flex; justify-content: center; align-items: center; text-align: center; flex-direction: column; background-color: rgb(82, 82, 82); margin: 10px; font-family: 'Roboto', sans-serif; } .btn { width: 100%; height: 50px; background-color: rgb(29, 29, 29); color: white; font-size: 20px; border: none; cursor: pointer; } </style></head> <body> <div class="main"> <h1>Click the button to open a new window</h1> <button class="btn">Open</button> </div> <script> document.querySelector('.btn') .addEventListener('click', function () { window.open('https://www.geeksforgeeks.org/', '_blank', 'width=400,height=400 top=200,left=600'); }); </script></body> </html> Output: Example 2: In this example, we will open a blank window by passing the URL as an empty string. HTML <!DOCTYPE html> <head> <style> body { background-color: #272727; display: flex; justify-content: center; align-items: center; margin-top: 20%; } .main { width: 50%; height: 100%; display: flex; justify-content: center; align-items: center; text-align: center; flex-direction: column; background-color: rgb(82, 82, 82); margin: 10px; font-family: 'Roboto', sans-serif; } .btn { width: 100%; height: 50px; background-color: rgb(29, 29, 29); color: white; font-size: 20px; border: none; cursor: pointer; } </style></head> <body> <div class="main"> <h1>Click the button to open a new window.</h1> <button class="btn">Open</button> </div></body> <script> document.querySelector('.btn') .addEventListener('click', function () { window.open('', '_blank', 'width=400,height=400 top=200,left=600'); });</script> </html> Output: Supported Browsers: Google Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 4 and above Opera 3 and above Safari 1 and above JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. kumargaurav97520 sanjyotpanure JavaScript-Methods Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Jun, 2022" }, { "code": null, "e": 271, "s": 53, "text": "The Javascript window.open() method is used to open a new tab or window with the specified URL and name. It supports various parameters that can be used to specify the type a...
How to prevent scientific notation in R?
05 Jan, 2022 Scientific notations in R Programming Language are considered equivalent to the exponential formats. Scientific notations are used for numbers that are extremely large or small to be handled in the decimal form. In R Language, the E-notation is used for such numbers. In this article, we are going to see how to prevent scientific notation in R programming. Method 1: Using scipen option In order to eliminate the exponential notation of the integer, we can use the global setting using options() method, by setting the scipen argument, that is options(scipen = n). Scipen: A penalty to be applied when deciding to print numeric values in fixed or exponential notation. Positive values bias towards fixed and negative towards scientific notation: fixed notation will be preferred unless it is more than scipen digits wider. The scipen value is an indicator of the integer’s prompt for exponential notation. In order to prevent the triggering of scientific notation, any large positive number can be used, for all practical purposes. However, this method makes changes to the entire R configurational settings. options(scipen=999) This option can be reset by using 0 as the scipen value. Code: R num = 12383828281831342print ("original number :")print (num) # after global setting for# optionsoptions(scipen = 100, digits = 4) # declaring the numbernum = 12383828281831342print ("Modified number :")print (num) Output: [1] "original number :" [1] 1.238383e+16 [1] "Modified number :" [1] 12383828281831342 Method 2: Using format() method In order to disable the scientific option for any function output or numerical integer, the format method in R can be customized. Modification is made to the original integer. This eliminates the automatic exponential representation of the number. This method can be used in case, we wish to eliminate the scientific notation for a specific number and not set it globally. Syntax: format(number, scientific = FALSE) Returns : The exponential number with the exactly same number of digits. However, the output is returned as a character variable object. So, it needs to be converted to an integer explicitly, in order to use it for further purposes. Example 1: R # declaring an integer numbernum = 1000000000000print ("original number")print (num) print ("modified number")format(num, scientific = F) Output: [1] "original number" [1] 1e+12 [1] "modified number" [1] "1000000000000" Example 2: R # declaring an exponential numbernum =2.21e+09print ("original number")print (num) print ("modified number")format(num, scientific = FALSE) Output [1] "original number" [1] 2.21e+09 [1] "modified number" [1] "2210000000" gulshankumarar231 khushboogoyal499 Picked R String-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jan, 2022" }, { "code": null, "e": 386, "s": 28, "text": "Scientific notations in R Programming Language are considered equivalent to the exponential formats. Scientific notations are used for numbers that are extremely large or smal...
JPMS : Java Platform Module System
13 Oct, 2021 JPMS: JPMS i.e. Java Platform Module System is a new feature which is introduced in Java 9. With the help of the Java module system, we can package our Java application and our Java packages into Java modules. By the help of the Java module, we can specify which of the packages of the module should be visible to other Java modules. A Java module must also specify which other Java modules is requires to do its job. The Java Platform Module System is also sometimes referred to as Java Jigsaw or Project Jigsaw depending. Jigsaw was the internally used project name during development. Later Jigsaw changed name to Java Platform Module System. The main intent of developing JPMS is to make the JRE more modular i.e. have smaller jars which are optional and/or we can download/upgrade only the functionality as per need.JPMS/Project Jigsaw is going to address few major problems: ClassPath/JAR Hell Massive Monolithic JDK Version conflicts Security Problems ClassPath/JAR Hell Massive Monolithic JDK Version conflicts Security Problems Let’s see each one of them in detail. ClassPath/JAR Hell: Java searches for classes and packages on the classpath at the run time. Suppose we created one application and the application requires some class files from few jar files and we added that jars inside the classpath. At the compile time, compiler will not check that the required class files are present inside the jar or not. It will run the application and at the run time it will goto the classpath and check that required classes are there inside the jar files or not. If it is there then our application will execute fine. But for any reason if any one of the class file is not present inside the jar then it will throw NoClassDefFound error. We are following this approach before Java 9 introduced and with this approach at the run time there are chances to get NoClassDefFound error, which is not good. With the help of Java module system, we can package our Java application and our Java packages into Java modules. Apart from .class files, a Java module contains one more file i.e. module-info.Java file. Each Java module needs a Java module descriptor named module-info.Java which has to be located in the corresponding module root directory. Creating a module is relatively simple, however. A module is typically just a jar file that has a module-info.class file at the root – known as a modular jar file. Using a modular jar file involves adding the jar file to the modulepath instead of the classpath. In module-info.Java, we can mention all the dependencies/which modules are needed at the run time. Now at the compile time with the help of module-info.Java, compiler will get to know that what are classes needed to run the application and at the compilation time only compiler will check that the corresponding classes/packages are present inside the module or not. If the required classes are present then the code will compile successfully otherwise it will throw compilation errors at the compile time only. This is how Java module system resolve the classPath/JAR Hell problem. Massive Monolithic JDK: Monolithic means formed of a single large block of stone. The big monolithic nature of JDK causes several problems. It doesn’t fit on small devices. Small devices do not have necessarily the memory to hold all of the JDK, especially, when the application only uses small part of it. Java class Geeksforgeeks { public static void main(String[] args) { System.out.println( "Hello, " + "Welcome to Geeksforgeeks!!!"); }} To run the above code, we need few classes like String, System, Object etc. But we have to hold the entire JDK even if we are not using the entire jar of JDK not even 10% of it. With this approach to run even 1KB of file, we need to have minimum 60MB of rt.jar file. We can resolve this issue with JPMS. Jigsaw breaks up the JDK itself into many modules e.g. Java.sql contains the familiar SQL classes, Java.io contains the familiar IO classes etc. As per requirement, we can use appropriate module. No need to use the entire JDK. Version conflicts: Here we have 4 jar files inside classpath. Suppose JAR 4 requires a .class file with name xyz of JAR 3 and JAR 2 also contains the .class file with the name xyz. Now JVM will search for xyz class file from left to right and it will get the .class file named with xyz from JAR 2. Now the JVM will assign xyz.class file of JAR 2 inside JAR 4. But JAR 4 requires xyz.class file of JAR 3. Here we will get version conflict. With the help of JPMS, we can specify that we want a .class file of a particular JAR file. We have to specify inside module-info.Java like below: Java module module4{ requires module3;} Security Problems: Assume we have a JAR and inside that jar we have 2 packages. com.geeksforgeeks.demo.api.geeks com.geeksforgeeks.demo.impl.geeksImpl Both packages are public in nature. At some point, we might decide that our team should use geeks package and not use geeksImpl directly. However, there is no way to enforce that on the classpath. In JPMS/Jigsaw, a module contains a module-info.Java file which allows us to explicitly state what is public to other modules. Java // com.geeksforgeeks.demo.api.geeks is accessible,// but com.geeksforgeeks.demo.impl.geeksImpl is not module com.geeksforgeeks.demo{ exports com.geeksforgeeks.demo.impl;} sooda367 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Oct, 2021" }, { "code": null, "e": 936, "s": 54, "text": "JPMS: JPMS i.e. Java Platform Module System is a new feature which is introduced in Java 9. With the help of the Java module system, we can package our Java application and o...
How to Install glob in Python in Windows?
21 Sep, 2021 The Python Glob module searches all path names looking for files matching a specified pattern according to the rules dictated by the Unix shell. In this article, we will look into, how to install the glob module on Windows. The only thing that you need for installing the glob module on Windows are: Python PIP or Conda (depending upon user preference) If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command: conda install -c anaconda glob2 Type y for yes when prompted. You will get a similar message once the installation is complete: Make sure you follow the best practices for installation using conda as: Use an environment for installation rather than in the base environment using the below command: conda create -n my-env conda activate my-env Note: If your preferred method of installation is conda-forge, use the below command: conda config --env --add channels conda-forge To verify if glob library has been successfully installed in your system run the below command in Anaconda Powershell Prompt: conda list glob2 You’ll get the below message if the installation is complete: If you want the installation to be done through PIP, open up the Command Prompt and use the below command: pip install glob2 You will get a similar message once the installation is complete: To verify if glob module has been successfully installed in your system run the below command in Command Prompt: python -m pip show glob2 You’ll get the below message if the installation is complete: Blogathon-2021 how-to-install Picked Blogathon How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Sep, 2021" }, { "code": null, "e": 173, "s": 28, "text": "The Python Glob module searches all path names looking for files matching a specified pattern according to the rules dictated by the Unix shell." }, { "code": null, ...
Why we use then() method in JavaScript ?
13 Sep, 2021 The then() method in JavaScript has been defined in the Promise API and is used to deal with asynchronous tasks such as an API call. Previously, callback functions were used instead of this function which made the code difficult to maintain. Syntax: demo().then( (onResolved) => { // Some task on success }, (onRejected) => { // Some task on failure } ) Note: demo is a function that returns a promise prototype. Parameters: This function has two parameters to handle the success or rejection of the promise: onFulfilled: This is a function that is called upon the success of the promise. This is an optional parameter. onRejected: This is a function that is called upon the rejection of the promise. This is an optional parameter. Return Value: This method can either return a Promise (if further another then() is called) or nothing. Example 1: Passing no arguments JavaScript <script type="text/javascript"> function demo() { document.write("Function called!!<br>") return Promise.resolve("Success"); // or // return Promise.reject("Failure"); } demo().then() </script> Output: Function called!! Example 2: Passing only the first callback JavaScript <script type="text/javascript"> function demo() { document.write("Function called!!<br>") return Promise.resolve("Success"); // or // return Promise.reject("Failure"); } demo().then( (message) => { document.write("Then success:" + message); } )</script> Output: Function called!! Then success:Success Note that if the demo function returns a reject then it will generate an error. Example 3: Passing both the arguments JavaScript <script type="text/javascript"> function demo() { document.write("Function called!!<br>") return Promise.resolve("Success"); // or // return Promise.reject("Failure"); } demo().then( (message) => { document.write("Then success:" + message); }, (message) => { document.write("Then failure:" + message); } )</script> Output: Function called!! Then success:Success Example 4: Chaining Multiple then() methods: Each then() can return a promise (a resolve or a reject) and therefore multiple then() methods can be chained together. JavaScript <script type="text/javascript"> function demo() { document.write("Function called!!<br>") return Promise.resolve(1); // or // return Promise.reject("Failure"); } demo().then( (value) => { document.write(value); return ++value; }, (message) => { document.write(message); } ).then( (value) => { document.write(value); }, (message) => { document.write(message); } )</script> Output: Function called!! 12 Example 5: Using then() as an asynchronous function JavaScript <script type="text/javascript"> var demo = new Promise((resolve, reject) => { resolve(1); }) let call = demo.then( (value) => { console.log(value); return ++value; }, (message) => { document.write(message); }); console.log(call); setTimeout(() => { console.log(call); });</script> Console Output: Promise {status: "pending"} 1 Promise {status: "resolved", result: 2} Supported Browsers: Google Chrome 6.0 and above Internet Explorer 9.0 and above Mozilla 4.0 and above Opera 11.1 and above Safari 5.0 and above ysachin2314 JavaScript-Misc Picked CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Sep, 2021" }, { "code": null, "e": 296, "s": 54, "text": "The then() method in JavaScript has been defined in the Promise API and is used to deal with asynchronous tasks such as an API call. Previously, callback functions were used ...
PostgreSQL – HAVING clause
28 Aug, 2020 PostgreSQL has a HAVING clause that is used to eliminate groups of rows that do not meet specific criteria or conditions. Ii generally used in conjunction with the GROUP BY clause to filter group rows that do not satisfy a specified condition. Syntax: SELECT column_1, aggregate_function (column_2) FROM tbl_name GROUP BY column_1 HAVING condition; Now let’s analyze the above syntax: In the above syntax the aggregate_function represents functions like SUM(), COUNT() etc. The HAVING clause provides the condition for group rows created by the GROUP BY clause. The WHERE clause sets the condition fro each row before the GROUP BY clause is applied. For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.Example 1:Here we will query to selects the only customer who has been spending more than 200 USD using the HAVING clause in the “payment” table of our sample database. SELECT customer_id, SUM (amount) FROM payment GROUP BY customer_id HAVING SUM (amount) > 200; Output: Example 2: Here we will query to select the stores that has more than 200 customers using the HAVING clause in the “customer” table of our sample database. SELECT store_id, COUNT (customer_id) FROM customer GROUP BY store_id HAVING COUNT (customer_id) > 200; Output: postgreSQL-clauses PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Aug, 2020" }, { "code": null, "e": 298, "s": 54, "text": "PostgreSQL has a HAVING clause that is used to eliminate groups of rows that do not meet specific criteria or conditions. Ii generally used in conjunction with the GROUP BY c...
Convert Excel to PDF Using Python
24 Feb, 2021 Python is a high-level, general-purpose, and very popular programming language. Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting-edge technology in Software Industry. In this article, we will learn how to convert an Excel File to PDF File Using Python Here we will use the win32com module for file conversion. Python extensions for Microsoft Windows Provide access to much of the Win32 API, the ability to create and use COM objects, and the Pythonwin environment. pip install pywin32 Approach: First, we will create a COM Object Using Dispatch() method. Then we will read the Excel file pass “Excel.Application” inside the Dispatch method Pass Excel file path Then we will convert it into PDF using the ExportAsFixedFormat() method ExportAsFixedFormat():- The ExportAsFixedFormat method is used to publish a workbook in either PDF or XPS format. Syntax: ExportAsFixedFormat (Type, FileName, Quality, IncludeDocProperties, IgnorePrintAreas, From, To, OpenAfterPublish, FixedFormatExtClassPtr) Excel File click here Input: EXCEL FILE Below is the Implementation: Python3 # Import Modulefrom win32com import client # Open Microsoft Excelexcel = client.Dispatch("Excel.Application") # Read Excel Filesheets = excel.Workbooks.Open('Excel File Path')work_sheets = sheets.Worksheets[0] # Convert into PDF Filework_sheets.ExportAsFixedFormat(0, 'PDF File Path') Output: PDF FILE python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python Read a file line by line in Python Different ways to create Pandas Dataframe How to Install PIP on Windows ? Python String | replace() Python Classes and Objects Python OOPs Concepts Introduction To PYTHON *args and **kwargs in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Feb, 2021" }, { "code": null, "e": 280, "s": 28, "text": "Python is a high-level, general-purpose, and very popular programming language. Python programming language (latest Python 3) is being used in web development, Machine Learnin...
Flexbox - Quick Guide
Cascading Style Sheets (CSS) is a simple design language intended to simplify the process of making web pages presentable. CSS handles the look and feel part of a web page. Using CSS, you can control the color of the text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what background images or colors are used, layout designs, variations in display for different devices and screen sizes as well as a variety of other effects. To determine the position and dimensions of the boxes, in CSS, you can use one of the layout modes available − The block layout − This mode is used in laying out documents. The block layout − This mode is used in laying out documents. The inline layout − This mode is used in laying out text. The inline layout − This mode is used in laying out text. The table layout − This mode is used in laying out tables. The table layout − This mode is used in laying out tables. The table layout − This mode is used in positioning the elements. The table layout − This mode is used in positioning the elements. All these modes are used to align specific elements like documents, text, tables, etc., however, none of these provides a complete solution to lay out complex websites. Initially this is used to be done using a combination of floated elements, positioned elements, and table layout (often). But floats only allow to horizontally position the boxes. In addition to the above-mentioned modes, CSS3 provides another layout mode Flexible Box, commonly called as Flexbox. Using this mode, you can easily create layouts for complex applications and web pages. Unlike floats, Flexbox layout gives complete control over the direction, alignment, order, size of the boxes. Following are the notable features of Flexbox layout − Direction − You can arrange the items on a web page in any direction such as left to right, right to left, top to bottom, and bottom to top. Direction − You can arrange the items on a web page in any direction such as left to right, right to left, top to bottom, and bottom to top. Order − Using Flexbox, you can rearrange the order of the contents of a web page. Order − Using Flexbox, you can rearrange the order of the contents of a web page. Wrap − In case of inconsistent space for the contents of a web page (in single line), you can wrap them to multiple lines (both horizontally) and vertically. Wrap − In case of inconsistent space for the contents of a web page (in single line), you can wrap them to multiple lines (both horizontally) and vertically. Alignment − Using Flexbox, you can align the contents of the webpage with respect to their container. Alignment − Using Flexbox, you can align the contents of the webpage with respect to their container. Resize − Using Flexbox, you can increase or decrease the size of the items in the page to fit in available space. Resize − Using Flexbox, you can increase or decrease the size of the items in the page to fit in available space. Following are the browsers that support Flexbox. Chrome 29+ Firefox 28+ Internet Explorer 11+ Opera 17+ Safari 6.1+ Android 4.4+ iOS 7.1+ To use Flexbox in your application, you need to create/define a flex container using the display property. Usage − display: flex | inline-flex This property accepts two values flex − Generates a block level flex container. flex − Generates a block level flex container. inline-flex − Generates an inline flex container box. inline-flex − Generates an inline flex container box. Now, we will see how to use the display property with examples. On passing this value to the display property, a block level flex container will be created. It occupies the full width of the parent container (browser). The following example demonstrates how to create a block level flex container. Here, we are creating six boxes with different colors and we have used the flex container to hold them. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .container{ display:flex; } .box{ font-size:35px; padding:15px; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − Since we have given the value flex to the display property, the container uses the width of the container (browser). You can observe this by adding a border to the container as shown below. .container { display:inline-flex; border:3px solid black; } It will produce the following result − On passing this value to the display property, an inline level flex container will be created. It just takes the place required for the content. The following example demonstrates how to create an inline flex container. Here, we are creating six boxes with different colors and we have used the inline-flex container to hold them. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .container{ display:inline-flex; border:3px solid black; } .box{ font-size:35px; padding:15px; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − Since we have used an inline flex container, it just took the space that is required to wrap its elements. The flex-direction property is used to specify the direction in which the elements of flex container (flex-items) are needed to be placed. usage − flex-direction: row | row-reverse | column | column-reverse This property accepts four values − row − Arranges the elements of the container horizontally from left to right. row − Arranges the elements of the container horizontally from left to right. row-reverse − Arranges the elements of the container horizontally from right to left. row-reverse − Arranges the elements of the container horizontally from right to left. column − Arranges the elements of the container vertically from left to right. column − Arranges the elements of the container vertically from left to right. column-reverse − Arranges the elements of the container vertically from right to left. column-reverse − Arranges the elements of the container vertically from right to left. Now, we will take a few examples to demonstrate the use of the direction property. On passing this value to the direction property, the elements of the container are arranged horizontally from left to right as shown below. The following example demonstrates the result of passing the value row to the flex-direction property. Here, we are creating six boxes with different colors with the flex-direction value row. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:inline-flex; border:3px solid black; flex-direction:row; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the direction property, the elements of the container are arranged horizontally from right to left as shown below. The following example demonstrates the result of passing the value row-reverse to the flex-direction property. Here, we are creating six boxes with different colors with the flex-direction value row-reverse. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:inline-flex; border:3px solid black; flex-direction:row-reverse; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the direction property, the elements of the container are arranged vertically from top to bottom as shown below. The following example demonstrates the result of passing the value column to the flex-direction property. Here, we are creating six boxes with different colors with the flex-direction value column. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:inline-flex; border:3px solid black; flex-direction:column; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the direction property, the elements of the container are arranged vertically from bottom to top as shown below. The following example demonstrates the result of passing the value column-reverse to the flex-direction property. Here, we are creating six boxes with different colors with the flex-direction value column-reverse. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:inline-flex; border:3px solid black; flex-direction:column-reverse; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − Generally, in case of insufficient space for the container, the rest of the flex items will be hidden as shown below. The flex-wrap property is used to specify the controls whether the flex-container is single-line or multi-line. usage − flex-wrap: nowrap | wrap | wrap-reverse flex-direction: column | column-reverse This property accepts the following values − wrap − In case of insufficient space for them, the elements of the container (flexitems) will wrap into additional flex lines from top to bottom. wrap − In case of insufficient space for them, the elements of the container (flexitems) will wrap into additional flex lines from top to bottom. wrap-reverse − In case of insufficient space for them, the elements of the container (flex-items) will wrap into additional flex lines from bottom to top. wrap-reverse − In case of insufficient space for them, the elements of the container (flex-items) will wrap into additional flex lines from bottom to top. Now, we will see how to use the wrap property, with examples. On passing the value wrap to the property flex-wrap, the elements of the container are arranged horizontally from left to right as shown below. The following example demonstrates the result of passing the value wrap to the flex-wrap property. Here, we are creating six boxes with different colors with the flex-direction value row. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; width:100px; } .container{ display:flex; border:3px solid black; flex-direction:row; flex-wrap:wrap; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing the value wrap-reverse to the property flex-wrap, the elements of the container are arranged horizontally from left to right as shown below. The following example demonstrates the result of passing the value wrap-reverse to the flex-wrap property. Here, we are creating six boxes with different colors with the flex-direction value row. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; width:100px; } .container{ display:flex; border:3px solid black; flex-direction:row; flex-wrap:wrap-reverse; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing the value wrap to the property flex-wrap and the value column to the property flex-direction, the elements of the container are arranged horizontally from left to right as shown below. The following example demonstrates the result of passing the value wrap to the flex-wrap property. Here, we are creating six boxes with different colors with the flex-direction value column. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; width:100px; } .container{ display:flex; border:3px solid black; flex-direction:column; flex-wrap:wrap; height:100vh; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing the value wrap-reverse to the property flex-wrap and the value column to the property flex-direction, the elements of the container are arranged horizontally from left to right as shown below. The following example demonstrates the result of passing the value wrap-reverse to the flex-wrap property. Here, we are creating six boxes with different colors and the with the flex-direction value column. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; width:100px; } .container{ display:flex; border:3px solid black; flex-direction:column; flex-wrap:wrap-reverse; height:100vh; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − Often you can observe an extra space left in the container after arranging the flex items as shown below. Using the property justify-content, you can align the contents along the main axis by distributing the extra space as intended. You can also adjust the alignment of the flexitems, in case they overflow the line. usage − justify-content: flex-start | flex-end | center | space-between | space-around| space-evenly; This property accepts the following values − flex-start − The flex-items are placed at the start of the container. flex-start − The flex-items are placed at the start of the container. flex-end − The flex-items are placed at the end of the container. flex-end − The flex-items are placed at the end of the container. center − The flex-items are placed at the center of the container, where the extra space is equally distributed at the start and at the end of the flex-items. center − The flex-items are placed at the center of the container, where the extra space is equally distributed at the start and at the end of the flex-items. space-between − The extra space is equally distributed between the flex-items. space-between − The extra space is equally distributed between the flex-items. space-around − The extra space is equally distributed between the flex items such that the space between the edges of the container and its contents is half as the space between the flex-items. space-around − The extra space is equally distributed between the flex items such that the space between the edges of the container and its contents is half as the space between the flex-items. Now, we will see how to use the justify-content property, with examples. On passing this value to the property justify-content, the flex-items are placed at the start of the container. The following example demonstrates the result of passing the value flex-start to the justify-content property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; border:3px solid black; justify-content:flex-start; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property justify-content, the flex-items are placed at the end of the container. The following example demonstrates the result of passing the value flex-end to the justify-content property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; border:3px solid black; justify-content:flex-end; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property justify-content, the flex-items are placed at the center of the container, where the extra space is equally distributed at the start and at the end of the flex-items. The following example demonstrates the result of passing the value center to the justify-content property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; border:3px solid black; justify-content:center; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property justify-content, the extra space is equally distributed between the flex items such that the space between any two flex-items is the same and the start and end of the flex-items touch the edges of the container. The following example demonstrates the result of passing the value space-between to the justify-content property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; border:3px solid black; justify-content:space-between; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property justify-content, the extra space is equally distributed between the flex-items such that the space between any two flex-items is the same. However, the space between the edges of the container and its contents (the start and end of the flex-items) is half as the space between the flex items. The following example demonstrates the result of passing the value space-around to the justify-content property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; border:3px solid black; justify-content:space-around; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property justify-content, the extra space is equally distributed between the flex-items such that the space between any two flex-items is the same (including the space to the edges). The following example demonstrates the result of passing the value space-evenly to the justify-content property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; border:3px solid black; justify-content:space-evenly; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − The align-items property is same as justify content. But here, the items were aligned across the cross access (vertically). Usage − align-items: flex-start | flex-end | center | baseline | stretch; This property accepts the following values − flex-start − The flex items were aligned vertically at the top of the container. flex-start − The flex items were aligned vertically at the top of the container. flex-end − The flex items were aligned vertically at the bottom of the container. flex-end − The flex items were aligned vertically at the bottom of the container. flex-center − The flex items were aligned vertically at the center of the container. flex-center − The flex items were aligned vertically at the center of the container. stretch − The flex items were aligned vertically such that they fill up the whole vertical space of the container. stretch − The flex items were aligned vertically such that they fill up the whole vertical space of the container. baseline − The flex items were aligned such that the baseline of their text align along a horizontal line. baseline − The flex items were aligned such that the baseline of their text align along a horizontal line. On passing this value to the property align-items, the flex items were aligned vertically at the top of the container. The following example demonstrates the result of passing the value flex-start to the align-items property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; height:100vh; align-items:flex-start; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property align-items, the flex-items are aligned vertically at the bottom of the container. The following example demonstrates the result of passing the value flex-end to the align-items property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; height:100vh; align-items:flex-end; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property align-items, the flex-items are aligned vertically at the center of the container. The following example demonstrates the result of passing the value flex-center to the align-items property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; height:100vh; align-items:center; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property align-items, the flex-items are aligned vertically such that they fill up the whole vertical space of the container. The following example demonstrates the result of passing the value stretch to the align-items property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; height:100vh; align-items:stretch; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property align-items, the flex-items are aligned such that the baseline of their text align along a horizontal line. The following example demonstrates the result of passing the value baseline to the align-items property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; height:100vh; align-items:baseline; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − In case the flex-container has multiple lines (when, flex-wrap: wrap), the align-content property defines the alignment of each line within the container. Usage − align-content: flex-start | flex-end | center | space-between | space-around | stretch; This property accepts the following values − stretch − The lines in the content will stretch to fill up the remaining space. stretch − The lines in the content will stretch to fill up the remaining space. flex-start − All the lines in the content are packed at the start of the container. flex-start − All the lines in the content are packed at the start of the container. flex-end − All the lines in the content are packed at the end of the container. flex-end − All the lines in the content are packed at the end of the container. center − All the lines in the content are packed at the center of the container. center − All the lines in the content are packed at the center of the container. space-between − The extra space is distributed between the lines evenly. space-between − The extra space is distributed between the lines evenly. space-around − The extra space is distributed between the lines evenly with equal space around each line (including the first and last lines) space-around − The extra space is distributed between the lines evenly with equal space around each line (including the first and last lines) On passing this value to the property align-content, all the lines are packed at the center of the container. The following example demonstrates the result of passing the value center to the align-content property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:25px; padding:15px; width:43%; } .container{ display:flex; height:100vh; flex-wrap:wrap; align-content:center; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property align-content, all the lines are packed at the start of the container. The following example demonstrates the result of passing the value flex-start to the align-content property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:25px; padding:15px; width:40%; } .container{ display:flex; height:100vh; flex-wrap:wrap; align-content:flex-start; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property align-content, all the lines are packed at the end of the container. The following example demonstrates the result of passing the value flex-end to the align-content property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:25px; padding:15px; width:40%; } .container{ display:flex; height:100vh; flex-wrap:wrap; align-content:flex-end; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property align-content, the lines will stretch to fill up the remaining space. The following example demonstrates the result of passing the value stretch to the align-content property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:25px; padding:15px; width:40; } .container{ display:flex; height:100vh; flex-wrap:wrap; align-content:stretch; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property align-content, the extra space is distributed between the lines evenly with equal space around each line (including the first and last lines). The following example demonstrates the result of passing the value space-around to the align-content property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:25px; padding:15px; width:40%; } .container{ display:flex; height:100vh; flex-wrap:wrap; align-content:space-around; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property align-content, the extra space is distributed between the lines evenly, where the first line will be at the top and the last line will be at the bottom of the container. The following example demonstrates the result of passing the value space-between to the align-content property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:25px; padding:15px; width:40%; } .container{ display:flex; height:100vh; flex-wrap:wrap; align-content:space-between; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − The flex-order property is used to define the order of the flexbox item. The following example demonstrates the order property. Here we are creating six colored boxes with the labels one, two, three, four, five, six, arranged in the same order, and we are reordering them in the order one, two, five, six, three, four, using the flex-order property. <!doctype html> <html lang = "en"> <style> .box{ font-size:35px; padding:15px; } .box1{background:green;} .box2{background:blue;} .box3{background:red; order:1} .box4{background:magenta; order:2} .box5{background:yellow;} .box6{background:pink;} .container{ display:inline-flex; border:3px solid black; flex-direction:rows; flex-wrap:wrap; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − You can also assign –ve values to the order as shown below. <!doctype html> <html lang = "en"> <style> .box{ font-size:35px; padding:15px; } .box1{background:green;} .box2{background:blue;} .box3{background:red; order:-1} .box4{background:magenta; order:-2} .box5{background:yellow;} .box6{background:pink;} .container{ display:inline-flex; border:3px solid black; flex-direction:row; flex-wrap:wrap; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − We use the flex-basis property to define the default size of the flex-item before the space is distributed. The following example demonstrates the usage of the flex-basis property. Here we are creating 3 colored boxes and fixing their size to 150 px. <!doctype html> <html lang = "en"> <style> .box{ font-size:15px; padding:15px; } .box1{background:green; flex-basis:150px; } .box2{background:blue; flex-basis:150px;} .box3{background:red; flex-basis:150px;} .container{ display:flex; height:100vh; align-items:flex-start; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> </div> </body> </html> It will produce the following result − We use the flex-grow property to set the flex-grow factor. In case of excess space in the container, it specifies how much a particular flex-item should grow. <!doctype html> <html lang = "en"> <style> .box{ font-size:15px; padding:15px; } .box1{background:green; flex-grow:10; flex-basis:100px; } .box2{background:blue; flex-grow:1; flex-basis:100px; } .box3{background:red; flex-grow:1; flex-basis:100px; } .container{ display:flex; height:100vh; align-items:flex-start; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> </div> </body> </html> It will produce the following result − We use the flex-shrink property is used to set the flex shrink-factor. In case there is not enough space in the container, it specifies how much a flex-item should shrink. <!doctype html> <html lang = "en"> <style> .box{ font-size:15px; padding:15px; } .box1{background:green; flex-basis:200px; flex-shrink:10} .box2{background:blue; flex-basis:200px; flex-shrink:1} .box3{background:red; flex-basis:200px; flex-shrink:1} .container{ display:flex; height:100vh; align-items:flex-start; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> </div> </body> </html> It will produce the following result − There is a shorthand to set values to all these three properties at once; it is called flex. Using this property, you can set values to flex-grow, flex-shrink, and flex-basis values at once. Here is the syntax of this property. .item { flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ] } This property is similar to align-items, but here, it is applied to individual flex items. Usage − align-self: auto | flex-start | flex-end | center | baseline | stretch; This property accepts the following values − flex-start − The flex item will be aligned vertically at the top of the container. flex-start − The flex item will be aligned vertically at the top of the container. flex-end − The flex item will be aligned vertically at the bottom of the container. flex-end − The flex item will be aligned vertically at the bottom of the container. flex-center − The flex item will be aligned vertically at the center of the container. flex-center − The flex item will be aligned vertically at the center of the container. Stretch − The flex item will be aligned vertically such that it fills up the whole vertical space of the container. Stretch − The flex item will be aligned vertically such that it fills up the whole vertical space of the container. baseline − The flex item will be aligned at the base line of the cross axis. baseline − The flex item will be aligned at the base line of the cross axis. On passing this value to the property align-self, a particular flex-item will be aligned vertically at the top of the container. The following example demonstrates the result of passing the value flex-start to the align-self property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta; align-self:start;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; height:100vh; border:3px solid black; align-items:flex-start; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property align-self, a particular flex-item will be aligned vertically at the bottom of the container. The following example demonstrates the result of passing the value flex-end to the align-self property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta; align-self:flex-end;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; height:100vh; border:3px solid black; align-items:flex-start; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing the value center to the property align-self, a particular flex-item will be aligned vertically at the center of the container. The following example demonstrates the result of passing the value center to the align-self property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta; align-self:center;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; height:100vh; border:3px solid black; align-items:flex-start; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property align-self, a particular flex item it will be aligned vertically such that it fills up the whole vertical space of the container. The following example demonstrates the result of passing the value stretch to the align-self property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta; align-self:stretch;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; height:100vh; border:3px solid black; align-items:flex-start; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 87 Lectures 11 hours Code And Create 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 1984, "s": 1811, "text": "Cascading Style Sheets (CSS) is a simple design language intended to simplify the process of making web pages presentable. CSS handles the look and feel part of a web page." }, { "code": null, "e": 2281, "s": 1984, "text": "Using CSS...
Create a HashMap in Java
To create a HashMap, use the HashMap map and new − HashMap hm = new HashMap(); Now, set elements − hm.put("Finance", new Double(999.87)); hm.put("Operations", new Double(298.64)); hm.put("Marketing", new Double(39.56)); Display the elements now using the following code − Live Demo import java.util.*; public class Demo { public static void main(String args[]) { // Create a hash map HashMap hm = new HashMap(); // Put elements to the map hm.put("Finance", new Double(999.87)); hm.put("Operations", new Double(298.64)); hm.put("Marketing", new Double(39.56)); // Get a set of the entries Set set = hm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); } } Finance: 999.87 Operations: 298.64 Marketing: 39.56
[ { "code": null, "e": 1113, "s": 1062, "text": "To create a HashMap, use the HashMap map and new −" }, { "code": null, "e": 1141, "s": 1113, "text": "HashMap hm = new HashMap();" }, { "code": null, "e": 1161, "s": 1141, "text": "Now, set elements −" }, { ...
Animating Yourself as a Disney Character with AI | by Fathy Rashad | Towards Data Science
Last week, I was surfing the internet and stumbled upon an interesting article on StyleGAN2 network blending by Justin Pinkney. What’s so interesting about it? Someone made a cool app with the idea! Doron Adler fine-tuned a StyleGAN2 model with Disney characters and then mixed the layers with the real face model (FFHQ) and generated Disney characters based on real faces. Then, Justin Pinkney followed up by making the model available on Toonify. You can simply upload your picture and instantly get your Disney character. Try it out! But, in this article, we will learn how to do this programmatically and also animate the character! GANStyleGANToonification with Layer SwappingAnimating with First Order MotionTutorial GAN StyleGAN Toonification with Layer Swapping Animating with First Order Motion Tutorial If you do not want to learn the theory and go straight to coding, you can skip to the tutorial. The core mechanism behind this character generation is a concept called Generative Adversarial Network (GAN) which is extremely popular right now in the community due to its generative applications. What is GAN? It’s basically 2 networks trying to compete with each other, the generator and the discriminator. The generator tries to fool the discriminator into believing its generated image to be real, while the discriminator tries to classify between the real image and the fake (generated) image. The discriminator will be trained first by showing it the real image from the dataset and random noise (images from the untrained generator). As the data distribution is very different, the discriminator will be able to differentiate easily. Disclaimer: The illustration may not exactly accurate in representing what’s happening in GAN as I try to simplify it as much as possible. Then, we will switch to train the generator while freezing the discriminator. The generator will learn how to generate better images based on the output of the discriminator (real or fake) until the discriminator cannot discriminate correctly anymore. Then, we switch back to training the discriminator and the cycle continues with both of them getting better until the generator reached the point of generating a very realistic image and you can stop the training. In 2018, NVIDIA published a groundbreaking paper that manages to generate high-quality images (1024x1024) titled “A Style-Based Generator Architecture for Generative Adversarial Networks”. One of the novelty is that it disentangles the latent space which allows us to control the attributes at a different level. For example, the lower layer would be able to control the pose and head shape while the higher layer control high level features such as the lighting or texture. The disentanglement is done by introducing an additional mapping network that maps the input z (noise/random vector sampled from a normal distribution) to separate vector w and feed it into different levels of the layers. Hence, each part of the z input control a different level of features Hence, if we change the input in the lower layer (4x4, 8x8), we would have variations in the high-level features such as the head shape, hairstyle, and pose. On the other hand, if you change the input for the higher layer (512x512, 1024x1024), we would have variations in the finer features such as the lighting, skin color, and hair color. We can attempt to further visualize the disentanglement by analyzing the activation maps and cluster the activations as done by this paper. The color represents a cluster formed where you can think of it as the controllable part of the image. In the last layer, you can see that different parts of the lighting are represented as different clusters. In the middle layers, the facial feature such as the eye, nose, or mouth is represented as different clusters which means this is where the variations in the facial features are controlled. Finally, in the first few layers, different parts of the head are represented as different clusters which proves that it controls the shape, pose, and hairstyle of the person. You can watch the presentation video of the paper here. crossminds.ai Besides the disentanglement, StyleGAN also made several other improvements such as progressive growing architecture. Although they switched to architecture similar to MSG-GAN in StyleGAN2. For the latest update, you can read the paper or just watch the StyleGAN2 demo video below. crossminds.ai I also use the website to keep track of new papers on CVPR and ECCV this year. So, it’s pretty useful. The particular disentanglement feature of StyleGAN is what enables us to mix different models and generate Disney characters from a face. If the first few layers control the facial feature and the last few-layer control the texture, what if we swap the last few layers with another model’s layers? For example, if we use the weights of the face model for the first few layers and the weights of the painting model for the rest of the layer, it will generate the face with the painting style! Moreover, not only it can copy the texture of the second model, but it also able to copy the facial feature style of the different models such Disney character eye or mouth. After we generated the Disney character, why not take it to another level and animate it? An interesting paper titled “First Order Motion Model for Image Animation” provided us just the ability to do that. Basically, it tries to learn the motions from the driving video using keypoints and attempts to morph the input image to enact the motion. Now that we understand a bit about the concept, let’s do it and code! Luckily, Justin Pinkney made his Toonification model available and created a Colab for it. I made another Colab notebook which is basically his code with additional code for the animation modified from Aliaksandr Siarohin’s notebook. Here is the Colab notebook for you to follow along! First, make sure you are using GPU runtime and Tensorflow 1. %tensorflow_version 1.x Note: % is a special command in Colab, it will not work if you are doing this locally Next, we clone the repo and create folders that we will use. !git clone https://github.com/justinpinkney/stylegan2%cd stylegan2!nvcc test_nvcc.cu -o test_nvcc -run!mkdir raw!mkdir aligned!mkdir generate Note: ‘!’ is used to run a shell command in Colab, if you are doing this locally, simply run the command on your shell/console. Next, upload your image inside the raw folder, we will use a script to crop the face and resize the image, hence your image does not have to be a full face. But for better results, make sure your face would have at least 256x256 resolution. In this example, we will use the Elon Musk image as an example. !wget https://drive.google.com/uc?id=1ZwjotR2QWSS8jaJ12Xj00tXfM0V_nD3c -O raw/example.jpg Then, we will load the blended model of the real face and Disney character by Doron’s Adler and also the normal FFHQ face model. Why did we need to load the normal real face (FFHQ) model as well? Remember that the StyleGAN model only takes the latent vector z and generates a face based on the latent vector. It does not take an image and transform the image like Image-to-Image translation model. So how do we generate a face that we want? StyleGAN2 introduces a method of projecting to the latent space. Basically, we can try to find the matching latent vector for our desired image using gradient descent. But before we try to find the matching latent vector, we need to crop and align the image first. !python align_images.py raw aligned The script takes the source image directory and the output directory as the input and will crop and align our face properly. Finally, we will project the image to the latent space. !python project_images.py --num-steps 500 aligned generated The script will take the images in the aligned directory and create the latent vector saved as .npy file in the generated folder. Now that we have the latent vector, we can try to generate the faces using our blended Disney model. The generated images are saved inside the generated folder. We can display the images inside the notebook. Voila! We have a Disney-fied Elon Musk, but we are not done yet. Let’s animate this! First, let’s clone Aliaksanr's repo on the first-order model. !git clone https://github.com/AliaksandrSiarohin/first-order-model Then, we will set up a path, so we do not have to be in the first-order-model directory todo the python import or you can just cd to the directory. Then, before we load the keypoint and video generator model, we need to download the pre-trained weight first. The file is quite big ~700 MB, and you may need to download it manually as Google does not allow the download of large files with wget. !wget "https://drive.google.com/uc?export=download&id=1jmcn19-c3p8mf39aYNXUhdMqzqDYZhQ_" -O vox-cpk.pth.tar Load the first-order model using the downloaded weight just now. Next, we need a driving video from where we would source the animation from. You can use the example video or upload your own video. If you upload a video, make sure to change the file path accordingly. !wget https://drive.google.com/uc?id=1LjDoFmeP0hZQSsUmnou0UbQJJzQ8rMLR -O src_video.mp4 Finally, we can generate the animation! Yay! We finally animated our character. Congratulations to you if you manage to reach this point 🎉 There are a lot of things we can still experiment on. What if we blend other models such as the painting's model or we can also reverse blend the Disney character and paintings where we generate a real face based on a Disney character or the painting. We can also try to incorporate Deepfake and swap the faces within Disney movies with our Disney character. If you enjoyed my writings, check out my other articles! towardsdatascience.com towardsdatascience.com Feel free to connect with me on Linkedin as well. www.linkedin.com [1] Karras, T., Laine, S., & Aila, T. (2019). A style-based generator architecture for generative adversarial networks. In Proceedings of the IEEE conference on computer vision and pattern recognition (pp. 4401–4410). [2] Karras, T., Laine, S., Aittala, M., Hellsten, J., Lehtinen, J., & Aila, T. (2020). Analyzing and improving the image quality of stylegan. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (pp. 8110–8119). [3]Siarohin, A., Lathuilière, S., Tulyakov, S., Ricci, E., & Sebe, N. (2019). First order motion model for image animation. In Advances in Neural Information Processing Systems (pp. 7137–7147). [4] Collins, E., Bala, R., Price, B., & Susstrunk, S. (2020). Editing in Style: Uncovering the Local Semantics of GANs. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (pp. 5771–5780).
[ { "code": null, "e": 546, "s": 172, "text": "Last week, I was surfing the internet and stumbled upon an interesting article on StyleGAN2 network blending by Justin Pinkney. What’s so interesting about it? Someone made a cool app with the idea! Doron Adler fine-tuned a StyleGAN2 model with Disney cha...
Installing Realtek RTL8821CE Driver to use the Wireless Network Interface in Ubuntu - GeeksforGeeks
24 Dec, 2020 If you dual boot your Laptop or PC with any other OS and you restart Ubuntu then it will show Error[Wireless connection is not present or no network devices are available]. This issue may happen also due to the installations of unwanted software in Ubuntu. Problem: Wireless network (Wi-Fi) option is not available. Follow the below steps to get back the Wi-Fi option on Ubuntu Note: First connect a wired device to your laptop so that you can use internet services to follow further steps. Step 1: Open Terminal using Ctrl+Alt+T. Step 2: Update system packages using the following command. sudo apt-get update Step 3: Install the required packages using the following command. sudo apt install git build-essential dkms Step 4: Clone the Realtek RTL8821CE Driver using the following command. git clone https://github.com/tomaspinho/rtl8821ce Step 5: Move to the repository directory using the following command. cd rtl8821ce Step 6: Use the following command to make the script of dkms-installation executable. chmod +x dkms-install.sh Step 7: Make the dkms-remove script executable. chmod +x dkms-remove.sh Step 8: Execute the installation script using the below-mentioned command. sudo ./dkms-install.sh After doing these steps restart your PC, and now you can see that the wireless network option is available. Technical Scripter 2020 Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25677, "s": 25649, "text": "\n24 Dec, 2020" }, { "code": null, "e": 25934, "s": 25677, "text": "If you dual boot your Laptop or PC with any other OS and you restart Ubuntu then it will show Error[Wireless connection is not present or no network devices are av...
Null Pointer Exception In Java - GeeksforGeeks
04 Mar, 2022 NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attempts to use an object reference that has the null value.These can be: Invoking a method from a null object. Accessing or modifying a null object’s field. Taking the length of null, as if it were an array. Accessing or modifying the slots of null object, as if it were an array. Throwing null, as if it were a Throwable value. When you try to synchronize over a null object. Why do we need the null value? Null is a special value used in Java. It is mainly used to indicate that no value is assigned to a reference variable. One application of null is in implementing data structures like linked list and tree. Other applications include Null Object pattern (See this for details) and Singleton pattern. The Singleton pattern ensures that only one instance of a class is created and also, aims for providing a global point of access to the object.A sample way to create at most one instance of a class is to declare all its constructors as private and then, create a public method that returns the unique instance of the class: Java // To use randomUUID function.import java.util.UUID;import java.io.*; class Singleton{ // Initializing values of single and ID to null. private static Singleton single = null; private String ID = null; private Singleton() { /* Make it private, in order to prevent the creation of new instances of the Singleton class. */ // Create a random ID ID = UUID.randomUUID().toString(); } public static Singleton getInstance() { if (single == null) single = new Singleton(); return single; } public String getID() { return this.ID; }} // Driver Codepublic class TestSingleton{ public static void main(String[] args) { Singleton s = Singleton.getInstance(); System.out.println(s.getID()); }} Output: 10099197-8c2d-4638-9371-e88c820a9af2 In above example, a static instance of the singleton class. That instance is initialized at most once inside the Singleton getInstance method.How to avoid the NullPointerException? To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.Following are the common problems with the solution to overcome that problem. Case 1 : String comparison with literals A very common case problem involves the comparison between a String variable and a literal. The literal may be a String or an element of an Enum. Instead of invoking the method from the null object, consider invoking it from the literal. Java // A Java program to demonstrate that invoking a method// on null causes NullPointerExceptionimport java.io.*; class GFG{ public static void main (String[] args) { // Initializing String variable with null value String ptr = null; // Checking if ptr.equals null or works fine. try { // This line of code throws NullPointerException // because ptr is null if (ptr.equals("gfg")) System.out.print("Same"); else System.out.print("Not Same"); } catch(NullPointerException e) { System.out.print("NullPointerException Caught"); } }} Output: NullPointerException Caught We can avoid NullPointerException by calling equals on literal rather than object. Java // A Java program to demonstrate that we can avoid// NullPointerExceptionimport java.io.*; class GFG{ public static void main (String[] args) { // Initializing String variable with null value String ptr = null; // Checking if ptr is null using try catch. try { if ("gfg".equals(ptr)) System.out.print("Same"); else System.out.print("Not Same"); } catch(NullPointerException e) { System.out.print("Caught NullPointerException"); } }} Output: Not Same Case 2 : Keeping a Check on the arguments of a method Before executing the body of your new method, we should first check its arguments for null values and continue with execution of the method, only when the arguments are properly checked. Otherwise, it will throw an IllegalArgumentException and notify the calling method that something is wrong with the passed arguments. Java // A Java program to demonstrate that we should// check if parameters are null or not before// using them.import java.io.*; class GFG{ public static void main (String[] args) { // String s set an empty string and calling getLength() String s = ""; try { System.out.println(getLength(s)); } catch(IllegalArgumentException e) { System.out.println("IllegalArgumentException caught"); } // String s set to a value and calling getLength() s = "GeeksforGeeks"; try { System.out.println(getLength(s)); } catch(IllegalArgumentException e) { System.out.println("IllegalArgumentException caught"); } // Setting s as null and calling getLength() s = null; try { System.out.println(getLength(s)); } catch(IllegalArgumentException e) { System.out.println("IllegalArgumentException caught"); } } // Function to return length of string s. It throws // IllegalArgumentException if s is null. public static int getLength(String s) { if (s == null) throw new IllegalArgumentException("The argument cannot be null"); return s.length(); }} Output: 0 13 IllegalArgumentException caught Case 3 : Use of Ternary Operator The ternary operator can be used to avoid NullPointerException. First, the Boolean expression is evaluated. If the expression is true then, the value1 is returned, otherwise, the value2 is returned. We can use the ternary operator for handling null pointers: Java // A Java program to demonstrate that we can use// ternary operator to avoid NullPointerException.import java.io.*; class GFG{ public static void main (String[] args) { // Initializing String variable with null value String str = null; String message = (str == null) ? "" : str.substring(0,5); System.out.println(message); // Initializing String variable with null value str = "Geeksforgeeks"; message = (str == null) ? "" : str.substring(0,5); System.out.println(message); }} Output: Geeks The message variable will be empty if str’s reference is null as in case 1. Otherwise, if str point to actual data, the message will retrieve the first 6 characters of it as in case 2.Related Article – Interesting facts about Null in Java This article is contributed by Nikhil Meherwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. simmytarika5 Exception Handling Java-Exceptions Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Stack Class in Java Singleton Class in Java Set in Java Multithreading in Java Collections in Java Queue Interface In Java Initializing a List in Java
[ { "code": null, "e": 25673, "s": 25645, "text": "\n04 Mar, 2022" }, { "code": null, "e": 25907, "s": 25673, "text": "NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attem...
Python | Repeating tuples N times - GeeksforGeeks
03 Nov, 2019 Sometimes, while working with data, we might have a problem in which we need to replicate, i.e construct duplicates of tuples. This is important application in many domains of computer programming. Let’s discuss certain ways in which this task can be performed. Method #1 : Using * operatorThe multiplication operator can be used to construct the duplicates of a container. This also can be extended to tuples even though tuples are immutable. # Python3 code to demonstrate working of# Repeating tuples N times# using * operator # initialize tuple test_tup = (1, 3) # printing original tuple print("The original tuple : " + str(test_tup)) # initialize N N = 4 # Repeating tuples N times# using * operatorres = ((test_tup, ) * N) # printing resultprint("The duplicated tuple elements are : " + str(res)) The original tuple : (1, 3) The duplicated tuple elements are : ((1, 3), (1, 3), (1, 3), (1, 3)) Method #2 : Using repeat()The internal function of itertools library, repeat() can be used to achieve the solution to the above problem. # Python3 code to demonstrate working of# Repeating tuples N times# using repeat()from itertools import repeat # initialize tuple test_tup = (1, 3) # printing original tuple print("The original tuple : " + str(test_tup)) # initialize N N = 4 # Repeating tuples N times# using repeat()res = tuple(repeat(test_tup, N)) # printing resultprint("The duplicated tuple elements are : " + str(res)) The original tuple : (1, 3) The duplicated tuple elements are : ((1, 3), (1, 3), (1, 3), (1, 3)) Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25677, "s": 25649, "text": "\n03 Nov, 2019" }, { "code": null, "e": 25939, "s": 25677, "text": "Sometimes, while working with data, we might have a problem in which we need to replicate, i.e construct duplicates of tuples. This is important application in man...
Degree Centrality (Centrality Measure) - GeeksforGeeks
31 Oct, 2019 DegreeIn graph theory, the degree (or valency) of a vertex of a graph is the number of edges incident to the vertex, with loops counted twice.[1] The degree of a vertex is denoted or . The maximum degree of a graph G, denoted by (G), and the minimum degree of a graph, denoted by (G), are the maximum and minimum degree of its vertices. In the graph on the right, the maximum degree is 5 and the minimum degree is 0. In a regular graph, all degrees are the same, and so we can speak of the degree of the graph. Degree CentralityHistorically first and conceptually simplest is degree centrality, which is defined as the number of links incident upon a node (i.e., the number of ties that a node has). The degree can be interpreted in terms of the immediate risk of a node for catching whatever is flowing through the network (such as a virus, or some information). In the case of a directed network (where ties have direction), we usually define two separate measures of degree centrality, namely indegree and outdegree. Accordingly, indegree is a count of the number of ties directed to the node and outdegree is the number of ties that the node directs to others. When ties are associated to some positive aspects such as friendship or collaboration, indegree is often interpreted as a form of popularity, and outdegree as gregariousness. The degree centrality of a vertex , for a given graph with vertices and edges, is defined as Calculating degree centrality for all the nodes in a graph takes in a dense adjacency matrix representation of the graph, and for edges takes in a sparse matrix representation. The definition of centrality on the node level can be extended to the whole graph, in which case we are speaking of graph centralization. Let be the node with highest degree centrality in . Let be the node connected graph that maximizes the following quantity (with being the node with highest degree centrality in ): Correspondingly, the degree centralization of the graph is as follows: The value of is maximized when the graph contains one central node to which all other nodes are connected (a star graph), and in this case . Following is the code for the calculation of the degree centrality of the graph and its various nodes. import networkx as nx def degree_centrality(G, nodes): r"""Compute the degree centrality for nodes in a bipartite network. The degree centrality for a node `v` is the fraction of nodes connected to it. Parameters ---------- G : graph A bipartite network nodes : list or container Container with all nodes in one bipartite node set. Returns ------- centrality : dictionary Dictionary keyed by node with bipartite degree centrality as the value. Notes ----- The nodes input parameter must contain all nodes in one bipartite node set, but the dictionary returned contains all nodes from both bipartite node sets. For unipartite networks, the degree centrality values are normalized by dividing by the maximum possible degree (which is `n-1` where `n` is the number of nodes in G). In the bipartite case, the maximum possible degree of a node in a bipartite node set is the number of nodes in the opposite node set [1]_. The degree centrality for a node `v` in the bipartite sets `U` with `n` nodes and `V` with `m` nodes is .. math:: d_{v} = \frac{deg(v)}{m}, \mbox{for} v \in U , d_{v} = \frac{deg(v)}{n}, \mbox{for} v \in V , where `deg(v)` is the degree of node `v`. """ top = set(nodes) bottom = set(G) - top s = 1.0/len(bottom) centrality = dict((n,d*s) for n,d in G.degree_iter(top)) s = 1.0/len(top) centrality.update(dict((n,d*s) for n,d in G.degree_iter(bottom))) return centrality The above function is invoked using the networkx library and once the library is installed, you can eventually use it and the following code has to be written in python for the implementation of the Degree centrality of a node. import networkx as nxG=nx.erdos_renyi_graph(100,0.5)d=nx.degree_centrality(G)print(d) The result is as follows: {0: 0.5252525252525253, 1: 0.4444444444444445, 2: 0.5454545454545455, 3: 0.36363636363636365, 4: 0.42424242424242425, 5: 0.494949494949495, 6: 0.5454545454545455, 7: 0.494949494949495, 8: 0.5555555555555556, 9: 0.5151515151515152, 10: 0.5454545454545455, 11: 0.5151515151515152, 12: 0.494949494949495, 13: 0.4444444444444445, 14: 0.494949494949495, 15: 0.4141414141414142, 16: 0.43434343434343436, 17: 0.5555555555555556, 18: 0.494949494949495, 19: 0.5151515151515152, 20: 0.42424242424242425, 21: 0.494949494949495, 22: 0.5555555555555556, 23: 0.5151515151515152, 24: 0.4646464646464647, 25: 0.4747474747474748, 26: 0.4747474747474748, 27: 0.494949494949495, 28: 0.5656565656565657, 29: 0.5353535353535354, 30: 0.4747474747474748, 31: 0.494949494949495, 32: 0.43434343434343436, 33: 0.4444444444444445, 34: 0.5151515151515152, 35: 0.48484848484848486, 36: 0.43434343434343436, 37: 0.4040404040404041, 38: 0.5656565656565657, 39: 0.5656565656565657, 40: 0.494949494949495, 41: 0.5252525252525253, 42: 0.4545454545454546, 43: 0.42424242424242425, 44: 0.494949494949495, 45: 0.595959595959596, 46: 0.5454545454545455, 47: 0.5050505050505051, 48: 0.4646464646464647, 49: 0.48484848484848486, 50: 0.5353535353535354, 51: 0.5454545454545455, 52: 0.5252525252525253, 53: 0.5252525252525253, 54: 0.5353535353535354, 55: 0.6464646464646465, 56: 0.4444444444444445, 57: 0.48484848484848486, 58: 0.5353535353535354, 59: 0.494949494949495, 60: 0.4646464646464647, 61: 0.5858585858585859, 62: 0.494949494949495, 63: 0.48484848484848486, 64: 0.4444444444444445, 65: 0.6262626262626263, 66: 0.5151515151515152, 67: 0.4444444444444445, 68: 0.4747474747474748, 69: 0.5454545454545455, 70: 0.48484848484848486, 71: 0.5050505050505051, 72: 0.4646464646464647, 73: 0.4646464646464647, 74: 0.5454545454545455, 75: 0.4444444444444445, 76: 0.42424242424242425, 77: 0.4545454545454546, 78: 0.494949494949495, 79: 0.494949494949495, 80: 0.4444444444444445, 81: 0.48484848484848486, 82: 0.48484848484848486, 83: 0.5151515151515152, 84: 0.494949494949495, 85: 0.5151515151515152, 86: 0.5252525252525253, 87: 0.4545454545454546, 88: 0.5252525252525253, 89: 0.5353535353535354, 90: 0.5252525252525253, 91: 0.4646464646464647, 92: 0.4646464646464647, 93: 0.5555555555555556, 94: 0.5656565656565657, 95: 0.4646464646464647, 96: 0.494949494949495, 97: 0.494949494949495, 98: 0.5050505050505051, 99: 0.5050505050505051} The above result is a dictionary depicting the value of degree centrality of each node. The above is an extension of my article series on the centrality measures. Keep networking!!! ReferencesYou can read more about the same at https://en.wikipedia.org/wiki/Centrality#Degree_centralityhttp://networkx.readthedocs.io/en/networkx-1.10/index.html This article is contributed by Jayant Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ManasChhabra2 Graph Python Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Detect Cycle in a Directed Graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Ford-Fulkerson Algorithm for Maximum Flow Problem Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 26305, "s": 26277, "text": "\n31 Oct, 2019" }, { "code": null, "e": 26818, "s": 26305, "text": "DegreeIn graph theory, the degree (or valency) of a vertex of a graph is the number of edges incident to the vertex, with loops counted twice.[1] The degree of a v...
Manipulate R Data Frames Using SQL - GeeksforGeeks
04 Aug, 2021 Manipulating data frames in R Programming using SQL can be easily done using the sqldf package. This package in R provides a mechanism that allows data frame manipulation with SQL and also helps to connect with a limited number of databases. The sqldf package in R is basically used for executing the SQL commands or statements on data frames. One can simply specify the SQL statement using data frame names instead of table names in R, and then the following things happen: A database with proper schema or table layout is created The data frames are loaded into the created database automatically The specific SQL statement or command is executed The result is retrieved back into R, and Automatically the database gets deleted. This makes the existence of the database quite transparent. This method can lead to faster R calculation. The result is obtained using some heuristics in order to determine the class which is to be assigned to each column of the resultant data frame. A handful of SQL operations can be performed in R using the sqldf package. Let’s use two csv files from the Highway data. crashes.csv which contains Year, Road, N_Crashes, and Volume. roads.csv which contains Road, District, and Length. In order to work with the sqldf package, first install it as follows: install.packages("sqldf") After proper installation, include the package in R script as follows: library(sqldf) Now load the data in the script. In order to do so, change the present directory to the directory which contains the csv files crashes.csv and roads.csv using the setwd() function. Example: r # Importing required librarylibrary(sqldf) # Changing the directorysetwd("C:\\Users\\SHAONI\\Documents\\ R\\win-library") # Reading the csv filescrashes <- read.csv("crashes.csv")roads <- read.csv("roads.csv") # Displaying the data in crashes.csvhead(crashes)tail(crashes) # Displaying the data in roads.csvprint(roads) Output: Year Road N_Crashes Volume 1 1991 Interstate 65 25 40000 2 1992 Interstate 65 37 41000 3 1993 Interstate 65 45 45000 4 1994 Interstate 65 46 45600 5 1995 Interstate 65 46 49000 6 1996 Interstate 65 59 51000 Year Road N_Crashes Volume 105 2007 Interstate 275 32 21900 106 2008 Interstate 275 21 21850 107 2009 Interstate 275 25 22100 108 2010 Interstate 275 24 21500 109 2011 Interstate 275 23 20300 110 2012 Interstate 275 22 21200 Road District Length 1 Interstate 65 Greenfield 262 2 Interstate 70 Vincennes 156 3 US-36 Crawfordsville 139 4 US-40 Greenfield 150 5 US-52 Crawfordsville 172 Now perform any SQL operation on these data using the sqldf() function of the sqldf package. The most common SQL operation is the join operation. One can perform left join and inner join using sqldf(). Currently, sqldf() does not support the full outer join and right join operations. Along with the sqldf package we need to include the tcltk package.Example 1: Performing left join operation r # Perform Left Join # Importing required librarylibrary(sqldf)library(tcltk) # Setting the directorysetwd("C:\\Users\\SHAONI\\Documents\\ R\\win-library") # Reading the csv filescrashes <- read.csv("crashes.csv")roads <- read.csv("roads.csv") # Performing left joinjoin_string <- "select crashes.*, roads.District, roads.Length from crashes left join roads on crashes.Road = roads.Road" # Resultant data framecrashes_join_roads <- sqldf(join_string, stringsAsFactors = FALSE)head(crashes_join_roads)tail(crashes_join_roads) Output: Year Road N_Crashes Volume District Length 1 1991 Interstate 65 25 40000 Greenfield 262 2 1992 Interstate 65 37 41000 Greenfield 262 3 1993 Interstate 65 45 45000 Greenfield 262 4 1994 Interstate 65 46 45600 Greenfield 262 5 1995 Interstate 65 46 49000 Greenfield 262 6 1996 Interstate 65 59 51000 Greenfield 262 Year Road N_Crashes Volume District Length 105 2007 Interstate 275 32 21900 <NA> NA 106 2008 Interstate 275 21 21850 <NA> NA 107 2009 Interstate 275 25 22100 <NA> NA 108 2010 Interstate 275 24 21500 <NA> NA 109 2011 Interstate 275 23 20300 <NA> NA 110 2012 Interstate 275 22 21200 <NA> NA Explanation: The crashes_join_roads is a new data frame created by the sqldf statement which stores the result of the join operation. The sqldf() function or operation requires at least a string character along with the SQL operation. The stringsAsFactors parameter is used to assign character class to the categorical data instead of factor class.Example 2: Performing inner join r # Perform Inner Join # Importing required packagelibrary(sqldf)library(tcltk) # Selecting the proper directorysetwd("C:\\Users\\SHAONI\\Documents\\ R\\win-library")# Reading the csv filescrashes <- read.csv("crashes.csv")roads <- read.csv("roads.csv") # Performing the inner joinjoin_string2 <- "select crashes.*, roads.District, roads.Length from crashes inner join roads on crashes.Road = roads.Road" # The new data framecrashes_join_roads2 <- sqldf(join_string2, stringsAsFactors = FALSE)head(crashes_join_roads2)tail(crashes_join_roads2) Output: Year Road N_Crashes Volume District Length 1 1991 Interstate 65 25 40000 Greenfield 262 2 1992 Interstate 65 37 41000 Greenfield 262 3 1993 Interstate 65 45 45000 Greenfield 262 4 1994 Interstate 65 46 45600 Greenfield 262 5 1995 Interstate 65 46 49000 Greenfield 262 6 1996 Interstate 65 59 51000 Greenfield 262 Year Road N_Crashes Volume District Length 83 2007 US-36 49 24000 Crawfordsville 139 84 2008 US-36 52 24500 Crawfordsville 139 85 2009 US-36 55 24700 Crawfordsville 139 86 2010 US-36 35 23000 Crawfordsville 139 87 2011 US-36 33 21000 Crawfordsville 139 88 2012 US-36 31 20500 Crawfordsville 139 Here only the matching rows are kept in the resultant data frame.Now let’s see how the merge() function works. In R, the merge operation is capable of performing left join, right join, inner join, and full outer join, unlike the sqldf() function. Also, one can easily perform the equivalent operation like sqldf() using the merge() operation.Example 3: r # Perform Merge operation # Import required librarylibrary(sqldf)library(tcltk) setwd("C:\\Users\\SHAONI\\Documents\\ R\\win-library") # Reading the two csv filescrashes <- read.csv("crashes.csv")roads <- read.csv("roads.csv")# Merge the two data framescrashes_merge_roads2 <- merge(crashes, roads, by = c("Road"), all.x = TRUE)head(crashes_merge_roads2)tail(crashes_merge_roads2) Output: Road Year N_Crashes Volume District Length 1 Interstate 275 1994 21 21200 <NA> NA 2 Interstate 275 1995 28 23200 <NA> NA 3 Interstate 275 1996 22 20000 <NA> NA 4 Interstate 275 1997 27 18000 <NA> NA 5 Interstate 275 1998 21 19500 <NA> NA 6 Interstate 275 1999 22 21000 <NA> NA Road Year N_Crashes Volume District Length 105 US-40 2003 94 55200 Greenfield 150 106 US-40 2004 25 55300 Greenfield 150 107 US-40 2009 67 65000 Greenfield 150 108 US-40 2010 102 67000 Greenfield 150 109 US-40 2011 87 67500 Greenfield 150 110 US-40 2012 32 67500 Greenfield 150 We will see that the rows in the resultant data frames are rearranged when we are using the merge() function. R can perform the exact operations as SQL. Hence to use a SQL statement where to include any condition use the where clause.Example: Let’s see how to perform inner join using the combination of merge and subset operation by including the where clause in the query. r # Using where clause # Importing required librarylibrary(sqldf)library(plyr)library(tcltk) setwd("C:\\Users\\SHAONI\\Documents\\ R\\win-library")crashes <- read.csv("crashes.csv")roads <- read.csv("roads.csv") # Using the where clausejoin_string2 <- "select crashes.*, roads.District, roads.Length from crashes inner join roads on crashes.Road = roads.Road where crashes.Road = 'US-40'" crashes_join_roads4 <- sqldf(join_string2, stringsAsFactors = FALSE)head(crashes_join_roads4)tail(crashes_join_roads4) Output: Year Road N_Crashes Volume District Length 1 1991 US-40 46 21000 Greenfield 150 2 1992 US-40 101 21500 Greenfield 150 3 1993 US-40 76 23000 Greenfield 150 4 1994 US-40 72 21000 Greenfield 150 5 1995 US-40 75 24000 Greenfield 150 6 1996 US-40 136 23500 Greenfield 150 Year Road N_Crashes Volume District Length 17 2007 US-40 45 59500 Greenfield 150 18 2008 US-40 23 61000 Greenfield 150 19 2009 US-40 67 65000 Greenfield 150 20 2010 US-40 102 67000 Greenfield 150 21 2011 US-40 87 67500 Greenfield 150 22 2012 US-40 32 67500 Greenfield 150 In the sqldf package, the aggregate operations can be performed using the group by clause.Example: r # Perform aggregate operations # Import required librarylibrary(sqldf)library(tcltk) setwd("C:\\Users\\SHAONI\\Documents\\ R\\win-library")crashes <- read.csv("crashes.csv")roads <- read.csv("roads.csv") # Group by clausegroup_string <- "select crashes.Road, avg(crashes.N_Crashes) as Mean_Crashes from crashes left join roads on crashes.Road = roads.Road group by 1"sqldf(group_string) Output: Road Mean_Crashes 1 Interstate 275 24.95455 2 Interstate 65 107.81818 3 Interstate 70 65.18182 4 US-36 48.00000 5 US-40 68.68182 The sqldf() function can be used for performing certain kinds of data manipulations. To overcome these limitations, use the plyr package in the R Script. Hadley Wickham’s plyr package can be used to perform advanced calculations and data manipulations. Let’s see how it works.Example: r # Importing required librarylibrary(sqldf)library(plyr)library(tcltk) setwd("C:\\Users\\SHAONI\\Documents\\ R\\win-library")crashes <- read.csv("crashes.csv")roads <- read.csv("roads.csv") ddply(crashes_merge_roads,c("Road"),function(X)data.frame( Mean_Crashes = mean(X$N_Crashes), Q1_Crashes = quantile(X$N_Crashes, 0.25), Q3_Crashes = quantile(X$N_Crashes, 0.75), Median_Crashes = quantile(X$N_Crashes, 0.50))) Output: Road Mean_Crashes Q1_Crashes Q3_Crashes Median_Crashes 1 Interstate 65 107.81818 63.25 140.25 108.5 2 Interstate 70 65.18182 52.00 75.50 66.5 3 US-36 48.00000 42.00 57.25 47.0 4 US-40 68.68182 45.25 90.75 70.0 abhishek0719kadiyan R-DataFrame R Language SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Group by function in R using Dplyr SQL | DDL, DQL, DML, DCL and TCL Commands SQL | WITH clause SQL | Join (Inner, Left, Right and Full Joins) How to find Nth highest salary from a table SQL | ALTER (RENAME)
[ { "code": null, "e": 26299, "s": 26271, "text": "\n04 Aug, 2021" }, { "code": null, "e": 26776, "s": 26299, "text": "Manipulating data frames in R Programming using SQL can be easily done using the sqldf package. This package in R provides a mechanism that allows data frame manip...
HTML | <ol> type Attribute - GeeksforGeeks
27 Mar, 2020 The HTML <ol> type Attribute defines which type(1, A, a, I and i) of order you want in your list numeric, alphabetic or roman numbers. Syntax: <ol type="1 | a | A | i | I"> Attribute Values 1: This is the default value. It defines the list items in decimal number.(1, 2, 3, 4 .). a: It defines the list items in alphabetically ordered lowercase letters .(a, b, c, d ...) A: It defines the list items in alphabetically ordered uppercase letters.(A, B, C, D ..) i: It defines the list items in lowercase roman number order.(i, ii, iii, iv, v, vi ...) I: It defines the list items in uppercase roman number order.(I, II, III, IV, V, VI ..) Example: <!DOCTYPE html> <html> <head> <title>HTML ol type attribute</title> </head> <body> <h1 style="color:green;">GeeksforGeeks</h1> <h3>HTML ol Type attribute</h3> <p>Type attribute</p> <p>start attribute</p> <ol type="1"> <li>HTML</li> <li>CSS</li> <li>JS</li> </ol> </body> </html> Output: Supported Browsers: The browser supported by ol type attribute listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) How to Insert Form Data into Database using PHP ? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26001, "s": 25973, "text": "\n27 Mar, 2020" }, { "code": null, "e": 26136, "s": 26001, "text": "The HTML <ol> type Attribute defines which type(1, A, a, I and i) of order you want in your list numeric, alphabetic or roman numbers." }, { "code": null, ...
How message authentication code works? - GeeksforGeeks
09 Aug, 2019 Prerequisite – Message authentication codesApart from intruders, the transfer of message between two people also faces other external problems like noise, which may alter the original message constructed by the sender. To ensure that the message is not altered there’s this cool method MAC. MAC stands for Message Authentication Code. Here in MAC, sender and receiver share same key where sender generates a fixed size output called Cryptographic checksum or Message Authentication code and appends it to the original message. On receiver’s side, receiver also generates the code and compares it with what he/she received thus ensuring the originality of the message. These are components: Message Key MAC algorithm MAC value There are different types of models Of Message Authentication Code (MAC) as following below: MAC without encryption –This model can provide authentication but not confidentiality as anyone can see the message.Internal Error Code –In this model of MAC, sender encrypts the content before sending it through network for confidentiality. Thus this model provides confidentiality as well as authentication.M' = MAC(M, k)External Error Code –For cases when there is an alteration in message, we decrypt it for waste, to overcome that problem, we opt for external error code. Here we first apply MAC on the encrypted message ‘c’ and compare it with received MAC value on the receiver’s side and then decrypt ‘c’ if they both are same, else we simply discard the content received. Thus it saves time.c = E(M, k') M' = MAC(c, k) MAC without encryption –This model can provide authentication but not confidentiality as anyone can see the message. Internal Error Code –In this model of MAC, sender encrypts the content before sending it through network for confidentiality. Thus this model provides confidentiality as well as authentication.M' = MAC(M, k) M' = MAC(M, k) External Error Code –For cases when there is an alteration in message, we decrypt it for waste, to overcome that problem, we opt for external error code. Here we first apply MAC on the encrypted message ‘c’ and compare it with received MAC value on the receiver’s side and then decrypt ‘c’ if they both are same, else we simply discard the content received. Thus it saves time.c = E(M, k') M' = MAC(c, k) c = E(M, k') M' = MAC(c, k) Problems in MAC –If we do reverse engineering we can reach plain text or even the key. Here we have mapped input to output, to overcome this we move on to hash functions which are “One way”. Note – symbol “E” denotes symmetric key encryption. Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 Socket Programming in Python Caesar Cipher in Cryptography UDP Server-Client implementation in C Socket Programming in Java Advanced Encryption Standard (AES) Intrusion Detection System (IDS) Secure Socket Layer (SSL) Cryptography and its Types Wireless Sensor Network (WSN)
[ { "code": null, "e": 37839, "s": 37811, "text": "\n09 Aug, 2019" }, { "code": null, "e": 38130, "s": 37839, "text": "Prerequisite – Message authentication codesApart from intruders, the transfer of message between two people also faces other external problems like noise, which ma...
How to use jQuery with Node.js ? - GeeksforGeeks
15 Mar, 2021 jQuery is a JavaScript library, which provides us with the same functionality as vanilla JavaScript but in fewer lines of code. The need for jQuery is reduced as doing things became much simpler in vanilla JavaScript with updates. Although its popularity is decreasing, still around 76% of the projects use jQuery. Our Aim is to use jQuery with Node.js: We can use jQuery in Node.js using the jquery module. Note: Use the ‘jquery’ module not the ‘jQuery’ module as the latter is deprecated. Getting jQuery to work in Node.js: Step 1 : Making the package.json file. Use the following command to create the package.json file, which keeps track of the modules and dependencies. npm init -yThe ‘-y’ tag makes yes the default answer for all the questions asked while creating the package.json file. Step 1 : Making the package.json file. Use the following command to create the package.json file, which keeps track of the modules and dependencies. npm init -y The ‘-y’ tag makes yes the default answer for all the questions asked while creating the package.json file. Step 2: Installing the jquery module. Use the following command to install the jquery module.npm install jquery Step 2: Installing the jquery module. Use the following command to install the jquery module. npm install jquery Step 3 :Installing the jsdom module. Since jQuery is a frontend JavaScript Library, it needs to have a window with a document to work in the backend. ‘jsdom’ is a library that is used to parse and interact with the HTML. It is not exactly a web browser but mimics one. Use the following command to install the jsdom module.npm install jsdom Step 3 :Installing the jsdom module. Since jQuery is a frontend JavaScript Library, it needs to have a window with a document to work in the backend. ‘jsdom’ is a library that is used to parse and interact with the HTML. It is not exactly a web browser but mimics one. Use the following command to install the jsdom module. npm install jsdom Step 4 :Importing the jsdom module. Use the require method to import the jsdom module.const jsdom = require('jsdom') Step 4 :Importing the jsdom module. Use the require method to import the jsdom module. const jsdom = require('jsdom') Step 5: Creating a new window. We create a window with a document by creating a JSDOM object, with the HTML code as the parameter. Following code is used to create a window with a document :- const dom = new jsdom.JSDOM("") Step 5: Creating a new window. We create a window with a document by creating a JSDOM object, with the HTML code as the parameter. Following code is used to create a window with a document :- const dom = new jsdom.JSDOM("") Step 6: Importing jQuery and providing it with a window. Once the window with a document is created, we can use the jquery module by providing it with the window we created. The following code is used to import the jquery module.const jquery = require('jquery')(dom.window) Step 6: Importing jQuery and providing it with a window. Once the window with a document is created, we can use the jquery module by providing it with the window we created. The following code is used to import the jquery module. const jquery = require('jquery')(dom.window) That’s it we have successfully loaded jquery into our Node.js application. Example: To get a better understanding of how it works, please go through the below example :- Javascript // Importing the jsdom moduleconst jsdom = require("jsdom"); // Creating a window with a documentconst dom = new jsdom.JSDOM(`<!DOCTYPE html><body><h1 class="heading"> GeeksforGeeks</h1></body>`); // Importing the jquery and providing it// with the windowconst jquery = require("jquery")(dom.window); // Appending a paragraph tag to the bodyjquery("body").append("<p>Is a cool Website</p>"); // Getting the content of the bodyconst content = dom.window.document.querySelector("body"); // Printing the content of the heading and paragraphconsole.log(content.textContent); Output: GeeksforGeeks Is a cool website jQuery-Questions NodeJS-Questions Picked Technical Scripter 2020 JQuery Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery Scroll to the top of the page using JavaScript/jQuery jQuery | children() with Examples How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method Node.js fs.readFile() Method
[ { "code": null, "e": 26474, "s": 26446, "text": "\n15 Mar, 2021" }, { "code": null, "e": 26789, "s": 26474, "text": "jQuery is a JavaScript library, which provides us with the same functionality as vanilla JavaScript but in fewer lines of code. The need for jQuery is reduced as d...
Java Program to Extract a Image From a PDF - GeeksforGeeks
17 Nov, 2020 Program to extract an image from a PDF using Java. The external jar file is required to import in the program. Below is the implementation for the same. Algorithm: Extracting image using the APACHE PDF Box module. Load the existing PDF document using file io. Creating an object of PDFRenderer class. Rendering an image from the PDF document using the BufferedImage class. Writing the extracted image to the new file. Close the document. Note: External files are required to download for performing the operation. For more documentation of the module used to refer to this. Implementation: Java // Extracting Images from a PDF using javaimport java.io.*;import java.awt.image.BufferedImage;import javax.imageio.ImageIO;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.rendering.PDFRenderer; class GFG { public static void main(String[] args) throws Exception { // Existing PDF Document // to be Loaded using file io File newFile = new File("C:/Documents/GeeksforGeeks.pdf"); PDDocument pdfDocument = PDDocument.load(newFile); // PDFRenderer class to be Instantiated // i.e. creating it's object PDFRenderer pdfRenderer = new PDFRenderer(pdfDocument); // Rendering an image // from the PDF document // using BufferedImage class BufferedImage img = pdfRenderer.renderImage(0); // Writing the extracted // image to a new file ImageIO.write( img, "JPEG", new File("C:/Documents/GeeksforGeeks.png")); System.out.println( "Image has been extracted successfully"); // Closing the PDF document pdfDocument.close(); }} PDF before execution: Existing PDF Document which containing the image which is to be extracted Image after extraction: Extracted Image from the PDF document Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n17 Nov, 2020" }, { "code": null, "e": 25378, "s": 25225, "text": "Program to extract an image from a PDF using Java. The external jar file is required to import in the program. Below is the implementation for the same." }, { ...
Stack remove(int) method in Java with Example - GeeksforGeeks
24 Dec, 2018 The Java.util.Stack.remove(int index) method is used to remove an element from a Stack from a specific position or index. Syntax: Stack.remove(int index) Parameters: This method accepts a mandatory parameter index is of integer data type and specifies the position of the element to be removed from the Stack. Return Value: This method returns the element that has just been removed from the Stack. Below program illustrate the Java.util.Stack.remove(int index) method: Example 1: // Java code to illustrate remove() when position of// element is passed as parameter import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements in the Stack stack.add("Geeks"); stack.add("for"); stack.add("Geeks"); stack.add("10"); stack.add("20"); // Output the Stack System.out.println("Stack: " + stack); // Remove the element using remove() String rem_ele = stack.remove(4); // Print the removed element System.out.println("Removed element: " + rem_ele); // Print the final Stack System.out.println("Final Stack: " + stack); }} Stack: [Geeks, for, Geeks, 10, 20] Removed element: 20 Final Stack: [Geeks, for, Geeks, 10] Example 2: // Java code to illustrate remove() when position of// element is passed as parameter import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method to add elements in the Stack stack.add(10); stack.add(20); stack.add(30); stack.add(40); stack.add(50); // Output the Stack System.out.println("Stack: " + stack); // Remove the element using remove() int rem_ele = stack.remove(0); // Print the removed element System.out.println("Removed element: " + rem_ele); // Print the final Stack System.out.println("Final Stack: " + stack); }} Stack: [10, 20, 30, 40, 50] Removed element: 10 Final Stack: [20, 30, 40, 50] Java - util package Java-Collections Java-Functions Java-Stack Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples Reverse a string in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java
[ { "code": null, "e": 25719, "s": 25691, "text": "\n24 Dec, 2018" }, { "code": null, "e": 25841, "s": 25719, "text": "The Java.util.Stack.remove(int index) method is used to remove an element from a Stack from a specific position or index." }, { "code": null, "e": 2584...
How to create fade-in effect on page load using CSS ? - GeeksforGeeks
30 Jul, 2021 Use animation and transition property to create a fade-in effect on page load using CSS. Method 1: Using CSS animation property: A CSS animation is defined with 2 keyframes. One with the opacity set to 0, the other with the opacity set to 1. When the animation type is set to ease, the animation smoothly fades in the page. This property is applied to the body tag. Whenever the page loads, this animation would play and the page will appear to fade in. The time of the fade in can be set in the animation property. Syntax: body { animation: fadeInAnimation ease 3s animation-iteration-count: 1; animation-fill-mode: forwards;} @keyframes fadeInAnimation { 0% { opacity: 0; } 100% { opacity: 1; }} Example: <!DOCTYPE html><html> <head> <title> How to create fade-in effect on page load using CSS </title> <style> body { animation: fadeInAnimation ease 3s; animation-iteration-count: 1; animation-fill-mode: forwards; } @keyframes fadeInAnimation { 0% { opacity: 0; } 100% { opacity: 1; } } </style></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to create fade-in effect on page load using CSS </b> <p> This page will fade in after loading </p></body> </html> Output: Method 2: Using the transition property and setting the opacity to 1 when the body is loaded: In this method, the body can be set to the opacity 0 initially and the transition property is used to animate this property whenever it is changed. When the page is loaded, the opacity is set to 1 using the onload event. Due to the transition property, changing the opacity now will appear to fade in the page. The time of the fade in can be set in the transition property. Syntax: body { opacity: 0; transition: opacity 5s;} Example: <!DOCTYPE html><html> <head> <title> How to create fade-in effect on page load using CSS </title> <style> body { opacity: 0; transition: opacity 3s; } </style></head> <body onload="document.body.style.opacity='1'"> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to create fade-in effect on page load using CSS </b> <p> This page will fade in after loading </p></body> </html> Output: CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. CSS-Misc Picked CSS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? Design a web page using HTML and CSS Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25730, "s": 25702, "text": "\n30 Jul, 2021" }, { "code": null, "e": 25819, "s": 25730, "text": "Use animation and transition property to create a fade-in effect on page load using CSS." }, { "code": null, "e": 26246, "s": 25819, "text": "M...
How to set the Margin between the TextBox controls in C#? - GeeksforGeeks
29 Nov, 2019 In Windows forms, Textbox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the space between two or more TextBox controls with the help of Margin Property. In Windows form, you can set this property in two different ways: 1. Design-Time: It is the simplest way to set the Margin property of the TextBox as shown in the following steps: Step 1: Create a windows form.Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the TextBox control from the ToolBox and drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the TextBox control to set the Margin property of the TextBox.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Margin property of the TextBox programmatically with the help of given syntax: public System.Windows.Forms.Padding Margin { get; set; } Here, Padding is used to represent the space between the TextBox controls. Following steps are used to set the Margin property of the TextBox: Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox TextBox Mytextbox = new TextBox(); // Creating textbox TextBox Mytextbox = new TextBox(); Step 2 : After creating TextBox, set the Margin property of the TextBox provided by the TextBox class.// Set Margin property Mytextbox1.Margin = new Padding(5, 5, 5, 5); // Set Margin property Mytextbox1.Margin = new Padding(5, 5, 5, 5); Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form this.Controls.Add(Mytextbox1); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel1 = new Label(); Mylablel1.Location = new Point(96, 54); Mylablel1.Text = "Enter Name"; Mylablel1.AutoSize = true; Mylablel1.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel1); // Creating and setting the properties of TextBox1 TextBox Mytextbox1 = new TextBox(); Mytextbox1.Location = new Point(187, 51); Mytextbox1.BackColor = Color.LightGray; Mytextbox1.AutoSize = true; Mytextbox1.Name = "text_box1"; Mytextbox1.Margin = new Padding(5, 5, 5, 5); // Add this textbox to form this.Controls.Add(Mytextbox1); // Creating and setting the properties of Lable1 Label Mylablel2 = new Label(); Mylablel2.Location = new Point(96, 102); Mylablel2.Text = "Enter Area"; Mylablel2.AutoSize = true; Mylablel2.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel2); // Creating and setting the properties of TextBox2 TextBox Mytextbox2 = new TextBox(); Mytextbox2.Location = new Point(187, 99); Mytextbox2.BackColor = Color.LightGray; Mytextbox2.AutoSize = true; Mytextbox2.Name = "text_box2"; // Add this textbox to form this.Controls.Add(Mytextbox2); }}}Output: // Add this textbox to form this.Controls.Add(Mytextbox1); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel1 = new Label(); Mylablel1.Location = new Point(96, 54); Mylablel1.Text = "Enter Name"; Mylablel1.AutoSize = true; Mylablel1.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel1); // Creating and setting the properties of TextBox1 TextBox Mytextbox1 = new TextBox(); Mytextbox1.Location = new Point(187, 51); Mytextbox1.BackColor = Color.LightGray; Mytextbox1.AutoSize = true; Mytextbox1.Name = "text_box1"; Mytextbox1.Margin = new Padding(5, 5, 5, 5); // Add this textbox to form this.Controls.Add(Mytextbox1); // Creating and setting the properties of Lable1 Label Mylablel2 = new Label(); Mylablel2.Location = new Point(96, 102); Mylablel2.Text = "Enter Area"; Mylablel2.AutoSize = true; Mylablel2.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel2); // Creating and setting the properties of TextBox2 TextBox Mytextbox2 = new TextBox(); Mytextbox2.Location = new Point(187, 99); Mytextbox2.BackColor = Color.LightGray; Mytextbox2.AutoSize = true; Mytextbox2.Name = "text_box2"; // Add this textbox to form this.Controls.Add(Mytextbox2); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Lambda Expressions in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n29 Nov, 2019" }, { "code": null, "e": 25899, "s": 25547, "text": "In Windows forms, Textbox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple ...
Java program to delete duplicate lines in text file - GeeksforGeeks
30 May, 2018 Prerequisite : PrintWriter , BufferedReader Given a file input.txt . Our Task is to remove duplicate lines from it and save the output in file say output.txt Naive Algorithm : 1. Create PrintWriter object for output.txt 2. Open BufferedReader for input.txt 3. Run a loop for each line of input.txt 3.1 flag = false 3.2 Open BufferedReader for output.txt 3.3 Run a loop for each line of output.txt -> If line of output.txt is equal to current line of input.txt -> flag = true -> break loop 4. Check flag, if false -> write current line of input.txt to output.txt -> Flush PrintWriter stream 5. Close resources. To successfully run the below program input.txt must exits in same folder OR provide full path for it. // Java program to remove// duplicates from input.txt and // save output to output.txt import java.io.*; public class FileOperation{ public static void main(String[] args) throws IOException { // PrintWriter object for output.txt PrintWriter pw = new PrintWriter("output.txt"); // BufferedReader object for input.txt BufferedReader br1 = new BufferedReader(new FileReader("input.txt")); String line1 = br1.readLine(); // loop for each line of input.txt while(line1 != null) { boolean flag = false; // BufferedReader object for output.txt BufferedReader br2 = new BufferedReader(new FileReader("output.txt")); String line2 = br2.readLine(); // loop for each line of output.txt while(line2 != null) { if(line1.equals(line2)) { flag = true; break; } line2 = br2.readLine(); } // if flag = false // write line of input.txt to output.txt if(!flag){ pw.println(line1); // flushing is important here pw.flush(); } line1 = br1.readLine(); } // closing resources br1.close(); pw.close(); System.out.println("File operation performed successfully"); }} Output: File operation performed successfully Note : If output.txt exist in cwd(current working directory) then it will be overwritten by above program otherwise new file will be created. A better solution is to use HashSet to store each line of input.txt. As set ignores duplicate values, so while storing a line, check if it already present in hashset. Write it to output.txt only if not present in hashset. To successfully run the below program input.txt must exits in same folder OR provide full path for them. // Efficient Java program to remove// duplicates from input.txt and // save output to output.txt import java.io.*;import java.util.HashSet; public class FileOperation{ public static void main(String[] args) throws IOException { // PrintWriter object for output.txt PrintWriter pw = new PrintWriter("output.txt"); // BufferedReader object for input.txt BufferedReader br = new BufferedReader(new FileReader("input.txt")); String line = br.readLine(); // set store unique values HashSet<String> hs = new HashSet<String>(); // loop for each line of input.txt while(line != null) { // write only if not // present in hashset if(hs.add(line)) pw.println(line); line = br.readLine(); } pw.flush(); // closing resources br.close(); pw.close(); System.out.println("File operation performed successfully"); }} Output: File operation performed successfully Note : If output.txt exist in cwd(current working directory) then it will be overwritten by above program otherwise new file will be created. This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. java-file-handling Java-I/O Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Multithreading in Java Collections in Java
[ { "code": null, "e": 26129, "s": 26101, "text": "\n30 May, 2018" }, { "code": null, "e": 26173, "s": 26129, "text": "Prerequisite : PrintWriter , BufferedReader" }, { "code": null, "e": 26287, "s": 26173, "text": "Given a file input.txt . Our Task is to remove...
Program to validate an IP address - GeeksforGeeks
12 Apr, 2022 Write a program to Validate an IPv4 Address. According to Wikipedia, IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 172.16.254.1 Following are steps to check whether a given string is a valid IPv4 address or not: step 1) Parse string with “.” as delimiter using “strtok()” function. e.g.ptr = strtok(str, DELIM); step 2) A) If ptr contains any character which is not digit then return 0 B) Convert “ptr” to decimal number say ‘NUM’ C) If NUM is not in range of 0-255 return 0 D) If NUM is in range of 0-255 and ptr is non-NULL increment “dot_counter” by 1 E) if ptr is NULL goto step 3 else goto step 1step 3) if dot_counter != 3 return 0 else return 1 C++ // Program to check if a given// string is valid IPv4 address or not#include <bits/stdc++.h>using namespace std;#define DELIM "." /* function to check whether the string passed is valid or not */bool valid_part(char* s){ int n = strlen(s); // if length of passed string is // more than 3 then it is not valid if (n > 3) return false; // check if the string only contains digits // if not then return false for (int i = 0; i < n; i++) if ((s[i] >= '0' && s[i] <= '9') == false) return false; string str(s); // if the string is "00" or "001" or // "05" etc then it is not valid if (str.find('0') == 0 && n > 1) return false; stringstream geek(str); int x; geek >> x; // the string is valid if the number // generated is between 0 to 255 return (x >= 0 && x <= 255);} /* return 1 if IP string isvalid, else return 0 */int is_valid_ip(char* ip_str){ // if empty string then return false if (ip_str == NULL) return 0; int i, num, dots = 0; int len = strlen(ip_str); int count = 0; // the number dots in the original // string should be 3 // for it to be valid for (int i = 0; i < len; i++) if (ip_str[i] == '.') count++; if (count != 3) return false; // See following link for strtok() char *ptr = strtok(ip_str, DELIM); if (ptr == NULL) return 0; while (ptr) { /* after parsing string, it must be valid */ if (valid_part(ptr)) { /* parse remaining string */ ptr = strtok(NULL, "."); if (ptr != NULL) ++dots; } else return 0; } /* valid IP string must contain 3 dots */ // this is for the cases such as 1...1 where // originally the no. of dots is three but // after iteration of the string we find // it is not valid if (dots != 3) return 0; return 1;} // Driver codeint main(){ char ip1[] = "128.0.0.1"; char ip2[] = "125.16.100.1"; char ip3[] = "125.512.100.1"; char ip4[] = "125.512.100.abc"; is_valid_ip(ip1) ? cout<<"Valid\n" : cout<<"Not valid\n"; is_valid_ip(ip2) ? cout<<"Valid\n" : cout<<"Not valid\n"; is_valid_ip(ip3) ? cout<<"Valid\n" : cout<<"Not valid\n"; is_valid_ip(ip4) ? cout<<"Valid\n" : cout<<"Not valid\n"; return 0;} Valid Valid Not valid Not valid This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Python Solution :- Approach:- We will check all the cases where ip address may be invalid 1. First we will split the given input using split() function then check if it has a length of 4 or not .If length is not equal to 4 then we will directly return 0. 2. in second step we will check if any split element contains any leading zero or not .if it is then we will return zero. 3.If any of the split does not contain any number then it is not a valid ip address .so we will return 0 4. Then we will check if all the splits are in the range of 0-255 or not .If not we will return 0. 5.Finally if none of the above condition is true we can finally say that it is a valid ip address.And we will return True. Here is the code for above approach . Python3 def in_range(n): #check if every split is in range 0-255 if n >= 0 and n<=255: return True return False def has_leading_zero(n): # check if eery split has leading zero or not. if len(n)>1: if n[0] == "0": return True return Falsedef isValid(s): s = s.split(".") if len(s) != 4: #if number of splitting element is not 4 it is not a valid ip addrress return 0 for n in s: if has_leading_zero(n): return 0 if len(n) == 0: return 0 try: #if int(n) is not an integer it raises an error n = int(n) if not in_range(n): return 0 except: return 0 return 1 if __name__=="__main__": ip1 = "222.111.111.111" ip2 = "5555..555" ip3 = "0000.0000.0000.0000" ip4 = "1.1.1.1" print(isValid(ip1)) print(isValid(ip2)) print(isValid(ip3)) print(isValid(ip4)) # this code is contributed by Vivek Maddeshiya. 1 0 0 1 meeseeks_nits iamdhavalparmar vivekmaddheshiya205 Microsoft Qualcomm Zoho C Language C++ Strings Zoho Microsoft Qualcomm Strings CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Converting Strings to Numbers in C/C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 26477, "s": 26449, "text": "\n12 Apr, 2022" }, { "code": null, "e": 26720, "s": 26477, "text": "Write a program to Validate an IPv4 Address. According to Wikipedia, IPv4 addresses are canonically represented in dot-decimal notation, which consists of four dec...
Relational Database from CSV Files in C - GeeksforGeeks
24 Feb, 2022 In C programming, using arrays and string for data storage at run time which is volatile and gets memory in RAM. But to store data permanently in a hard disk which can be manipulated furthermore. So, the idea is to use a CSV file for data storage and manipulation. Not only CSV but other files like data, txt, and bin can also be used for data manipulation. But CSV file as the name suggests (Comma Separated Values) stores data in a table format which saves a lot of time in making perfect structure. In Relational Databases data gets stored in a table format so by using CSV File, the database can be created. Below is an example of a CSV File: For concepts of File Handling, refer to the Basic File Handling in C article. Create a buffer of character array (can be referred to as string) which takes all the data present in the file and by using File Pointer and fgets() data can be extracted. Use two variables row and column which will maintain the unique identification of every entry. As the string contains comma ‘, ‘ for separating values, so the idea is to use strtok() function for splitting values. This function splits a string using a delimiter here we are using ‘, ‘. Data Extraction deals with Opening an existing CSV file and extracting and printing the whole data on the console. Approach: Open CSV File using File Pointer.Extract the whole file data into a char buffer array.Now initialize row and column variables with value 0.Print data separated by a comma and increase the column variable.When reached to the end of a row entry initialize column variable to 0 and increase row variable.Repeat steps 4 and 5, till the pointer reaches the end of the file.Close the file. Open CSV File using File Pointer. Extract the whole file data into a char buffer array. Now initialize row and column variables with value 0. Print data separated by a comma and increase the column variable. When reached to the end of a row entry initialize column variable to 0 and increase row variable. Repeat steps 4 and 5, till the pointer reaches the end of the file. Close the file. Below is the program for the same: C // C program for the above approach#include <conio.h>#include <stdio.h>#include <string.h> // Driver Codeint main(){ // Substitute the full file path // for the string file_path FILE* fp = fopen("file_path", "r"); if (!fp) printf("Can't open file\n"); else { // Here we have taken size of // array 1024 you can modify it char buffer[1024]; int row = 0; int column = 0; while (fgets(buffer, 1024, fp)) { column = 0; row++; // To avoid printing of column // names in file can be changed // according to need if (row == 1) continue; // Splitting the data char* value = strtok(buffer, ", "); while (value) { // Column 1 if (column == 0) { printf("Name :"); } // Column 2 if (column == 1) { printf("\tAccount No. :"); } // Column 3 if (column == 2) { printf("\tAmount :"); } printf("%s", value); value = strtok(NULL, ", "); column++; } printf("\n"); } // Close the file fclose(fp); } return 0;} Data Addition deals with opening an existing CSV file, taking user inputs for the data to be added to the file, and then adding this data to the CSV file. Approach: Open CSV File using File Pointer in append mode which will place a pointer to the end of the file.Take Input from the user in temporary variables.Use fprintf() and separate variables according to their order and comma.Close the file. Open CSV File using File Pointer in append mode which will place a pointer to the end of the file. Take Input from the user in temporary variables. Use fprintf() and separate variables according to their order and comma. Close the file. Example: C // C program for the above approach#include <conio.h>#include <stdio.h>#include <string.h> // Driver Codeint main(){ // Substitute the file_path string // with full path of CSV file FILE* fp = fopen("file_path", "a+"); char name[50]; int accountno, amount; if (!fp) { // Error in file opening printf("Can't open file\n"); return 0; } // Asking user input for the // new record to be added printf("\nEnter Account Holder Name\n"); scanf("%s", &name); printf("\nEnter Account Number\n"); scanf("%d", &accountno); printf("\nEnter Available Amount\n"); scanf("%d", &amount); // Saving data in file fprintf(fp, "%s, %d, %d\n", name, accountno, amount); printf("\nNew Account added to record"); fclose(fp); return 0;} Output: Different from .txt and .dat file in terms of storing data in table format. Easy to organize data by direct user interaction or by the program. Widely adopted in financial industries to store and transmit data over the internet. Easily converted to other files and formats. It can be imported or exported to various platforms and interfaces. varshagumber28 C-File Handling CSV File Handling Articles C Language C Programs File Handling Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Docker - COPY Instruction Time complexities of different data structures SQL | Date functions Difference between Class and Object Arrays in C/C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() std::sort() in C++ STL Bitwise Operators in C/C++ Multidimensional Arrays in C / C++
[ { "code": null, "e": 25667, "s": 25639, "text": "\n24 Feb, 2022" }, { "code": null, "e": 26169, "s": 25667, "text": "In C programming, using arrays and string for data storage at run time which is volatile and gets memory in RAM. But to store data permanently in a hard disk which...
Difference between static and non-static method in Java - GeeksforGeeks
01 Nov, 2021 A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. Every method in java defaults to a non-static method without static keyword preceding it. Non-static methods can access any static method and static variable, without creating an instance of the object. Let us clarify the differences Below are the various important differences among these pointers as follows: Accessing members and methodsCalling processBinding processOverriding processMemory allocation Accessing members and methods Calling process Binding process Overriding process Memory allocation #1: Accessing members and methods A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables. Also, a static method can rewrite the values of any static data member. A non-static method can access static data members and static methods as well as non-static members and methods of another class or same class, also can change the values of any static data member Example Java // Java program to Illustrate Calling of a Static Method // Class 1// Helper classclass Helper { // Static method public static int sum(int a, int b) { // Simply returning the sum return a + b; }} // Class 2class GFG { // Main driver method public static void main(String[] args) { // Custom values for integer // to be summed up int n = 3, m = 6; // Calling the static method of above class // and storing sum in integer variable int s = Helper.sum(n, m); // Print and display the sum System.out.print("sum is = " + s); }} sum is = 9 Example Java // Java program to Illustrate Calling of a Non-Static Method // Class 1// Helper classclass Helper { // Non-static method public int sum(int a, int b) { // Returning sum of numbers return a + b; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Input integers to be summed up int n = 3, m = 6; // Creating object of above class Helper g = new Helper(); // Calling above method to compute sum int s = g.sum(n, m); // Calling the non-static method System.out.print("sum is = " + s); }} sum is = 9 #2: Calling process The memory of a static method is fixed in the ram, for this reason, we don’t need the object of a class in which the static method is defined to call the static method. To call the method we need to write the class name followed by the name of the method Syntax: Calling of static methods class GFG{ public static void geek() { } } // calling GFG.geek(); The memory of the non-static method is not fixed in the ram, so we need a class object to call a non-static method. To call the method we need to write the name of the method followed by the class object name Syntax: Calling of non-static methods class GFG{ public void geek() { } } // creating object GFG g = new GFG(); g.geek(); // calling #3: Binding process In the static method, the method use compile-time or early binding. For this reason, we can access the static method without creating an instance. In a non-static method, the method use runtime or dynamic binding. So that we cannot access a non-static method without creating an instance. #4: Overriding In the static method, we cannot override a static method, because of early binding. Example: Java // Override of static methodclass Parent { // static method static void show() { System.out.println("Parent"); }} // Parent inherit in Child classclass Child extends Parent { // override show() of Parent void show() { System.out.println("Child"); }} class GFG { public static void main(String[] args) { Parent p = new Parent(); // calling Parent's show() p.show(); // cannot override Parent's show() }} Output: java:15: error: show() in Child cannot override show() in Parent void show() ^ overridden method is static In the non-static method, we can override a non-static method. Because for override we need runtime polymorphism, which happens only in runtime binding. Example: Java // Override of non-static method class Parent { void show() { System.out.println("Parent"); }} // Parent inherit in Child classclass Child extends Parent { // override show() of Parent void show() { System.out.println("Child"); }} class GFG { public static void main(String[] args) { Parent p = new Parent(); // calling Parent's show() p.show(); Parent c = new Child(); // calling Child's show() c.show(); }} Output: Error Parent Child #5: Memory allocation In the static method, memory allocation happens only once, because the static keyword fixed a particular memory for that method in ram. So when the method is called every time in a program, each time that particular memory is used. For that reason, less memory is allocated. In the non-static method, here memory allocation happens when the method is invoked and the memory is allocated every time when the method is called. So much memory is used here. Now, lastly plotting table in order to grasp altogether harth TAMILMARAN C payyavulavijaykanth maheshvallamdas1993 Java-Functions Picked Static Keyword Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 25609, "s": 25581, "text": "\n01 Nov, 2021" }, { "code": null, "e": 26101, "s": 25609, "text": "A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or obje...
GregorianCalendar add() Method in Java - GeeksforGeeks
07 Aug, 2018 The java.util.GregorianCalendar.add(int calendarfield, int time) is an in-built method of GregorianCalendar class in Java. The function accepts a calendar field and the amount of time to be added to that particular calendar field as a parameter. Based on the calendar rules, the method adds or deducts, based on its sign, the specified amount of time to the specified field. Syntax: public void add(int calendarfield, int time) Parameters: The function accepts two mandatory parameters which are described below: calendarfield: The calendar field which is to be modified. time : The amount of time to be added. Return Values: This method has no return value. Exception: The method throws IllegalArgumentException if calendarfield has values ZONE_OFFSET, DST_OFFSET, or unknown, or if any of the calendar fields has an out-of-range value. Examples: Current Date and Time : Mon Jul 23 12:46:05 UTC 2018 Input : calendarfied = GregorianCalendar.YEAR, time = 2 Output : Thu Jul 23 12:46:05 UTC 2020 Input : calendarfied = GregorianCalendar.MONTH, time = 16 Output : Sat Nov 23 12:46:45 UTC 2019 Below programs illustrate the use of java.util.GregorianCalendar.add() method in Java:Program 1: // Java Program to demonstrate add() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Creating a new calendar GregorianCalendar newcalendar = (GregorianCalendar) GregorianCalendar.getInstance(); // Display the current date and time System.out.println(" Current Date and Time : " + newcalendar.getTime()); // Adding two months to the current date newcalendar.add((GregorianCalendar.MONTH), 2); // Display the modified date and time System.out.println(" Modified Date and Time : " + newcalendar.getTime()); }} Current Date and Time : Fri Aug 03 11:48:38 UTC 2018 Modified Date and Time : Wed Oct 03 11:48:38 UTC 2018 Program 2: // Java Program to demonstrate add() methodimport java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Creating a new calendar GregorianCalendar newcalendar = (GregorianCalendar) GregorianCalendar.getInstance(); // Display the current date and time System.out.println(" Current Date and Time : " + newcalendar.getTime()); // Adding twenty years to the current date newcalendar.add((GregorianCalendar.YEAR), 20); // Display the modified date and time System.out.println(" Modified Date and Time : " + newcalendar.getTime()); }} Current Date and Time : Fri Aug 03 11:48:40 UTC 2018 Modified Date and Time : Tue Aug 03 11:48:40 UTC 2038 Program 3: // Java Program to illustrate// GregorianCalendar.add()// function import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Creating a new calendar GregorianCalendar newcalendar = (GregorianCalendar) GregorianCalendar.getInstance(); // Display the current date and time System.out.println(" Current Date and Time : " + newcalendar.getTime()); // Deducting 16 months to the current date newcalendar.add((GregorianCalendar.MONTH), -16); // Display the modified date and time System.out.println(" Modified Date and Time : " + newcalendar.getTime()); // Deducting twelve years to the current date newcalendar.add((GregorianCalendar.MONTH), -12); // Display the modified date and time System.out.println(" Modified Date and Time : " + newcalendar.getTime()); }} Current Date and Time : Fri Aug 03 11:48:43 UTC 2018 Modified Date and Time : Mon Apr 03 11:48:43 UTC 2017 Modified Date and Time : Sun Apr 03 11:48:43 UTC 2016 Reference: https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#add() Java - util package Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n07 Aug, 2018" }, { "code": null, "e": 25600, "s": 25225, "text": "The java.util.GregorianCalendar.add(int calendarfield, int time) is an in-built method of GregorianCalendar class in Java. The function accepts a calendar field an...
Java Program Format Time in MMMM Format - GeeksforGeeks
02 Nov, 2020 In Java, The MMM format for months is a short form of the month using 3 characters. SimpleDateFormat class is used for implementing this format in java and you can import this package by using the following code. import java.text.SimpleDateFormat Example: MMMM Format: The MMMM format for months is the full name of the Month. For example -January, February, March, April, May, etc are the MMMM Format for the Month. Here, you will see the complete package that how you can use SimpleDateFormat class which extends DateFormat class. SimpleDateFormat class is also helpful to convert date to text format and also it’s parsing from text to date format and in normalization. Class SimpleDateFormat java.lang.Object java.text.Format java.text.DateFormat java.text.SimpleDateFormat Example 1: Display Month in MMM and MMMM Format Java // Java program to display Month // in MMM and MMMM Formatimport java.text.SimpleDateFormat;import java.util.Date; public class GFG { public static void main(String[] argv) throws Exception { // Setting the date object Date dat = new Date(); SimpleDateFormat dateFormat; // Setting MMM Format dateFormat = new SimpleDateFormat("MMM"); System.out.println(dateFormat.format(dat)); // Setting MMMM Format dateFormat = new SimpleDateFormat("MMMM"); System.out.println(dateFormat.format(dat));}} Output : Nov November Example 2: Display Date and Time in MMMM Format Java // Java Program to Display Date// and Time in MMMM Formatimport java.text.SimpleDateFormat;import java.util.Date; public class GFG { public static void main(String[] argv) throws Exception { // Setting the date object Date dat = new Date(); SimpleDateFormat dateFormat; // Setting the date and time in MMMM format dateFormat = new SimpleDateFormat("EEEE dd MMMM yyyy kk:mm:ss"); System.out.println(dateFormat.format(dat));}} Output: Monday 02 November 2020 11:46:05 Java-Date-Time Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n02 Nov, 2020" }, { "code": null, "e": 25439, "s": 25225, "text": "In Java, The MMM format for months is a short form of the month using 3 characters. SimpleDateFormat class is used for implementing this format in java and you can...
C# | Get an enumerator that iterates through Collection<T> - GeeksforGeeks
01 Feb, 2019 Collection<T>.GetEnumerator Method is used to get an enumerator that iterates through the Collection<T>. Syntax: public System.Collections.Generic.IEnumerator<T> GetEnumerator (); Return Value: This method returns an IEnumerator<T> for the Collection<T>. Below programs illustrate the use of above discussed method: Example 1: // C# code to get an Enumerator that// iterates through the Collection<T>using System;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); myColl.Add("A"); myColl.Add("B"); myColl.Add("C"); myColl.Add("D"); myColl.Add("E"); // Displaying the number of elements in Collection Console.WriteLine("The number of elements in myColl are: " + myColl.Count); // To get an Enumerator // for the Collection var enumerator = myColl.GetEnumerator(); // If MoveNext passes the end of the // collection, the enumerator is positioned // after the last element in the collection // and MoveNext returns false. while (enumerator.MoveNext()) { Console.WriteLine(enumerator.Current); } }} The number of elements in myColl are: 5 A B C D E Example 2: // C# code to get an Enumerator that// iterates through the Collection<T>using System;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of integers Collection<int> myColl = new Collection<int>(); myColl.Add(45); myColl.Add(56); myColl.Add(78); myColl.Add(75); // Displaying the number of elements in Collection Console.WriteLine("The number of elements in myColl are: " + myColl.Count); // To get an Enumerator // for the Collection var enumerator = myColl.GetEnumerator(); // If MoveNext passes the end of the // collection, the enumerator is positioned // after the last element in the collection // and MoveNext returns false. while (enumerator.MoveNext()) { Console.WriteLine(enumerator.Current); } }} The number of elements in myColl are: 4 45 56 78 75 Note: The foreach statement of the C# language hides the complexity of the enumerators. Therefore, using foreach is recommended, instead of directly manipulating the enumerator. Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection. Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element. An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined. This method is an O(1) operation. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.getenumerator?view=netframework-4.7.2 CSharp-Collection-Class CSharp-Collections.ObjectModel-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Abstract Classes C# | Class and Object C# | Constructors Extension Method in C# Introduction to .NET Framework C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method C# | Arrays C# | Data Types
[ { "code": null, "e": 25919, "s": 25891, "text": "\n01 Feb, 2019" }, { "code": null, "e": 26024, "s": 25919, "text": "Collection<T>.GetEnumerator Method is used to get an enumerator that iterates through the Collection<T>." }, { "code": null, "e": 26032, "s": 26024...
jQuery Interview Questions and Answers - GeeksforGeeks
03 Aug, 2021 What is jQuery ?jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM) and JavaScript.Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development. Does jQuery HTML work for both HTML and XML documents ?No, JQuery HTML doesn’t work with XML document. It only works for HTML documents. What are jQuery Selectors ? Give some examples.jQuery selectors are used to select the HTML elements and allows you to manipulate the HTML elements in a way we want. It selects the HTML elements on a variable parameter such as their name, classes, id, types, attributes, attribute values, etc. All selectors in jQuery are selected using a special sign i.e. dollar sign and parentheses:$("selector-name")Elements Selector: The elements selector selects the element on the basis of its name.Example:$("h1")Id Selector: The id selector selects the element on the basis of its id.Example:$("#gfg")Class Selector: The class selector selects the element on the basis of its class.Example:$(".GFG") What are the advantages of jQuery ?It contains wide range of plug-ins. jQuery allows developers to create plug-ins on top of the JavaScript library.Large development community.It has a good and comprehensive documentation.It contains lots of JavaScript library and it is easy to use compared to the standard JavaScript.jQuery lets users develop Ajax templates with ease, Ajax enables a sleeker interface where actions can be performed on pages without requiring the entire page to be reloaded.Being lightweight and a powerful chaining capability makes jQuery more strong. What are the methods used to provide effects?Some of methods are listed below which provides the effect:jQuery toggle() MethodjQuery slideDown() MethodjQuery Effect fadeOut() MethodjQuery fadeToggle() Method Difference between .empty(), .remove() and, .detach() in Jquery ?jQuery empty() Method: The empty() method in jQuery is used to remove all child nodes and its content for the selected elements.jQuery remove() Method: The remove() method in JQuery is used to remove all the selected elements including all the text. This method also remove data and all the events of the selected elements.jQuery detach() Method: The detach() method in jQuery is used to remove the selected elements from the DOM tree including its all text and child nodes but it keeps the data and the events. Document Object Model (DOM) is a World Wide Web Consortium standard. This defines for accessing elements in the DOM tree.Note: The remove() method is faster than empty() or detach() method. Is jQuery a JavaScript or JSON library file ?jQuery is a library of JavaScript file and it consists of DOM event effects and also the Ajax functions. jQuery is alleged to be one JavaScript file. What are the various ajax functions available in Jquery ?Ajax allows the user to exchange data with a server and update parts of a page without reloading the entire page. Some of the functions of ajax are as follows:jQuery ajaxSetup() Method: The ajaxSetup() method is used to set the default values for future AJAX requests.jQuery ajax() Method: The ajax() method is used to perform an AJAX request or asynchronous HTTP request.jQuery getScript() Method: The getScript() method is used to run a JavaScript using AJAX HTTP GET request.jQuery getJSON() Method: The getJSON() method fetches JSON-encoded data from the server using a GET HTTP request. Mention the compatible operating systems with jQuery.MacWindowsLinux How to include the jQuery library in the ASP.Net project ?Download the jQuery library from jQuery.cominclude that reference in the asp.net page. Explain bind() vs live() vs delegate() methods in jQuery.The bind() method does not attach the events to those elements that are added once DOM is loaded whereas live() and delegate() methods attach events to the future elements also.The difference between live() and delegate() methods is that the live() function does not work in chaining. It will work only on a selector or an element while delegate() method will work in chaining. Write the command that gives the version of jQuery ?The command $.ui.version returns jQuery UI version. What is jQuery connect ?A jQuery connect is a plugin that is used to connect or bind a function with another function. Connect is used to execute the function from the other function or plugin is executed. How to use connect ?Download jQuery connect file from jQuery.comInclude that file in the HTML file.Use $.connect function to connect a function to another function. What is the use of param() method in JQuery ?The param() method in jQuery is used to create a serialized representation of an object. Difference between $(this) and this in jQuery ?The this and $(this) references are same but the difference is “this” is used in the traditional way but when “this” is used with $() then it becomes a jQuery object. Difference between find and children methods ?The find() method is used to find all the descendant elements of the selected element and the children() method is used to find all the children element related to that selected element. In what scenarios jQuery can be used ?jQuery can be used in following scenarios:Mainly for Animation effectsManipulation purposeCalling functions on eventsApply CSS static or dynamic How to read, write and delete cookies in jQuery ?We can deal with cookies in jquery using Dough cookie plugin. Dough is easy to use and has powerful features.Create cookie:$.dough(“cookie_name”, “cookie_value”);Read Cookie:$.dough(“cookie_name”);Delete cookie:$.dough(“cookie_name”, “remove”); Features of jQuery which are used in web applications ?jQuery uses features like Sliding, File uploading and accordian in web applications. What is jQuery ?jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM) and JavaScript.Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development. Does jQuery HTML work for both HTML and XML documents ?No, JQuery HTML doesn’t work with XML document. It only works for HTML documents. What are jQuery Selectors ? Give some examples.jQuery selectors are used to select the HTML elements and allows you to manipulate the HTML elements in a way we want. It selects the HTML elements on a variable parameter such as their name, classes, id, types, attributes, attribute values, etc. All selectors in jQuery are selected using a special sign i.e. dollar sign and parentheses:$("selector-name")Elements Selector: The elements selector selects the element on the basis of its name.Example:$("h1")Id Selector: The id selector selects the element on the basis of its id.Example:$("#gfg")Class Selector: The class selector selects the element on the basis of its class.Example:$(".GFG") $("selector-name") Elements Selector: The elements selector selects the element on the basis of its name.Example:$("h1") $("h1") Id Selector: The id selector selects the element on the basis of its id.Example:$("#gfg") $("#gfg") Class Selector: The class selector selects the element on the basis of its class.Example:$(".GFG") $(".GFG") What are the advantages of jQuery ?It contains wide range of plug-ins. jQuery allows developers to create plug-ins on top of the JavaScript library.Large development community.It has a good and comprehensive documentation.It contains lots of JavaScript library and it is easy to use compared to the standard JavaScript.jQuery lets users develop Ajax templates with ease, Ajax enables a sleeker interface where actions can be performed on pages without requiring the entire page to be reloaded.Being lightweight and a powerful chaining capability makes jQuery more strong. It contains wide range of plug-ins. jQuery allows developers to create plug-ins on top of the JavaScript library. Large development community. It has a good and comprehensive documentation. It contains lots of JavaScript library and it is easy to use compared to the standard JavaScript. jQuery lets users develop Ajax templates with ease, Ajax enables a sleeker interface where actions can be performed on pages without requiring the entire page to be reloaded. Being lightweight and a powerful chaining capability makes jQuery more strong. What are the methods used to provide effects?Some of methods are listed below which provides the effect:jQuery toggle() MethodjQuery slideDown() MethodjQuery Effect fadeOut() MethodjQuery fadeToggle() Method jQuery toggle() Method jQuery slideDown() Method jQuery Effect fadeOut() Method jQuery fadeToggle() Method Difference between .empty(), .remove() and, .detach() in Jquery ?jQuery empty() Method: The empty() method in jQuery is used to remove all child nodes and its content for the selected elements.jQuery remove() Method: The remove() method in JQuery is used to remove all the selected elements including all the text. This method also remove data and all the events of the selected elements.jQuery detach() Method: The detach() method in jQuery is used to remove the selected elements from the DOM tree including its all text and child nodes but it keeps the data and the events. Document Object Model (DOM) is a World Wide Web Consortium standard. This defines for accessing elements in the DOM tree.Note: The remove() method is faster than empty() or detach() method. jQuery empty() Method: The empty() method in jQuery is used to remove all child nodes and its content for the selected elements. jQuery remove() Method: The remove() method in JQuery is used to remove all the selected elements including all the text. This method also remove data and all the events of the selected elements. jQuery detach() Method: The detach() method in jQuery is used to remove the selected elements from the DOM tree including its all text and child nodes but it keeps the data and the events. Document Object Model (DOM) is a World Wide Web Consortium standard. This defines for accessing elements in the DOM tree. Note: The remove() method is faster than empty() or detach() method. Is jQuery a JavaScript or JSON library file ?jQuery is a library of JavaScript file and it consists of DOM event effects and also the Ajax functions. jQuery is alleged to be one JavaScript file. What are the various ajax functions available in Jquery ?Ajax allows the user to exchange data with a server and update parts of a page without reloading the entire page. Some of the functions of ajax are as follows:jQuery ajaxSetup() Method: The ajaxSetup() method is used to set the default values for future AJAX requests.jQuery ajax() Method: The ajax() method is used to perform an AJAX request or asynchronous HTTP request.jQuery getScript() Method: The getScript() method is used to run a JavaScript using AJAX HTTP GET request.jQuery getJSON() Method: The getJSON() method fetches JSON-encoded data from the server using a GET HTTP request. jQuery ajaxSetup() Method: The ajaxSetup() method is used to set the default values for future AJAX requests. jQuery ajax() Method: The ajax() method is used to perform an AJAX request or asynchronous HTTP request. jQuery getScript() Method: The getScript() method is used to run a JavaScript using AJAX HTTP GET request. jQuery getJSON() Method: The getJSON() method fetches JSON-encoded data from the server using a GET HTTP request. Mention the compatible operating systems with jQuery.MacWindowsLinux Mac Windows Linux How to include the jQuery library in the ASP.Net project ?Download the jQuery library from jQuery.cominclude that reference in the asp.net page. Download the jQuery library from jQuery.com include that reference in the asp.net page. Explain bind() vs live() vs delegate() methods in jQuery.The bind() method does not attach the events to those elements that are added once DOM is loaded whereas live() and delegate() methods attach events to the future elements also.The difference between live() and delegate() methods is that the live() function does not work in chaining. It will work only on a selector or an element while delegate() method will work in chaining. The difference between live() and delegate() methods is that the live() function does not work in chaining. It will work only on a selector or an element while delegate() method will work in chaining. Write the command that gives the version of jQuery ?The command $.ui.version returns jQuery UI version. What is jQuery connect ?A jQuery connect is a plugin that is used to connect or bind a function with another function. Connect is used to execute the function from the other function or plugin is executed. How to use connect ?Download jQuery connect file from jQuery.comInclude that file in the HTML file.Use $.connect function to connect a function to another function. Download jQuery connect file from jQuery.com Include that file in the HTML file. Use $.connect function to connect a function to another function. What is the use of param() method in JQuery ?The param() method in jQuery is used to create a serialized representation of an object. Difference between $(this) and this in jQuery ?The this and $(this) references are same but the difference is “this” is used in the traditional way but when “this” is used with $() then it becomes a jQuery object. Difference between find and children methods ?The find() method is used to find all the descendant elements of the selected element and the children() method is used to find all the children element related to that selected element. In what scenarios jQuery can be used ?jQuery can be used in following scenarios:Mainly for Animation effectsManipulation purposeCalling functions on eventsApply CSS static or dynamic Mainly for Animation effects Manipulation purpose Calling functions on events Apply CSS static or dynamic How to read, write and delete cookies in jQuery ?We can deal with cookies in jquery using Dough cookie plugin. Dough is easy to use and has powerful features.Create cookie:$.dough(“cookie_name”, “cookie_value”);Read Cookie:$.dough(“cookie_name”);Delete cookie:$.dough(“cookie_name”, “remove”); Create cookie:$.dough(“cookie_name”, “cookie_value”); Read Cookie:$.dough(“cookie_name”); Delete cookie:$.dough(“cookie_name”, “remove”); Features of jQuery which are used in web applications ?jQuery uses features like Sliding, File uploading and accordian in web applications. jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. interview-preparation JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 41992, "s": 41964, "text": "\n03 Aug, 2021" }, { "code": null, "e": 47964, "s": 41992, "text": "What is jQuery ?jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Mo...
Introduction to MEAN Stack - GeeksforGeeks
22 Jun, 2020 MEAN Stack is one of the most popular Technology Stack. It is used to develop a Full Stack Web Application. Although it is a Stack of different technologies, all of these are based on JavaScript language. MEAN Stands for: M – MongoDBE – ExpressA – AngularN – Node.js M – MongoDB E – Express A – Angular N – Node.js This stack leads to faster development as well as the deployment of the Web Application. Angular is Frontend Development Framework whereas Node.js, Express, and MongoDB are used for Backend development as shown in the below figure. Flow of Data in MEAN Stack Application: Here, each module communicates with the others in order to have a flow of the data from Server/Backend to Client/Frontend. Getting Started with each Technology with examples: The description of each Technology in this Stack as well as the links to learn them are given below: 1. Node.js: Node.js is used to write the Server Side Code in Javascript. One of the most important points is that it runs the JavaScript code outside the Browser. It is cross-platform and Open Source. Pre-requisites to learn Node.js- JavaScript/TypeScript Go to Node.js Downloads and click Download button to get the latest version and Install as per your Operating System. Verify whether it is installed correctly by checking the version:node -vIf no version is obtained then it is not installed correctly. node -v If no version is obtained then it is not installed correctly. Check the version of npm (It is installed by default with node):npm -v npm -v Create an index.js file inside your project folder and copy the following code to it:var http = require("http"); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); // Send the response text as "Hello World" response.end('Hello World\n');}).listen(3100); console.log('Server running at http://127.0.0.1:3100/'); var http = require("http"); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); // Send the response text as "Hello World" response.end('Hello World\n');}).listen(3100); console.log('Server running at http://127.0.0.1:3100/'); Now open terminal and execute the following command:node index.js node index.js You will see on Terminal console a log which says:Server running at http://127.0.0.1:3100/ Server running at http://127.0.0.1:3100/ Go to the browser and type the URL: http://127.0.0.1:3100/ you will see an output as below: Links to learn more about Node.js:1. Introduction to Node.js2. Node.js Tutorials3. Get Knowledge of Latest Release of Node.js 2. AngularJS: Angular is a Front-end Open Source Framework developed by Google Team. This framework is revised in such a way that backward compatibility is maintained (If there is any breaking change then Angular informs it very early). Angular projects are simple to create using Angular CLI (Command Line Interface) tool developed by the Angular team. Pre-requisites to learn Angular:TypeScriptCSS PreprocessorTemplate Code (Angular Material, HTML 5, etc) TypeScriptCSS PreprocessorTemplate Code (Angular Material, HTML 5, etc) TypeScript CSS Preprocessor Template Code (Angular Material, HTML 5, etc) Installing Angular CLI – Command Line Interface using npm (Node Package Manager)npm install -g @angular/cli npm install -g @angular/cli Now check whether it was installed correctly using below command:ng --versionIt should show something like: ng --version It should show something like: Now, create a new project using below command:ng new project_name ng new project_name Go to project Directory using below command:cd project_name cd project_name Start the Angular Application using below command:ng serve ng serve Application will start on http://localhost:4200, you will see the following: Now make changes in app.component.html file and save the file, the application will reload automatically and corresponding changes will be reflected. Links of related Angular articles:1. AngularJS2. Angular 7 Introduction3. Angular 7 Installation4. Angular 7 Data Services and Observables5. Angular 7 Simple To do App6. Get Knowledge of Latest Release of Angular 3. MongoDB: MongoDB is a NoSQL Database. It has JSON like documents. It is document oriented database. Pre-requisites to learn MongoDB:What is DatabaseDisadvantages of SQL Database What is DatabaseDisadvantages of SQL Database What is Database Disadvantages of SQL Database Creating a database:use database_name; use database_name; Create a collection:db.createCollection("first_collection"); db.createCollection("first_collection"); Insert a record in the Collection:db.first_collection.insertOne( {name:"Geeks For Geeks"} ); db.first_collection.insertOne( {name:"Geeks For Geeks"} ); Print all the records in a collection:db.first_collection.find() db.first_collection.find() Links regarding MongoDB:1. MongoDB Introduction2. MongoDB Getting Started3. Defining, Creating and Dropping a MongoDB collection4. How MongoDB works ?5. Get Knowledge of Latest Release of MongoDB 4. ExpressJS: Express is a web Framework build on Node.js and used to make API and to build Web Applications. Pre-requisites to learn Express:JavaScript/ TypeScriptNode.js JavaScript/ TypeScriptNode.js JavaScript/ TypeScript Node.js Initialize a Project by typing the following command on terminal:npm init npm init It will ask some questions, Press enter in order to set all the default options. This will create package.json file as shown below:{ "name": "gfg-express", "version": "1.0.0", "description": "Basic Express Node.js Application", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC",} { "name": "gfg-express", "version": "1.0.0", "description": "Basic Express Node.js Application", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC",} Install the express using below command:npm install express --save npm install express --save Now, the package.json file will be changed to add the dependencies as shown below:{ "name": "gfg-express", "version": "1.0.0", "description": "Basic Express Node.js Application", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "express": "^4.17.1" }} { "name": "gfg-express", "version": "1.0.0", "description": "Basic Express Node.js Application", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "express": "^4.17.1" }} Create index.js file and add the below code to it:const express = require('express')const app = express()const PORT = 3000 app.get('/', (req, res) => res.send('Hello World!')) app.listen(PORT, () => console.log(`Example app listening at http://localhost:${PORT}`)) const express = require('express')const app = express()const PORT = 3000 app.get('/', (req, res) => res.send('Hello World!')) app.listen(PORT, () => console.log(`Example app listening at http://localhost:${PORT}`)) Start the express server using below command:node index.js node index.js Go to http://localhost:3000 to see the output as below: Links to learn ExpressJS:1. Introduction to Express2. Design first Application using Express AngularJS-Misc MongoDB Node.js-Misc JavaScript MongoDB Node.js Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Upload and Retrieve Image on MongoDB using Mongoose Spring Boot JpaRepository with Example Mongoose | findByIdAndUpdate() Function Login form using Node.js and MongoDB Aggregation in MongoDB
[ { "code": null, "e": 25935, "s": 25907, "text": "\n22 Jun, 2020" }, { "code": null, "e": 26140, "s": 25935, "text": "MEAN Stack is one of the most popular Technology Stack. It is used to develop a Full Stack Web Application. Although it is a Stack of different technologies, all o...
How to use Divider Component in ReactJS? - GeeksforGeeks
05 Mar, 2021 A divider is a thin line that groups content in lists and layouts. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Divider Component in ReactJS using the following approach. Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command. npm install @material-ui/core Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from "react";import Divider from "@material-ui/core/Divider";import ListItem from "@material-ui/core/ListItem";import ListItemText from "@material-ui/core/ListItemText";import List from "@material-ui/core/List"; export default function App() { return ( <div style={{ display: "block", padding: 30 }}> <h4>How to use Divider Component in ReactJS?</h4> <List component="nav"> <ListItem button> <ListItemText primary="1 Divider Below this list item" /> </ListItem> <Divider /> <ListItem button divider> <ListItemText primary="2 Divider Below this list item" /> </ListItem> <Divider /> <br /> <Divider /> </List> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project. npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. Reference: https://material-ui.com/components/dividers/ Material-UI React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n05 Mar, 2021" }, { "code": null, "e": 26305, "s": 26071, "text": "A divider is a thin line that groups content in lists and layouts. Material UI for React has this component available for us, and it is very easy to integrate. We ...
SUBSTRING() Function in SQL Server - GeeksforGeeks
28 Sep, 2020 The SUBSTRING() function extracts a substring starting from a position in an input string with a given length. In the case of substring, you need an input string and need to mention the starting point and the total length of the string. Input : String, start, length output : substring. Syntax : SUBSTRING(input_string, start, length); Parameter :SUBSTRING function accepts three-parameter like String, start, length. Let’s have a look. input_string –It can be a character, binary, text, ntext, or image expression. start – It is an integer defining the location where the returned substring starts. The first position in the string is 1. length – It is a positive integer that specifies the number of characters to be returned from the substring. Returns :It returns a substring with a specified length starting from a location in an input string. Example-1 :Using SUBSTRING() function with literal strings. SELECT SUBSTRING('SQL In Geeksforgeeks', 7, 18 ) AS ExtractString; Output : Example-2 :Using SUBSTRING() function with table columns. Table -Player_Details SELECT SUBSTRING(PlayerName, 1, 5) AS ExtractString FROM Player_Details; Output : DBMS-SQL SQL-Server substring SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? Difference between SQL and NoSQL Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE SQL - ORDER BY SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL?
[ { "code": null, "e": 26117, "s": 26089, "text": "\n28 Sep, 2020" }, { "code": null, "e": 26354, "s": 26117, "text": "The SUBSTRING() function extracts a substring starting from a position in an input string with a given length. In the case of substring, you need an input string a...
atan2() function in C++ STL - GeeksforGeeks
21 Jun, 2021 The atan2() is an inbuilt function in C++ STL which returns tangent inverse of (y/x), where y is the proportion of the y-coordinate and x is the proportion of the x-coordinate. The numeric value lies between –and representing the angle of a (x, y) point and positive x-axis. It is the counterclockwise angle, measured in radian, between the positive X-axis, and the point (x, y). Syntax: atan2(data_type y, data_type x) Parameters:The function accepts two mandatory parameters which are described below: y – This value specifies y-coordinate. x – This value specifies the x-coordinate. The parameters can be of double, float or long double datatype. Return Value: The function returns a numeric value between –and representing the angle of a (x, y) point and positive x-axis. It is the counterclockwise angle, measured in radian, between the positive X-axis, and the point (x, y). Below programs illustrate the atan2() function: Program 1: CPP // CPP program to demonstrate the atan2()// function when both parameters are of// same type#include<bits/stdc++.h>using namespace std; int main(){ double x = 10.0, y = 10.0, result; result = atan2(y, x); cout << "atan2(y/x) = " << result << " radians" << endl; cout << "atan2(y/x) = " << result * 180 / 3.141592 << " degrees" << endl; return 0;} atan2(y/x) = 0.785398 radians atan2(y/x) = 45 degrees Program 2: CPP // CPP program to demonstrate the atan2()// function when both parameters are of// different types#include <bits/stdc++.h>using namespace std; int main(){ double result; float x = -10.0; int y = 10; result = atan2(y, x); cout << "atan2(y/x) = " << result << " radians" << endl; cout << "atan2(y/x) = " << result * 180 / 3.141592 << " degrees" << endl; return 0;} atan2(y/x) = 2.35619 radians atan2(y/x) = 135 degrees Program 3: CPP // CPP program to demonstrate the atan2()// function when y/x is undefined#include<bits/stdc++.h>using namespace std; int main(){ double x = 0.0, y = 10.0, result; result = atan2(y, x); cout << "atan2(y/x) = " << result << " radians" << endl; cout << "atan2(y/x) = " << result * 180 / 3.141592 << " degrees" << endl; return 0;} atan2(y/x) = 1.5708 radians atan2(y/x) = 90 degrees Program 4: CPP // CPP program to demonstrate the atan2()// function when both parameters are zero#include<bits/stdc++.h>using namespace std; int main(){ double x = 0.0, y = 0.0, result; result = atan2(y, x); cout << "atan2(y/x) = " << result << " radians" << endl; cout << "atan2(y/x) = " << result * 180 / 3.141592 << " degrees" << endl; return 0;} atan2(y/x) = 0 radians atan2(y/x) = 0 degrees Errors and Exceptions: The function returns no matching function for call to error when a string or character is passed as an argument. Program 5: CPP // CPP program to demonstrate the atan2()// errors and exceptions#include<bits/stdc++.h>using namespace std; int main(){ double x = 0.0, y = 10.0, result; result = atan2("1", x); cout << "atan2(y/x) = " << result << " radians" << endl; cout << "atan2(y/x) = " << result * 180 / 3.141592 << " degrees" << endl; return 0;} Output: prog.cpp:9:26: error: no matching function for call to 'atan2(const char [2], double&)' result = atan2("1", x); simmytarika5 CPP-Functions cpp-math STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Operator Overloading in C++ Socket Programming in C/C++ Bitwise Operators in C/C++ Multidimensional Arrays in C / C++ Virtual Function in C++ Constructors in C++ Templates in C++ with Examples
[ { "code": null, "e": 24610, "s": 24582, "text": "\n21 Jun, 2021" }, { "code": null, "e": 25000, "s": 24610, "text": "The atan2() is an inbuilt function in C++ STL which returns tangent inverse of (y/x), where y is the proportion of the y-coordinate and x is the proportion of the ...
Timer objects in Python
Timer objects are used to create some actions which are bounded by the time period. Using timer object create some threads that carries out some actions. In python Timer is a subclass of Thread class. Using start() method timer is started. threading.Timer(interval, function, args = None, kwargs = None), this is the syntax of creating timer of Timer object. Here in this example at first we shall get After 3 second it will display import threading def mytimer(): print("Python Program\n") my_timer = threading.Timer(3.0, mytimer) my_timer.start() print("Bye\n") Bye Python Program timer.cancel() is the syntax for cancelling the timer. import threading def mytimer(): print("Python Program\n") my_timer = threading.Timer(3.0, mytimer) my_timer.start() print("Cancelling timer\n") my_timer.cancel() print("Bye\n") Cancelling Timer Bye
[ { "code": null, "e": 1302, "s": 1062, "text": "Timer objects are used to create some actions which are bounded by the time period. Using timer object create some threads that carries out some actions. In python Timer is a subclass of Thread class. Using start() method timer is started." }, { ...
Erlang - Recursion
Recursion is an important part of Erlang. First let’s see how we can implement simple recursion by implementing the factorial program. -module(helloworld). -export([fac/1,start/0]). fac(N) when N == 0 -> 1; fac(N) when N > 0 -> N*fac(N-1). start() -> X = fac(4), io:fwrite("~w",[X]). The following things need to be noted about the above program − We are first defining a function called fac(N). We are first defining a function called fac(N). We are able to define the recursive function by calling fac(N) recursively. We are able to define the recursive function by calling fac(N) recursively. The output of the above program is − 24 In this section, we will understand in detail the different types of recursions and its usage in Erlang. A more practical approach to recursion can be seen with a simple example which is used to determine the length of a list. A list can have multiple values such as [1,2,3,4]. Let’s use recursion to see how we can get the length of a list. Example -module(helloworld). -export([len/1,start/0]). len([]) -> 0; len([_|T]) -> 1 + len(T). start() -> X = [1,2,3,4], Y = len(X), io:fwrite("~w",[Y]). The following things need to be noted about the above program − The first function len([]) is used for the special case condition if the list is empty. The first function len([]) is used for the special case condition if the list is empty. The [H|T] pattern to match against lists of one or more elements, as a list of length one will be defined as [X|[]] and a list of length two will be defined as [X|[Y|[]]]. Note that the second element is a list itself. This means we only need to count the first one and the function can call itself on the second element. Given each value in a list counts as a length of 1. The [H|T] pattern to match against lists of one or more elements, as a list of length one will be defined as [X|[]] and a list of length two will be defined as [X|[Y|[]]]. Note that the second element is a list itself. This means we only need to count the first one and the function can call itself on the second element. Given each value in a list counts as a length of 1. The output of the above program will be − Output 4 To understand how the tail recursion works, let’s understand how the following code in the previous section works. Syntax len([]) -> 0; len([_|T]) -> 1 + len(T). The answer to 1 + len(Rest) needs the answer of len(Rest) to be found. The function len(Rest) itself then needed the result of another function call to be found. The additions would get stacked until the last one is found, and only then would the final result be calculated. Tail recursion aims to eliminate this stacking of operation by reducing them as they happen. In order to achieve this, we will need to hold an extra temporary variable as a parameter in our function. The aforementioned temporary variable is sometimes called accumulator and acts as a place to store the results of our computations as they happen in order to limit the growth of our calls. Let’s look at an example of tail recursion − Example -module(helloworld). -export([tail_len/1,tail_len/2,start/0]). tail_len(L) -> tail_len(L,0). tail_len([], Acc) -> Acc; tail_len([_|T], Acc) -> tail_len(T,Acc+1). start() -> X = [1,2,3,4], Y = tail_len(X), io:fwrite("~w",[Y]). The output of the above program is − Output 4 Let’s look at an example of recursion. This time around let’s write a function which takes an integer as its first parameter and then any other term as its second parameter. It will then create a list of as many copies of the term as specified by the integer. Let’s look at how an example of this would look like − -module(helloworld). -export([duplicate/2,start/0]). duplicate(0,_) -> []; duplicate(N,Term) when N > 0 -> io:fwrite("~w,~n",[Term]), [Term|duplicate(N-1,Term)]. start() -> duplicate(5,1). The output of the above program will be − 1, 1, 1, 1, 1, There are no bounds to which you can use recursion in Erlang. Let’s quickly now look at how we can reverse the elements of a list using recursion. The following program can be used to accomplish this. -module(helloworld). -export([tail_reverse/2,start/0]). tail_reverse(L) -> tail_reverse(L,[]). tail_reverse([],Acc) -> Acc; tail_reverse([H|T],Acc) -> tail_reverse(T, [H|Acc]). start() -> X = [1,2,3,4], Y = tail_reverse(X), io:fwrite("~w",[Y]). The output of the above program will be − [4,3,2,1] The following things need to be noted about the above program − We are again using the concept of temporary variables to store each element of the List in a variable called Acc. We are again using the concept of temporary variables to store each element of the List in a variable called Acc. We then call tail_reverse recursively, but this time around, we ensure that the last element is put in the new list first. We then call tail_reverse recursively, but this time around, we ensure that the last element is put in the new list first. We then recursively call tail_reverse for each element in the list. We then recursively call tail_reverse for each element in the list. Print Add Notes Bookmark this page
[ { "code": null, "e": 2436, "s": 2301, "text": "Recursion is an important part of Erlang. First let’s see how we can implement simple recursion by implementing the factorial program." }, { "code": null, "e": 2599, "s": 2436, "text": "-module(helloworld). \n-export([fac/1,start/0])...
Difference between fork() and exec() in C
Here we will see the effect of fork() and exec() system call in C. The fork is used to create a new process by duplicating the calling process. The new process is the child process. See the following property. The child process has its own unique process id. The parent process id of the child process is same as the process id of the calling process. The child process does not inherit the parent’s memory lock and semaphores. The fork() returns the PID of the child process. If the value is non-zero, then it is parent process’s id, and if this is 0, then this is child process’s id. The exec() system call is used to replace the current process image with the new process image. It loads the program into the current space, and runs it from the entry point. So the main difference between fork() and exec() is that fork starts new process which is a copy of the main process. the exec() replaces the current process image with new one, Both parent and child processes are executed simultaneously. #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <sys/wait.h> int main() { pid_t process_id; int return_val = 1; int state; process_id = fork(); if (process_id == -1) { //when process id is negative, there is an error, unable to fork printf("can't fork, error occured\n"); exit(EXIT_FAILURE); } else if (process_id == 0) { //the child process is created printf("The child process is (%u)\n",getpid()); char * argv_list[] = {"ls","-lart","/home",NULL}; execv("ls",argv_list); // the execv() only return if error occured. exit(0); } else { //for the parent process printf("The parent process is (%u)\n",getppid()); if (waitpid(process_id, &state, 0) > 0) { //wait untill the process change its state if (WIFEXITED(state) && !WEXITSTATUS(state)) printf("program is executed successfully\n"); else if (WIFEXITED(state) && WEXITSTATUS(state)) { if (WEXITSTATUS(state) == 127) { printf("Execution failed\n"); } else printf("program terminated with non-zero status\n"); } else printf("program didn't terminate normally\n"); } else { printf("waitpid() function failed\n"); } exit(0); } return 0; } The parent process is (8627) The child process is (8756) program is executed successfully
[ { "code": null, "e": 1272, "s": 1062, "text": "Here we will see the effect of fork() and exec() system call in C. The fork is used to create a new process by duplicating the calling process. The new process is the child process. See the following property." }, { "code": null, "e": 1321, ...
Python Program For Finding Intersection Point Of Two Linked Lists - GeeksforGeeks
11 Dec, 2021 There are two singly linked lists in a system. By some programming error, the end node of one of the linked list got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge. Above diagram shows an example with two linked lists having 15 as intersection points. Method 1(Simply use two loops): Use 2 nested for loops. The outer loop will be for each node of the 1st list and the inner loop will be for the 2nd list. In the inner loop, check if any of the nodes of the 2nd list is the same as the current node of the first linked list. The time complexity of this method will be O(M * N) where m and n are the numbers of nodes in two lists. Method 2 (Mark Visited Nodes): This solution requires modifications to basic linked list data structure. Have a visited flag with each node. Traverse the first linked list and keep marking visited nodes. Now traverse the second linked list, If you see a visited node again then there is an intersection point, return the intersecting node. This solution works in O(m+n) but requires additional information with each node. A variation of this solution that doesn’t require modification to the basic data structure can be implemented using a hash. Traverse the first linked list and store the addresses of visited nodes in a hash. Now traverse the second linked list and if you see an address that already exists in the hash then return the intersecting node. Method 3(Using difference of node counts): Get count of the nodes in the first list, let count be c1. Get count of the nodes in the second list, let count be c2. Get the difference of counts d = abs(c1 – c2) Now traverse the bigger list from the first node till d nodes so that from here onwards both the lists have equal no of nodes Then we can traverse both the lists in parallel till we come across a common node. (Note that getting a common node is done by comparing the address of the nodes) Below image is a dry run of the above approach: Below is the implementation of the above approach : Python3 # Python program to implement# the above approach# Defining a node for LinkedListclass Node: def __init__(self, data): self.data = data self.next = None def getIntersectionNode(head1, head2): # Finding the total number of elements # in head1 LinkedList c1=getCount(head1) # Finding the total number of elements # in head2 LinkedList c2=getCount(head2) # Traverse the bigger node by 'd' so that # from that node onwards, both LinkedList # would be having same number of nodes and # we can traverse them together. if c1 > c2: d = c1 - c2 return _getIntersectionNode(d, head1, head2) else: d = c2 - c1 return _getIntersectionNode(d, head2, head1) def _getIntersectionNode(d, head1, head2): current1 = head1 current2 = head2 for i in range(d): if current1 is None: return -1 current1 = current1.next while current1 is not None and current2 is not None: # Instead of values, we need to check # if there addresses are same because # there can be a case where value is # same but that value is not an # intersecting point. if current1 is current2: # or current2.data (the value # would be same) return current1.data current1 = current1.next current2 = current2.next # Incase, we are not able to find # our intersecting point. return -1 # Function to get the count of a LinkedListdef getCount(node): cur=node count=0 while cur is not None: count+=1 cur=cur.next return count # Driver codeif __name__ == '__main__': # Creating two LinkedList # 1st one: 3->6->9->15->30 # 2nd one: 10->15->30 # We can see that 15 would be # our intersection point # Defining the common node common = Node(15) #Defining the first LinkedList head1 = Node(3) head1.next = Node(6) head1.next.next = Node(9) head1.next.next.next = common head1.next.next.next.next = Node(30) # Defining the second LinkedList head2 = Node(10) head2.next = common head2.next.next = Node(30) print("The node of intersection is ", getIntersectionNode(head1,head2))# This code is contributed by Ansh Gupta. Output: The node of intersection is 15 Time Complexity: O(m+n) Auxiliary Space: O(1) Method 4(Make circle in first list): Thanks to Saravanan Man for providing below solution. 1. Traverse the first linked list(count the elements) and make a circular linked list. (Remember the last node so that we can break the circle later on). 2. Now view the problem as finding the loop in the second linked list. So the problem is solved. 3. Since we already know the length of the loop(size of the first linked list) we can traverse those many numbers of nodes in the second list, and then start another pointer from the beginning of the second list. we have to traverse until they are equal, and that is the required intersection point. 4. remove the circle from the linked list. Time Complexity: O(m+n) Auxiliary Space: O(1) Method 5 (Reverse the first list and make equations): Thanks to Saravanan Mani for providing this method. 1) Let X be the length of the first linked list until intersection point. Let Y be the length of the second linked list until the intersection point. Let Z be the length of the linked list from the intersection point to End of the linked list including the intersection node. We Have X + Z = C1; Y + Z = C2; 2) Reverse first linked list. 3) Traverse Second linked list. Let C3 be the length of second list - 1. Now we have X + Y = C3 We have 3 linear equations. By solving them, we get X = (C1 + C3 – C2)/2; Y = (C2 + C3 – C1)/2; Z = (C1 + C2 – C3)/2; WE GOT THE INTERSECTION POINT. 4) Reverse first linked list. Advantage: No Comparison of pointers. Disadvantage: Modifying linked list(Reversing list). Time complexity: O(m+n) Auxiliary Space: O(1) Method 6 (Traverse both lists and compare addresses of last nodes): This method is only to detect if there is an intersection point or not. (Thanks to NeoTheSaviour for suggesting this) 1) Traverse list 1, store the last node address 2) Traverse list 2, store the last node address. 3) If nodes stored in 1 and 2 are same then they are intersecting. The time complexity of this method is O(m+n) and used Auxiliary space is O(1) Please refer complete article on Write a function to get the intersection point of two Linked Lists for more details! Accolite Amazon D-E-Shaw FactSet Goldman Sachs Linked Lists MakeMyTrip MAQ Software Microsoft Qualcomm Snapdeal Visa Zopper Linked List Python Python Programs Accolite Amazon Microsoft Snapdeal D-E-Shaw FactSet MakeMyTrip Visa Goldman Sachs MAQ Software Qualcomm Zopper Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Singly Linked List | Insertion Swap nodes in a linked list without swapping data Given a linked list which is sorted, how will you insert in sorted way Delete a node in a Doubly Linked List Circular Linked List | Set 2 (Traversal) Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24934, "s": 24906, "text": "\n11 Dec, 2021" }, { "code": null, "e": 25177, "s": 24934, "text": "There are two singly linked lists in a system. By some programming error, the end node of one of the linked list got linked to the second list, forming an inverted...
Java Math acos() Method
❮ Math Methods Return the arc cosine of different numbers: System.out.println(Math.acos(0.64)); System.out.println(Math.acos(-0.4)); System.out.println(Math.acos(0)); System.out.println(Math.acos(1)); System.out.println(Math.acos(-1)); System.out.println(Math.acos(2)); Try it Yourself » The acos() method returns the arc cosine value of a number. Tip: acos(-1) returns the value of PI. public static double abs(double number) We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 17, "s": 0, "text": "\n❮ Math Methods\n" }, { "code": null, "e": 61, "s": 17, "text": "Return the arc cosine of different numbers:" }, { "code": null, "e": 273, "s": 61, "text": "System.out.println(Math.acos(0.64));\nSystem.out.println(Mat...
Difference between an Iterator and ListIterator in Java - GeeksforGeeks
17 Apr, 2019 Iterator Iterators are used in Collection framework in Java to retrieve elements one by one. It can be applied to any Collection object. By using Iterator, we can perform both read and remove operations. Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map interface. Iterator is the only cursor available for entire collection framework. Iterator object can be created by calling iterator() method present in Collection interface. // Here "c" is any Collection object. itr is of // type Iterator interface and refers to "c" Iterator itr = c.iterator(); ListIteratorIt is only applicable for List collection implemented classes like arraylist, linkedlist etc. It provides bi-directional iteration. ListIterator must be used when we want to enumerate elements of List. This cursor has more functionality(methods) than iterator. ListIterator object can be created by calling listIterator() method present in List interface. // Here "l" is any List object, ltr is of type // ListIterator interface and refers to "l" ListIterator ltr = l.listIterator(); Differences between Iterator and ListIterator: Iterator can traverse only in forward direction whereas ListIterator traverses both in forward and backward directions.Example:import java.io.*;import java.util.*; class IteratorDemo1 { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); // Iterator Iterator itr = list.iterator(); System.out.println("Iterator:"); System.out.println("Forward traversal: "); while (itr.hasNext()) System.out.print(itr.next() + " "); System.out.println(); // ListIterator ListIterator i = list.listIterator(); System.out.println("ListIterator:"); System.out.println("Forward Traversal : "); while (i.hasNext()) System.out.print(i.next() + " "); System.out.println(); System.out.println("Backward Traversal : "); while (i.hasPrevious()) System.out.print(i.previous() + " "); System.out.println(); }}Output:Iterator: Forward traversal: 1 2 3 4 5 ListIterator: Forward Traversal : 1 2 3 4 5 Backward Traversal : 5 4 3 2 1 ListIterator can help to replace an element whereas Iterator cannot.Example:import java.util.ArrayList;import java.util.ListIterator; public class ListIteratorDemo2 { public static void main(String[] args) { ArrayList<Integer> aList = new ArrayList<Integer>(); aList.add(1); aList.add(2); aList.add(3); aList.add(4); aList.add(5); System.out.println("Elements of ArrayList: "); for (Integer i : aList) { System.out.println(i); } ListIterator<Integer> l = aList.listIterator(); l.next(); l.set(80000); System.out.println("\nNow the ArrayList" + " elements are: "); for (Integer i : aList) { System.out.println(i); } }}Output:Elements of ArrayList: 1 2 3 4 5 Now the ArrayList elements are: 80000 2 3 4 5 OUTPUTTable showing Difference between Iterator and ListIteratorIteratorListIteratorCan traverse elements present in Collection only in the forward direction.Can traverse elements present in Collection both in forward and backward directions.Helps to traverse Map, List and Set.Can only traverse List and not the other two.Indexes cannot be obtained by using Iterator.It has methods like nextIndex() and previousIndex() to obtain indexes of elements at any time while traversing List.Cannot modify or replace elements present in CollectionWe can modify or replace elements with the help of set(E e)Cannot add elements and it throws ConcurrentModificationException.Can easily add elements to a collection at any time.Certain methods of Iterator are next(), remove() and hasNext().Certain methods of ListIterator are next(), previous(), hasNext(), hasPrevious(), add(E e).My Personal Notes arrow_drop_upSave Iterator can traverse only in forward direction whereas ListIterator traverses both in forward and backward directions.Example:import java.io.*;import java.util.*; class IteratorDemo1 { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); // Iterator Iterator itr = list.iterator(); System.out.println("Iterator:"); System.out.println("Forward traversal: "); while (itr.hasNext()) System.out.print(itr.next() + " "); System.out.println(); // ListIterator ListIterator i = list.listIterator(); System.out.println("ListIterator:"); System.out.println("Forward Traversal : "); while (i.hasNext()) System.out.print(i.next() + " "); System.out.println(); System.out.println("Backward Traversal : "); while (i.hasPrevious()) System.out.print(i.previous() + " "); System.out.println(); }}Output:Iterator: Forward traversal: 1 2 3 4 5 ListIterator: Forward Traversal : 1 2 3 4 5 Backward Traversal : 5 4 3 2 1 Example: import java.io.*;import java.util.*; class IteratorDemo1 { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); // Iterator Iterator itr = list.iterator(); System.out.println("Iterator:"); System.out.println("Forward traversal: "); while (itr.hasNext()) System.out.print(itr.next() + " "); System.out.println(); // ListIterator ListIterator i = list.listIterator(); System.out.println("ListIterator:"); System.out.println("Forward Traversal : "); while (i.hasNext()) System.out.print(i.next() + " "); System.out.println(); System.out.println("Backward Traversal : "); while (i.hasPrevious()) System.out.print(i.previous() + " "); System.out.println(); }} Iterator: Forward traversal: 1 2 3 4 5 ListIterator: Forward Traversal : 1 2 3 4 5 Backward Traversal : 5 4 3 2 1 ListIterator can help to replace an element whereas Iterator cannot.Example:import java.util.ArrayList;import java.util.ListIterator; public class ListIteratorDemo2 { public static void main(String[] args) { ArrayList<Integer> aList = new ArrayList<Integer>(); aList.add(1); aList.add(2); aList.add(3); aList.add(4); aList.add(5); System.out.println("Elements of ArrayList: "); for (Integer i : aList) { System.out.println(i); } ListIterator<Integer> l = aList.listIterator(); l.next(); l.set(80000); System.out.println("\nNow the ArrayList" + " elements are: "); for (Integer i : aList) { System.out.println(i); } }}Output:Elements of ArrayList: 1 2 3 4 5 Now the ArrayList elements are: 80000 2 3 4 5 OUTPUTTable showing Difference between Iterator and ListIteratorIteratorListIteratorCan traverse elements present in Collection only in the forward direction.Can traverse elements present in Collection both in forward and backward directions.Helps to traverse Map, List and Set.Can only traverse List and not the other two.Indexes cannot be obtained by using Iterator.It has methods like nextIndex() and previousIndex() to obtain indexes of elements at any time while traversing List.Cannot modify or replace elements present in CollectionWe can modify or replace elements with the help of set(E e)Cannot add elements and it throws ConcurrentModificationException.Can easily add elements to a collection at any time.Certain methods of Iterator are next(), remove() and hasNext().Certain methods of ListIterator are next(), previous(), hasNext(), hasPrevious(), add(E e).My Personal Notes arrow_drop_upSave Example: import java.util.ArrayList;import java.util.ListIterator; public class ListIteratorDemo2 { public static void main(String[] args) { ArrayList<Integer> aList = new ArrayList<Integer>(); aList.add(1); aList.add(2); aList.add(3); aList.add(4); aList.add(5); System.out.println("Elements of ArrayList: "); for (Integer i : aList) { System.out.println(i); } ListIterator<Integer> l = aList.listIterator(); l.next(); l.set(80000); System.out.println("\nNow the ArrayList" + " elements are: "); for (Integer i : aList) { System.out.println(i); } }} Elements of ArrayList: 1 2 3 4 5 Now the ArrayList elements are: 80000 2 3 4 5 OUTPUT Table showing Difference between Iterator and ListIterator Java-Iterator Picked Difference Between Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Stack vs Heap Memory Allocation Difference between Process and Thread Difference Between Method Overloading and Method Overriding in Java Difference between Clustered and Non-clustered index Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 24792, "s": 24764, "text": "\n17 Apr, 2019" }, { "code": null, "e": 24801, "s": 24792, "text": "Iterator" }, { "code": null, "e": 25262, "s": 24801, "text": "Iterators are used in Collection framework in Java to retrieve elements one by on...
PHP - Mysql GROUP BY HAVING Clause - GeeksforGeeks
16 Mar, 2021 Problem Statement :In this article, we are going to perform database operations with GROUP BY HAVING operation through PHP through xampp server. In this scenario, we are going to consider the food database. Requirements :xampp server Introduction :PHP is a server side scripting language that can communicate with Mysql web server through xampp tool. MySQL is a query language that can communicate with php through xampp. GROUP BY Clause –The GROUP BY Statement in database is an SQL which used to arrange identical data into groups by using aggregate operations like SUM(), MIN(), MAX() etc. Syntax – SELECT column1,column2,columnn, function_name(column2) FROM table_name WHERE condition GROUP BY column1, column2,columnn; GROUP BY HAVING Clause –Having Clause is just the aggregate function used with the GROUP BY clause. The HAVING clause is used instead of WHERE with aggregate functions. While the GROUP BY Clause groups rows that have the same values into summary rows. The having clause is used with the where clause in order to find rows with certain conditions. The having clause is always used after the group By clause. Syntax – SELECT column1,column2,columnn FROM table_name GROUP BY column_name HAVING aggregate_function(column_name) condition; Example Query:Consider the food database: Select food items with cost greater than 200 SELECT food_item from food GROUP BY(food_item) HAVING SUM(cost) > 200; Result: Item : cakes Item : chocoss Item : fry Item : milk Query: Food items with weight less than 100 SELECT food_item from food GROUP BY(food_item) HAVING SUM(weight)>100; Result: Item : cakes Approach: create database in xampp create table an insert records into it. write php code to perform group by having clause. Steps : Start the xampp server Create database named geek Create a table named food and insert records into it. Refer this for insert records into xampp : https://www.geeksforgeeks.org/performing-database-operations-in-xampp/ Your table will look like: table columns-structure PHP code (form.php) After typing this code run it in tour web browser by typing “localhost/form.php” PHP <?php // code?><html><body><?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//database is the database name$dbname = "geek"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo "<h1>"; echo "GROUP BY HAVING Demo "; echo"</h1>";echo "<br>";echo "food items with cost greater than 200";echo "<br>";echo "<br>";//sql query$sql = "SELECT food_item from food GROUP BY(food_item) HAVING SUM(cost)>200";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo " Item : ". $row['food_item']; echo "<br>"; } echo "<br>";echo "food items with weight less than than 100";echo "<br>";echo "<br>";//sql query$sql = "SELECT food_item from food GROUP BY(food_item) HAVING SUM(weight)>100";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo " Item : ". $row['food_item']; echo "<br>"; }//close the connection $conn->close();?></body></html> Output: Example-2: PHP code (form1.php) Display food items with average cost greater than 400 PHP <html><body><?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//database is the database name$dbname = "geek"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo "<h1>"; echo "GROUP BY HAVING Demo "; echo"</h1>";echo "<br>";echo "food items with average cost greater than 400";echo "<br>";echo "<br>";//sql query$sql = "SELECT food_item,food_id from food GROUP BY(food_item) HAVING AVG(cost)>400";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo " Item : ". $row['food_item'], " ---- Item id : ". $row['food_id']; echo "<br>"; } //close the connection $conn->close();?></body></html> Output: PHP PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? Different ways for passing data to view in Laravel Create a drop-down list that options fetched from a MySQL database in PHP How to generate PDF file using PHP ? How to create admin login page using PHP? PHP Cookies PHP | shell_exec() vs exec() Function PHP | Ternary Operator PHP str_replace() Function How to Install php-curl in Ubuntu ?
[ { "code": null, "e": 24972, "s": 24944, "text": "\n16 Mar, 2021" }, { "code": null, "e": 25118, "s": 24972, "text": "Problem Statement :In this article, we are going to perform database operations with GROUP BY HAVING operation through PHP through xampp server." }, { "co...
Angular Material - Toasts
The Angular Material provides various special methods to show unobtrusive alerts to the users. It also provides a term toast for them. The $mdToast service is used to show toasts. The following example shows the use of toasts. am_toasts.htm <html lang = "en"> <head> <link rel = "stylesheet" href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script> <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons"> <script language = "javascript"> angular .module('firstApplication', ['ngMaterial']) .controller('toastController', toastController); function toastController ($scope, $mdToast, $document) { $scope.showToast1 = function() { $mdToast.show ( $mdToast.simple() .textContent('Hello World!') .hideDelay(3000) ); }; $scope.showToast2 = function() { var toast = $mdToast.simple() .textContent('Hello World!') .action('OK') .highlightAction(false); $mdToast.show(toast).then(function(response) { if ( response == 'ok' ) { alert('You clicked \'OK\'.'); } }); } } </script> </head> <body ng-app = "firstApplication"> <div id = "toastContainer" ng-controller = "toastController as ctrl" layout = "row" ng-cloak> <md-button ng-click = "showToast1()">Show Simple Alert</md-button> <md-button ng-click = "showToast2()">Show Alert with callback</md-button> </div> </body> </html> Verify the result. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2370, "s": 2190, "text": "The Angular Material provides various special methods to show unobtrusive alerts to the users. It also provides a term toast for them. The $mdToast service is used to show toasts." }, { "code": null, "e": 2417, "s": 2370, "text": "Th...
ByteBuffer allocate() method in Java with Examples - GeeksforGeeks
25 Jul, 2019 The allocate() method of java.nio.ByteBuffer class is used to allocate a new byte buffer. The new buffer’s position will be zero, its limit will be its capacity, its mark will be undefined, and each of its elements will be initialized to zero. It will have a backing array, and its array offset will be zero. Syntax : public static ByteBuffer allocate(int capacity) Parameters: This method takes capacity, in bytes as parameter. Return Value: This method returns the new byte buffer . Throws: This method throws IllegalArgumentException, If the capacity is a negative integer Below are the examples to illustrate the allocate() method: Examples 1: // Java program to demonstrate// allocate() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value // in ByteBuffer using putInt() method bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.put((byte)50); bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: " + Arrays.toString(bb.array())); } catch (IllegalArgumentException e) { System.out.println("IllegalArgumentException catched"); } catch (ReadOnlyBufferException e) { System.out.println("ReadOnlyBufferException catched"); } }} Original ByteBuffer: [20, 30, 40, 50] Examples 2: // Java program to demonstrate// allocate() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity with negative // value of the ByteBuffer int capacity = -4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity System.out.println("Trying to allocate negative"+ " value in ByteBuffer"); ByteBuffer bb = ByteBuffer.allocate(capacity); // putting int to byte typecast value // in ByteBuffer using putInt() method bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.put((byte)50); bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: " + Arrays.toString(bb.array())); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception thrown : " + e); } }} Trying to allocate negative value in ByteBuffer Exception thrown : java.lang.IllegalArgumentException nidhi_biet Java-ByteBuffer Java-Functions Java-NIO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Stream In Java Singleton Class in Java
[ { "code": null, "e": 24594, "s": 24566, "text": "\n25 Jul, 2019" }, { "code": null, "e": 24684, "s": 24594, "text": "The allocate() method of java.nio.ByteBuffer class is used to allocate a new byte buffer." }, { "code": null, "e": 24903, "s": 24684, "text": "...
Text Validations in Cypress
Cypress can validate the text on an element with the help of jQuery text() method. This method shall help us to fetch the text content on the selected element. We can also put assertions on the text content of the element. cy.get('.product').should('have.text', 'Tutorialspoint'); We can do validations on the text like verify what it contains or matches with the help of the Javascript methods match(), include() and so on. Thus Cypress commands can work on non-Cypress methods with the help of jQuery objects and invoke methods on them. Code Implementation with the text() method. // test suite describe('Tutorialspoint Test', function () { // test case it('Test Case1', function (){ // test step to launch a URL cy.visit("https://www.tutorialspoint.com/index.htm"); // enter test in the edit box // assertion to validate the number of child elements cy.get('#gs_50d > tbody > tr > td'). should('have.length',2); // locate element with get and find method cy.get('#gs_50d > tbody > tr > td'). find('input') //enter test in the edit box .type('Cypress'); //iterate the list items with each command cy.get('.mui-tabs__bar.mui-tabs__bar_1.mui-tabs__bar--justified) .find('li').each(($el, index, $list) => { // extract text with text() method const txt = $el.find('a').text(); if ( txt.includes('Deve')){ $el.click(); } }) }); }); On running the above block of code, Cypress Test runner gives the below output −
[ { "code": null, "e": 1285, "s": 1062, "text": "Cypress can validate the text on an element with the help of jQuery text() method.\nThis method shall help us to fetch the text content on the selected element. We\ncan also put assertions on the text content of the element." }, { "code": null, ...
MongoDB and Python
MongoDB is a widely used document database which is also a form of NoSQL DB. Python can interact with MongoDB through some python modules and create and manipulate data inside Mongo DB. In this article we will learn to do that. But MongoDB should already be available in your system before python can connect to it and run. To setup MongoDB in your system please visit our MongoDB tutorial here.. To interact with MongoDB we need the module names pymongo. Install it in your python environment using the below command. pip install pymogo We now use this python module to check for any existing DB. The below python program connects to the MongoDB service and gives a output of the list of DB names available. import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") print(myclient.list_database_names()) Running the above code gives us the following result − ['Mymdb', 'admin', 'config', 'local'] A collection is similar to a table in traditional rdbms. We can next check for collections present in a specific database using the below python program. import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mndb = myclient["Mymdb"] print(mndb.list_collection_names()) Running the above code gives us the following result − ['newmongocoll'] The document in MongoDB is also comparable to a row in traditional RDBMS. In this program we see how to insert a document to MongoDB using a python program. First we connect to the DB and collections and then use a dictionary to put values of the document into the collection. import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mndb = myclient["Mymdb"] mycol = mndb['newmongocoll'] mydict = { "ID": "2", "Name": "Ramana" } x = mycol.insert_one(mydict) print(x) Running the above code gives us the following result − <pymongo.results.InsertOneResult object at 0x000002CA92A920C0> We can also query for documents present in MongoDB using find method available in pymongo. import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mndb = myclient["Mymdb"] mycol = mndb['newmongocoll'] for x in mycol.find(): print(x) Running the above code gives us the following result − {'_id': ObjectId('5ef8b6f92d192421b78d32cb'), 'ID': '2', 'Name': 'Ramana'}
[ { "code": null, "e": 1460, "s": 1062, "text": "MongoDB is a widely used document database which is also a form of NoSQL DB. Python can interact with MongoDB through some python modules and create and manipulate data inside Mongo DB. In this article we will learn to do that. But MongoDB should alread...
How to handle authentication popup with Selenium WebDriver using Java?
We can handle authentication popup with Selenium. To do this, we have to pass the user credentials within the URL. We shall have to add the username and password to the URL. https://username:password@URL https://admin:admin@the−nternet.herokuapp.com/basic_auth Here, the admin is the username and password. URL − www.the-internet.herokuapp.com/basic_auth Let us work and accept the below authentication popup. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class AuthnPopup{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String u = "admin"; // adding username, password with URL String str = "https://" + u + ":" + u + "@" + "the-internet.herokuapp.com/basic_auth"; driver.get(str); // identify and get text after authentication of popup String t = driver.findElement(By.cssSelector("p")).getText(); System.out.println("Text is: " + t); driver.quit(); } }
[ { "code": null, "e": 1236, "s": 1062, "text": "We can handle authentication popup with Selenium. To do this, we have to pass the user credentials within the URL. We shall have to add the username and password to the URL." }, { "code": null, "e": 1417, "s": 1236, "text": "https://...
Pascal - Procedures
Procedures are subprograms that, instead of returning a single value, allow to obtain a group of results. In Pascal, a procedure is defined using the procedure keyword. The general form of a procedure definition is as follows − procedure name(argument(s): type1, argument(s): type 2, ... ); < local declarations > begin < procedure body > end; A procedure definition in Pascal consists of a header, local declarations and a body of the procedure. The procedure header consists of the keyword procedure and a name given to the procedure. Here are all the parts of a procedure − Arguments − The argument(s) establish the linkage between the calling program and the procedure identifiers and also called the formal parameters. Rules for arguments in procedures are same as that for the functions. Arguments − The argument(s) establish the linkage between the calling program and the procedure identifiers and also called the formal parameters. Rules for arguments in procedures are same as that for the functions. Local declarations − Local declarations refer to the declarations for labels, constants, variables, functions and procedures, which are applicable to the body of the procedure only. Local declarations − Local declarations refer to the declarations for labels, constants, variables, functions and procedures, which are applicable to the body of the procedure only. Procedure Body − The procedure body contains a collection of statements that define what the procedure does. It should always be enclosed between the reserved words begin and end. It is the part of a procedure where all computations are done. Procedure Body − The procedure body contains a collection of statements that define what the procedure does. It should always be enclosed between the reserved words begin and end. It is the part of a procedure where all computations are done. Following is the source code for a procedure called findMin(). This procedure takes 4 parameters x, y, z and m and stores the minimum among the first three variables in the variable named m. The variable m is passed by reference (we will discuss passing arguments by reference a little later) − procedure findMin(x, y, z: integer; var m: integer); (* Finds the minimum of the 3 values *) begin if x < y then m := x else m := y; if z <m then m := z; end; { end of procedure findMin } A procedure declaration tells the compiler about a procedure name and how to call the procedure. The actual body of the procedure can be defined separately. A procedure declaration has the following syntax − procedure name(argument(s): type1, argument(s): type 2, ... ); Please note that the name of the procedure is not associated with any type. For the above defined procedure findMin(), following is the declaration − procedure findMin(x, y, z: integer; var m: integer); While creating a procedure, you give a definition of what the procedure has to do. To use the procedure, you will have to call that procedure to perform the defined task. When a program calls a procedure, program control is transferred to the called procedure. A called procedure performs the defined task, and when its last end statement is reached, it returns the control back to the calling program. To call a procedure, you simply need to pass the required parameters along with the procedure name as shown below − program exProcedure; var a, b, c, min: integer; procedure findMin(x, y, z: integer; var m: integer); (* Finds the minimum of the 3 values *) begin if x < y then m:= x else m:= y; if z < m then m:= z; end; { end of procedure findMin } begin writeln(' Enter three numbers: '); readln( a, b, c); findMin(a, b, c, min); (* Procedure call *) writeln(' Minimum: ', min); end. When the above code is compiled and executed, it produces the following result − Enter three numbers: 89 45 67 Minimum: 45 We have seen that a program or subprogram may call another subprogram. When a subprogram calls itself, it is referred to as a recursive call and the process is known as recursion. To illustrate the concept, let us calculate the factorial of a number. Factorial of a number n is defined as − n! = n*(n-1)! = n*(n-1)*(n-2)! ... = n*(n-1)*(n-2)*(n-3)... 1 The following program calculates the factorial of a given number by calling itself recursively. program exRecursion; var num, f: integer; function fact(x: integer): integer; (* calculates factorial of x - x! *) begin if x=0 then fact := 1 else fact := x * fact(x-1); (* recursive call *) end; { end of function fact} begin writeln(' Enter a number: '); readln(num); f := fact(num); writeln(' Factorial ', num, ' is: ' , f); end. When the above code is compiled and executed, it produces the following result − Enter a number: 5 Factorial 5 is: 120 Following is another example, which generates the Fibonacci Series for a given number using a recursive function − program recursiveFibonacci; var i: integer; function fibonacci(n: integer): integer; begin if n=1 then fibonacci := 0 else if n=2 then fibonacci := 1 else fibonacci := fibonacci(n-1) + fibonacci(n-2); end; begin for i:= 1 to 10 do write(fibonacci (i), ' '); end. When the above code is compiled and executed, it produces the following result − 0 1 1 2 3 5 8 13 21 34 If a subprogram (function or procedure) is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the subprogram. The formal parameters behave like other local variables inside the subprogram and are created upon entry into the subprogram and destroyed upon exit. While calling a subprogram, there are two ways that arguments can be passed to the subprogram − This method copies the actual value of an argument into the formal parameter of the subprogram. In this case, changes made to the parameter inside the subprogram have no effect on the argument. This method copies the address of an argument into the formal parameter. Inside the subprogram, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. By default, Pascal uses call by value to pass arguments. In general, this means that code within a subprogram cannot alter the arguments used to call the subprogram. The example program we used in the chapter 'Pascal - Functions' called the function named max() using call by value. Whereas, the example program provided here (exProcedure) calls the procedure findMin() using call by reference. 94 Lectures 8.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2189, "s": 2083, "text": "Procedures are subprograms that, instead of returning a single value, allow to obtain a group of results." }, { "code": null, "e": 2311, "s": 2189, "text": "In Pascal, a procedure is defined using the procedure keyword. The general f...
Operations on table in Cassandra - GeeksforGeeks
31 Dec, 2019 In this article, we will discuss table operations like Create insert truncate drop in Cassandra with some sample exercise. Let’s have a look. Creating a table – Register:First, we are going to create a table namely as Register in which we have id, name, email, city are the fields. Let’s have a look. Create table Register ( id uuid primary key, name text, email text, city text ); Inserting data into Register table:After creating a table now, we are going to insert some data into Register table. Let’s have a look. Insert into Register (id, name, email, city) values(uuid(), 'Ashish', 'ashish05.rana05@gmail.com', 'delhi'); Insert into Register (id, name, email, city) values(uuid(), 'abi', 'abc@gmail.com', 'mumbai'); Insert into Register (id, name, email, city) values(uuid(), 'rana', 'def@gmail.com', 'bangalore'); Verify the results:To verify the results using the following CQL query given below. Let’s have a look. select * from Register; Describe the table schema: describe table Register; CREATE TABLE cluster1.register ( id uuid, city text, email text, name text, PRIMARY KEY (id) ) WITH read_repair_chance = 0.0 AND dclocal_read_repair_chance = 0.0 AND gc_grace_seconds = 864000 AND bloom_filter_fp_chance = 0.01 AND caching = { 'keys' : 'ALL', 'rows_per_partition' : 'NONE' } AND comment = '' AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold' : 32, 'min_threshold' : 4 } AND compression = { 'chunk_length_in_kb' : 64, 'class' : 'org.apache.cassandra.io.compress.LZ4Compressor' } AND default_time_to_live = 0 AND speculative_retry = '99PERCENTILE' AND min_index_interval = 128 AND max_index_interval = 2048 AND crc_check_chance = 1.0 AND cdc = false AND memtable_flush_period_in_ms = 0; Updating the table:To update the table used the following CQL query given below. update Register set email = 'abe@gmail.com' where id = 57280025-1261-44ab-85d4-62ab2c58a1c1; Verifying after updating the table:Let’s verify the results by using the following CQL query given below. select * from Register; Output: Alter operation on a table:To alter the table used the following CQL query given below. ALTER table Register add events text; To see the update used the following CQL query given below. describe table Register; Output: CREATE TABLE cluster1.register ( id uuid, city text, email text, events text, name text, PRIMARY KEY (id) ) WITH read_repair_chance = 0.0 AND dclocal_read_repair_chance = 0.0 AND gc_grace_seconds = 864000 AND bloom_filter_fp_chance = 0.01 AND caching = { 'keys' : 'ALL', 'rows_per_partition' : 'NONE' } AND comment = '' AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold' : 32, 'min_threshold' : 4 } AND compression = { 'chunk_length_in_kb' : 64, 'class' : 'org.apache.cassandra.io.compress.LZ4Compressor' } AND default_time_to_live = 0 AND speculative_retry = '99PERCENTILE' AND min_index_interval = 128 AND max_index_interval = 2048 AND crc_check_chance = 1.0 AND cdc = false AND memtable_flush_period_in_ms = 0; Verifying the newly added column:To verify the newly added column used the following CQL query given below. select * from Register; Output: Inserting data into the new added column: Insert into Register (id, name, email, city, events) values(uuid(), 'Ashish', 'ashish05.rana05@gmail.com', 'delhi', 'game'); To verify inserted data to the newly added column used the following CQL query given below. select * from Register; Output: Deleting data from table Register:To delete data from table Register used the following CQL query. Let’s have a look. truncate Register; Delete a table:To delete table schema and data from table Register used the following CQL query. Let’s have a look. drop table Register; Apache BigData DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction of B-Tree Difference between Clustered and Non-clustered index Introduction of ER Model Introduction of DBMS (Database Management System) | Set 1 SQL | Views CTE in SQL SQL Interview Questions Third Normal Form (3NF) Difference between Primary Key and Foreign Key SQL | GROUP BY
[ { "code": null, "e": 23950, "s": 23922, "text": "\n31 Dec, 2019" }, { "code": null, "e": 24092, "s": 23950, "text": "In this article, we will discuss table operations like Create insert truncate drop in Cassandra with some sample exercise. Let’s have a look." }, { "code":...
Tutorial: Scrape 100 Headlines in Seconds With 23 Lines of Python | by Jack Bandy | Towards Data Science
If you need to do any kind of web scraping, Scrapy is almost impossible to pass up. With built-in features such as parallel requests, user agent spoofing, robots.txt policies, and more, you can build a powerful web scraper with just a few lines of code. In this tutorial, I will show how to create a basic Scrapy Spider that collects headlines from news articles. On most websites, you can do this without worrying about paywalls, bot detection, or weird parsing tricks, so I will leave those worries for another tutorial. Here is a file with 100 random urls, from a dataset I have been collecting from NewsAPI. The first few lines look like this: We will use three open-source libraries (and their dependencies): Pandas, Scrapy, and Readability. Assuming you already have pip installed, you can ensure your computer has these by running the following command in your terminal: pip install scrapy pandas readability-lxml Then, make the folder where you want to organize the project and navigate to it: mkdir headline_scrapercd headline_scraper Now, we can create the spider. Scrapy has a startproject command that sets up a whole project, but I have found that can be bloated. We’ll keep it simple by making our own spider which, as promised, comes in at just 23 lines (including comments and whitespace 🙂). These are the contents of a file titled headline_scraper.py : Unlike a normal python script, we need to use scrapy’s runspider command to run the file. Choose where to save the output using the -o flag: scrapy runspider headline_scraper.py -o scraped_headlines.csv That’s everything! Below is an explanation of what’s going on in the code. Besides importing libraries and declaring PATH_TO_DATA(a link to the gist where the 100 urls are stored), here is what the initial lines are doing: class HeadlineSpider(scrapy.Spider) makes a new kind of class, “HeadlineSpider,” that inherits the base functionality of scrapy Spiders name="headline_spider" names the new Spider “headline_spider,” for Scrapy’s reference start_urls=read_csv(PATH_TO_DATA).url.tolist() uses the csv reader from pandas to download the file with 100 urls, then gets the “url” column and turns it into a python list. start_urls are needed for any spider, but in this case, they are the only urls that will be visited. (If you want to use a different file with your own urls, simply replace PATH_TO_DATA with the location of your file. Then, either make sure the column of urls is labeled “url,” or replace .url with .name_of_your_column It can be on your machine, i.e., PATH_TO_DATA=/Users/Jack/Desktop/file.csv ) Now that we have initialized the spider, we need to tell it what to actually do when it gets to a web page. To actually extract the headline, we must implement the parse method. Scrapy automatically sends the http response to this method whenever it retrieves a url from the list of start_urls , then it is totally up to you what to do with it. Here’s what this version does: doc=Document(response.text)this line uses readability’s functionality to parse through the html. You could also use alternative libraries, such as BeautifulSoup or Newspaper, for this part. yield is essentially a return method that creates the output, which you can think of as a row in the resulting spreadsheet. 'short_title':doc.short_title() and the lines below it simply set different attributes of the return object. You can think of 'short_title' as a column in the resulting spreadsheet, and the contents will be the output of doc.short_title() (for example, “How the coronavirus outbreak is affecting the global economy”) Again, this part is very customizable. If you wanted to try getting the full text of the article, just change the yield lines to include doc.summary() as follows. yield { 'full_text': doc.summary(), 'short_title': doc.short_title(), 'full_title': doc.title(), 'url': response.url} This will make an additional column calledfull_text in the resulting .csv file, with readability’s best attempt at extracting the article text. Here is the output file from runningscrapy runspider headline_scraper.py -o scraped_headlines.csv: Boom! Well, at least for the most part. Scrapy is very error tolerant out of the box, so only 95/100 urls came back. The 5 that didn’t come back encountered some kind of http error, like the 404 error you sometimes see browsing the web. Additionally, some rows (7 by my count) say “warning” and “Are you a robot?” rather than providing actual headline. (Bloomberg seems to have very effective bot detection.) There are many strategies to deal with bot detection, some of which are already implemented in Scrapy. Let me know if you are interested, and I can cover those strategies in a future tutorial. If you have any questions, comments, or issues with the code, feel free to reach out by responding to this post or messaging me on Twitter. Thanks!
[ { "code": null, "e": 301, "s": 47, "text": "If you need to do any kind of web scraping, Scrapy is almost impossible to pass up. With built-in features such as parallel requests, user agent spoofing, robots.txt policies, and more, you can build a powerful web scraper with just a few lines of code." ...
React.js Component Lifecycle - Unmounting
ComponentWillUnmount is the only method that executes in unmount phase. Component enters into this phase when there is no matching in element tree for this component. Just before the component gets removed from actual DOM, this method gets called. Along with removal of this component from DOM tree, all children of this component also gets removed automatically. Once component is removed from the DOM, it gets available for the garbage collection in React. Cleanup activities can be done in this method. E.g. clear localstorage variables used in app, clear session, clean up charts, cleanup timers, cancel pending api requests etc. componentWillUnmount(){ this.resetSession(); //example method to clean data } Cleanup activities helps in improving performances, memory leakages and maintain security. In latest release 16.4 +, three methods are marked as deprecated and renamed as well. These methods will be removed in next major release of React.jscomponentWillReceiveProps changed to UNSAFE_componentWillReceiveProps . This method is implemented securely and statically with name getDerivedStateFromPropscomponentWillMount changed to UNSAFE_componentWillMount. Code from this method should be moved to componentDidMount or constructor as per logic.componentWillUpdate changed to UNSAFE_componentWillUpdate. Secure implementation is getSnapshotBeforeUpdate. If there is any value returned from this method then it will used as an argument in the next method i.e. componentDidUpdate.If user closes browser then the componentWiIlUnmount will not complete.componentWillUnmount does not have any argument. setState shold not be called from this method. This is a one-time call for the component. Purpose of this method is to destroy the side effects created by the component.Once component is unmounted, we can’t use it again. Every time a new component gets created.Also if there is no difference in virtual dom and actual dom, react can stop the update phase as well. componentWillReceiveProps changed to UNSAFE_componentWillReceiveProps . This method is implemented securely and statically with name getDerivedStateFromProps componentWillMount changed to UNSAFE_componentWillMount. Code from this method should be moved to componentDidMount or constructor as per logic. componentWillUpdate changed to UNSAFE_componentWillUpdate. Secure implementation is getSnapshotBeforeUpdate. If there is any value returned from this method then it will used as an argument in the next method i.e. componentDidUpdate. If user closes browser then the componentWiIlUnmount will not complete. componentWillUnmount does not have any argument. setState shold not be called from this method. This is a one-time call for the component. Purpose of this method is to destroy the side effects created by the component. Once component is unmounted, we can’t use it again. Every time a new component gets created. Also if there is no difference in virtual dom and actual dom, react can stop the update phase as well.
[ { "code": null, "e": 1134, "s": 1062, "text": "ComponentWillUnmount is the only method that executes in unmount phase." }, { "code": null, "e": 1229, "s": 1134, "text": "Component enters into this phase when there is no matching in element tree for this component." }, { "...
How to adjust Space Between ggplot2 Axis Labels and Plot Area in R ? - GeeksforGeeks
21 Apr, 2021 While plotting the graphs we can make different changes in order to make them much more appealing and clear to the observer. One of the ways is to adjust the spacing between the labels and plot area. In this article, we will study how to adjust space between ggplot2 Axis Labels and plot area in R Programming Language. To add customizations to our plot we can use the theme() function. To adjust the vertical spacing we use vjust in the element_text function to vertically adjust the plotting Example R rm(list=ls()) data <- data.frame(name = c("Aditya", "Ritika", "Pulkit", "Vishesh", "Kaif"), marks = c(58, 82, 79, 42, 66)) library("ggplot2") ggp <- ggplot(data, aes(name, marks, fill = name)) + geom_bar(stat = "identity") ggp + theme(axis.text.x = element_text(vjust = -12)) Output: vertically adjusted plot We can adjust the horizontal spacing in the similar way using hjust in element_text Example R rm(list=ls()) data <- data.frame(Name = c("Aditya", "Ritika", "Pulkit", "Vishesh", "Kaif"), Marks = c(58, 82, 79, 42, 66)) library("ggplot2") ggp <- ggplot(data, aes(Name, Marks, fill = Name)) + geom_bar(stat = "identity") ggp + theme(axis.text.x = element_text(hjust = -1)) Output: horizontally adjusted plot Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R Data Visualization in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr Logistic Regression in R Programming How to Split Column Into Multiple Columns in R DataFrame? Control Statements in R Programming How to import an Excel File into R ? Replace Specific Characters in String in R How to filter R DataFrame by values in a column?
[ { "code": null, "e": 25162, "s": 25134, "text": "\n21 Apr, 2021" }, { "code": null, "e": 25482, "s": 25162, "text": "While plotting the graphs we can make different changes in order to make them much more appealing and clear to the observer. One of the ways is to adjust the spaci...
Tryit Editor v3.7
Tryit: Template 1 - using float
[]
Tryit Editor v3.6 - Show Node.js Command Prompt
var mysql = require('mysql'); ​ var con = mysql.createConnection({ host: "localhost", user: "myusername", password: "mypassword", database: "mydb" }); ​ con.connect(function(err) { if (err) throw err;
[ { "code": null, "e": 30, "s": 0, "text": "var mysql = require('mysql');" }, { "code": null, "e": 32, "s": 30, "text": "​" }, { "code": null, "e": 67, "s": 32, "text": "var con = mysql.createConnection({" }, { "code": null, "e": 88, "s": 67, ...
Traverse Through a HashMap in Java - GeeksforGeeks
06 Jan, 2022 HashMap stores the data in (Key, Value) pairs, and you can access them by an index of another type. HashMap class implements Map interface which allows us to store key. hashMap is a part of the java collections framework been up since Java 1.2. It internally uses hashing technique which is pretty fast. Syntax: public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Clonnable, Serial We can iterate over mapping that is key and value pairs a was listed below that are later described as follows: Methods: Using an IteratorUsing enhanced for Loop (for-each loop)Using forEach() Method Using an Iterator Using enhanced for Loop (for-each loop) Using forEach() Method Method 1: Using an Iterator Iterator is an interface in java.util package which is used to iterate through a collection. As such there is nothing special to discuss iterators so do we will be proposing out methods of Iterator interface been used to traverse over HashMap. hm.entrySet() is used to retrieve all the key-value pairs called Map.Entries and stores internally into a set. hm.entrySet().iterator() returns an iterator that acts as a cursor and points at the first element of the set and moves on till the end. hmIterator.hasNext() checks for the next element in the set and returns a boolean hmIterator.next() returns the next element(Map.Entry) from the set. mapElement.getKey() returns the key of the associated Map.Entry mapElement.getValue() return the value of the associated Map.Entry Example: Java // Java Program to Traverse through HashMap// Using Iterator // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an Hashmap of string-integer pairs // It contains student name and their marks HashMap<String, Integer> hm = new HashMap<String, Integer>(); // Adding mappings to above HashMap // using put() method hm.put("GeeksforGeeks", 54); hm.put("A computer portal", 80); hm.put("For geeks", 82); // Printing all elements of HashMap System.out.println("Created hashmap is" + hm); // Getting an iterator Iterator hmIterator = hm.entrySet().iterator(); // Display message only System.out.println( "HashMap after adding bonus marks:"); // Iterating through Hashmap and // adding some bonus marks for every student while (hmIterator.hasNext()) { Map.Entry mapElement = (Map.Entry)hmIterator.next(); int marks = ((int)mapElement.getValue() + 10); // Printing mark corresponding to string entries System.out.println(mapElement.getKey() + " : " + marks); } }} Created hashmap is{GeeksforGeeks=54, A computer portal=80, For geeks=82} HashMap after adding bonus marks: GeeksforGeeks : 64 A computer portal : 90 For geeks : 92 Method 2: Using for-each Loop Example: Java // Java program for Traversing through HashMap// Using for-each Loop // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // creating an empty HashMap of string and integer // pairs Mappings denotes Student name and marks HashMap<String, Integer> hm = new HashMap<String, Integer>(); // Adding mappings to HashMap // using put() method hm.put("GeeksforGeeks", 54); hm.put("A computer portal", 80); hm.put("For geeks", 82); // Printing all elements of above Map System.out.println("Created hashmap is" + hm); // Display message only System.out.println( "HashMap after adding bonus marks:"); // Looping through the HashMap // Using for-each loop for (Map.Entry mapElement : hm.entrySet()) { String key = (String)mapElement.getKey(); // Adding some bonus marks to all the students int value = ((int)mapElement.getValue() + 10); // Printing above marks corresponding to // students names System.out.println(key + " : " + value); } }} Created hashmap is{GeeksforGeeks=54, A computer portal=80, For geeks=82} HashMap after adding bonus marks: GeeksforGeeks : 64 A computer portal : 90 For geeks : 92 Method 3: Using forEach() method forEach() is a method of HashMap that is introduced in java 8. It is used to iterate through the hashmap and also reduces the number of lines of code as proposed below as follows: Example: Java // Java program for traversing Through HashMap// Using forEach() Method // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty HashMap of string-integer // pairs HashMap<String, Integer> hm = new HashMap<String, Integer>(); // Adding mappings to HashMap // using put() method hm.put("GeeksforGeeks", 54); hm.put("A computer portal", 80); hm.put("For geeks", 82); // Printing all elements of above HashMap System.out.println("Created hashmap is" + hm); // Display message only System.out.println( "HashMap after adding bonus marks:"); // Looping through HashMap and adding bonus marks // using HashMap.forEach() hm.forEach((k, v) -> System.out.println(k + " : " + (v + 10))); }} Created hashmap is{GeeksforGeeks=54, A computer portal=80, For geeks=82} HashMap after adding bonus marks: GeeksforGeeks : 64 A computer portal : 90 For geeks : 92 solankimayank surindertarika1234 gulshankumarar231 surinderdawra388 Java - util package Java 8 Java-HashMap Java-Iterator Java-Map-Programs Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Initializing a List in Java Convert a String to Character array in Java Java Programming Examples Implementing a Linked List in Java using Class Convert Double to Integer in Java
[ { "code": null, "e": 24574, "s": 24546, "text": "\n06 Jan, 2022" }, { "code": null, "e": 24878, "s": 24574, "text": "HashMap stores the data in (Key, Value) pairs, and you can access them by an index of another type. HashMap class implements Map interface which allows us to store...
Git Commit
Since we have finished our work, we are ready move from stage to commit for our repo. Adding commits keep track of our progress and changes as we work. Git considers each commit change point or "save point". It is a point in the project you can go back to if you find a bug, or want to make a change. When we commit, we should always include a message. By adding clear messages to each commit, it is easy for yourself (and others) to see what has changed and when. git commit -m "First release of Hello World!" [master (root-commit) 221ec6e] First release of Hello World! 3 files changed, 26 insertions(+) create mode 100644 README.md create mode 100644 bluestyle.css create mode 100644 index.html The commit command performs a commit, and the -m "message" adds a message. The Staging Environment has been committed to our repo, with the message:"First release of Hello World!" Sometimes, when you make small changes, using the staging environment seems like a waste of time. It is possible to commit changes directly, skipping the staging environment. The -a option will automatically stage every changed, already tracked file. Let's add a small update to index.html: And check the status of our repository. But this time, we will use the --short option to see the changes in a more compact way: git status --short M index.html Note: Short status flags are: ?? - Untracked files A - Files added to stage M - Modified files D - Deleted files We see the file we expected is modified. So let's commit it directly: git commit -a -m "Updated index.html with a new line" [master 09f4acd] Updated index.html with a new line 1 file changed, 1 insertion(+) Warning: Skipping the Staging Environment is not generally recommended. Skipping the stage step can sometimes make you include unwanted changes. To view the history of commits for a repository, you can use the log command: git log commit 09f4acd3f8836b7f6fc44ad9e012f82faf861803 (HEAD -> master) Author: w3schools-test Date: Fri Mar 26 09:35:54 2021 +0100 Updated index.html with a new line commit 221ec6e10aeedbfd02b85264087cd9adc18e4b26 Author: w3schools-test Date: Fri Mar 26 09:13:07 2021 +0100 First release of Hello World! Commit the changes to the current repository with the message "First release! git "First release!" Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 89, "s": 0, "text": "Since we have finished our work, \nwe are ready move from stage to commit \nfor our repo." }, { "code": null, "e": 306, "s": 89, "text": "Adding commits keep track of our progress and changes as we work. Git \nconsiders each commit chang...
Make a star shape with HTML5 SVG
Here is the HTML5 version of an SVG example that would draw a star using the <polygon> tag. <html> <head> <style> #svgelem{ position: relative; left: 50%; -webkit-transform: translateX(-40%); -ms-transform: translateX(-40%); transform: translateX(-40%); } </style> <title>SVG</title> <meta charset="utf-8" /> </head> <body> <h2 align = "center">HTML5 SVG Star</h2> <svg id = "svgelem" height = "200" xmlns = "http://www.w3.org/2000/svg"> <polygon points = "100,10 40,180 190,60 10,60 160,180" fill = "red"/> </svg> </body> </html>
[ { "code": null, "e": 1154, "s": 1062, "text": "Here is the HTML5 version of an SVG example that would draw a star using the <polygon> tag." }, { "code": null, "e": 1731, "s": 1154, "text": "<html>\n <head>\n <style>\n #svgelem{\n position: relative;\n ...
LongStream limit() in Java - GeeksforGeeks
06 Dec, 2018 LongStream limit(long maxSize) returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length. Note : LongStream limit() is a short-circuiting stateful intermediate operation i.e, when processed with an infinite input, it may produce a finite stream as a result without processing the entire input. Syntax : LongStream limit(long maxSize) Parameters : LongStream : A sequence of primitive long-valued elements. This is the long primitive specialization of Stream.maxSize : The number of elements the stream should be limited to. LongStream : A sequence of primitive long-valued elements. This is the long primitive specialization of Stream. maxSize : The number of elements the stream should be limited to. Return Value : The function returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length. Exception : The function throws IllegalArgumentException if maxSize is negative. Example 1 : // Java code for LongStream limit// (long maxSize)import java.util.*;import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Creating an LongStream LongStream stream = LongStream.of(2L, 4L, 6L, 8L, 10L); // Using LongStream limit(long maxSize) to // get a stream consisting of the elements of // this stream, truncated to be no longer // than maxSize in length. stream.limit(3).forEach(System.out::println); }} Output : 2 4 6 Example 2 : // Java code for LongStream limit// (long maxSize)import java.util.*;import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Creating an LongStream of numbers [5, 6, .. 11] LongStream stream = LongStream.range(5, 12); // Using LongStream limit(long maxSize) to // get a stream consisting of the elements of // this stream, truncated to be no longer // than maxSize in length. stream.limit(4).forEach(System.out::println); }} Output : 5 6 7 8 Example 3 : // Java code for LongStream limit// (long maxSize)import java.util.*;import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Creating an LongStream LongStream stream = LongStream.iterate(4L, num -> num + 2); // Using LongStream limit(long maxSize) to // get a stream consisting of the elements of // this stream, truncated to be no longer // than maxSize in length. stream.limit(4).forEach(System.out::println); }} Output : 4 6 8 10 Difference between LongStream limit() and LongStream skip() : The limit() method returns a reduced stream of first maxSize elements but skip() method returns a stream of remaining elements after skipping first maxSize elements.limit() is a short-circuiting stateful intermediate operation i.e, when processed with an infinite input, it may produce a finite stream as a result without processing the entire input but skip() is a stateful intermediate operation i.e, it may need to process the entire input before producing a result. The limit() method returns a reduced stream of first maxSize elements but skip() method returns a stream of remaining elements after skipping first maxSize elements. limit() is a short-circuiting stateful intermediate operation i.e, when processed with an infinite input, it may produce a finite stream as a result without processing the entire input but skip() is a stateful intermediate operation i.e, it may need to process the entire input before producing a result. Java - util package Java-Functions java-longstream java-stream Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Interfaces in Java Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Overriding in Java Stack Class in Java Collections in Java
[ { "code": null, "e": 24114, "s": 24086, "text": "\n06 Dec, 2018" }, { "code": null, "e": 24255, "s": 24114, "text": "LongStream limit(long maxSize) returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length." }, { "code": ...
The search Function in Python
This function searches for first occurrence of RE pattern within string with optional flags. Here is the syntax for this function − re.search(pattern, string, flags=0) Here is the description of the parameters − The re.search function returns a match object on success, none on failure. We use group(num) or groups() function of match object to get matched expression. Live Demo #!/usr/bin/python import re line = "Cats are smarter than dogs"; searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I) if searchObj: print "searchObj.group() : ", searchObj.group() print "searchObj.group(1) : ", searchObj.group(1) print "searchObj.group(2) : ", searchObj.group(2) else: print "Nothing found!!" When the above code is executed, it produces the following result − searchObj.group() : Cats are smarter than dogs searchObj.group(1) : Cats searchObj.group(2) : smarter
[ { "code": null, "e": 1155, "s": 1062, "text": "This function searches for first occurrence of RE pattern within string with optional flags." }, { "code": null, "e": 1194, "s": 1155, "text": "Here is the syntax for this function −" }, { "code": null, "e": 1230, "s"...
Redirecting System.out.println() output to a file in Java
The filed named out of the System class represents a standard output Stream, an object of the PrintStream class. The println() method of this accepts any a value ( of any Java valid type), prints it and terminates the line. By default, console (screen) is the standard output Stream (System.in) in Java and, whenever we pass any String value to System.out.prinln() method, it prints the given String on the console. The setOut() method of the System class in java accepts an object of the PrintStream class and makes it the new standard output stream. Therefore, to redirect the System.out.println() output to a file − Create an object of the File class. Create an object of the File class. Instantiate a PrintStream class by passing the above created File object as a parameter. Instantiate a PrintStream class by passing the above created File object as a parameter. Invoke the out() method of the System class, pass the PrintStream object to it. Invoke the out() method of the System class, pass the PrintStream object to it. Finally, print data using the println() method, and it will be redirected to the file represented by the File object created in the first step. Finally, print data using the println() method, and it will be redirected to the file represented by the File object created in the first step. import java.io.File; import java.io.IOException; import java.io.PrintStream; public class SetOutExample { public static void main(String args[]) throws IOException { //Instantiating the File class File file = new File("D:\\sample.txt"); //Instantiating the PrintStream class PrintStream stream = new PrintStream(file); System.out.println("From now on "+file.getAbsolutePath()+" will be your console"); System.setOut(stream); //Printing values to file System.out.println("Hello, how are you"); System.out.println("Welcome to Tutorialspoint"); } } From now on D:\sample.txt will be your console
[ { "code": null, "e": 1175, "s": 1062, "text": "The filed named out of the System class represents a standard output Stream, an object of the PrintStream class." }, { "code": null, "e": 1286, "s": 1175, "text": "The println() method of this accepts any a value ( of any Java valid ...
Machine Learning Infrastructure with Amazon SageMaker and Terraform — A Case of Fraud Detection | by Quy Tang | Towards Data Science
Think of Machine Learning and its “deep” child, Deep Learning, one would instantly conjure up a web of complexity solvable only by massive computing power. The advent of big data and especially cloud machine learning platforms have vastly simplified access to these computing power for the wider population. A cloud machine learning platform provides a fully managed infrastructure that automatically scales, integrates with the latest data technology and comes equipped with many built-in algorithms. This enables any developers and data scientists to quickly build and deploy models without worrying about the underlying sophisticated infrastructure. Amazon SageMaker is the cloud machine learning platform offered by Amazon Web Services (AWS). The AWS Solutions Builder Team has shared many different solutions built on Amazon SageMaker, covering topics such as predictive analysis in telecommunication or predictive train equipment maintenance. In this post, I will take the credit card fraud detection solution example and explain how to set up supporting infrastructure with Terraform while breaking down the solution into smaller chunks. This post targets readers interested in learning about cloud infrastructure to support machine learning and a quick view of how a machine learning workflow looks like. Disclaimer: I don’t claim any expertise in machine learning. All machine leaning work in this post has been taken from AWS site. My main focus is on Cloud infrastructure and DevOps. I do have data analysis background having used R for financial forecasting and risk management calculations, but that’s not the main purpose here. The goal of this solution is to predict whether a given credit card transaction is fraudulent or not. This is a binary (yes/no) classification that typically requires a logistic regression algorithm which, within the context of Amazon SageMaker, is equivalent to the built-in linear learner algorithm with binary classifier predictor type. The complete project for this article is hosted on Github. There are 3 main parts to this solution: Training a model based on a sample credit card transaction dataset.Storing the model in an accessible interface.Using the model to predict whether a generated transaction is fraudulent. Training a model based on a sample credit card transaction dataset. Storing the model in an accessible interface. Using the model to predict whether a generated transaction is fraudulent. These are typical of a machine learning process, which looks like this: Let’s follow the implementation based on the above 3 parts. To train a model, these components are needed: i. Credit card transaction dataset where fraudulent transactions have already been identified (a.k.a. labeled). ii. A machine learning algorithm stored as a Docker image (the equivalent of a CD-ROM for the uninitiated). iii. A server with pre-loaded machine learning libraries for data scientists to prepare, visualize and enhance the training data, and then set the algorithm’s parameters (in layman’s term; hyperparameters in machine learning speak) before starting the training process. iv. Server(s) to train the model using a particular algorithm, this is essentially the “learning” part of machine learning, which also is the one that requires the most computational power. Amazon SageMaker provides ii, iii and iv as managed services, while i is taken from a public data source. This is where it starts to get technical. If you are not interested in infrastructure, you can skip this. In terms of infrastructure for this part of the solution, we only need to set up iii (called the notebook instance), which contains all necessary libraries and one Jupyter notebook, basically, the data scientists’ tooling code (cum document). The Jupyter notebook, located at source/notebooks/sagemaker_fraud_detection.ipynb in the source code repository, includes code that retrieves ii (algorithm) and delivers iv (training instances) using Amazon SageMaker’s library. Within AWS world, an instance usually refers to a server, which can be a virtual machine or a container. As seen above, the notebook instance requires a few supporting resources including: IAM Role and Policy for the notebook instance: S3 bucket for storing the Jupyter notebook: S3 bucket for storing training data as well as generated model data: SageMaker notebook instance: In order for the notebook instance to obtain the Jupyter notebook located in our source code, we have to add an init script that downloads the notebook from the aws_s3_bucket.fraud_detection_function_bucket above (we uploaded using the aws_s3_bucket_object). This is done using the notebook instance’s lifecycle configuration: These are the main steps in the Jupyter notebook: i. Download sample data and extract features and label (fraud/nonfraud). ii. Convert the n-dimensional arrays into RecordIO format (a highly efficient data format). import sagemaker.amazon.common as smacbuf = io.BytesIO()smac.write_numpy_to_dense_tensor(buf, features, labels) iii. Store the RecordIO data into S3 bucket. bucket = "fraud-detection-end-to-end-demo"prefix = 'linear-learner'key = 'recordio-pb-data'boto3.resource('s3').Bucket(bucket).Object(os.path.join(prefix, 'train', key)).upload_fileobj(buf) iv. Retrieve the Docker image for the linear learner algorithm. container = get_image_uri(boto3.Session().region_name, 'linear-learner') v. Create a training job with the desired instance type and instance count, change the (hyper)parameters of the algorithm and start training using the training data uploaded to S3 earlier. You can see how simple it is to set up a cluster of servers to train a model and only pay for the time that it takes to train, a major cost saver. import sagemakers3_train_data = 's3://{}/{}/train/{}'.format(bucket, prefix, key)output_location = 's3://{}/{}/output'.format(bucket, prefix)linear = sagemaker.estimator.Estimator(container, get_execution_role(), train_instance_count=1, train_instance_type='ml.c4.xlarge', output_path=output_location, sagemaker_session=session)linear.set_hyperparameters(feature_dim=features.shape[1], predictor_type='binary_classifier', mini_batch_size=200)linear.fit({'train': s3_train_data}) Complete code: https://github.com/qtangs/tf-fraud-detection-using-machine-learning/blob/master/source/notebooks/sagemaker_fraud_detection.ipynb To store a model and present it to the outside world for prediction later on, these components are required: i. Model data ii. Other model metadata (container, training job, ...) iii. An endpoint (interface) configuration iv. Actual endpoint (a set of servers to run prediction on-demand) Amazon Sagemaker hosts ii, iii and iv while i (the model data) is stored in S3 as we saw in the previous code (output_location). Both i and ii (the model specification) are created at the end of the call linear.fit(...) . The endpoint configuration (iii) and the actual endpoint (iv) are created by this part of the Jupyter notebook: linear_predictor = linear.deploy(initial_instance_count=1, endpoint_name="fraud-detection-endpoint", instance_type='ml.m4.xlarge') Complete code: https://github.com/qtangs/tf-fraud-detection-using-machine-learning/blob/master/source/notebooks/sagemaker_fraud_detection.ipynb With the created endpoint, we can now use it on any generated transaction. To simulate transactions coming in for prediction, we need: a CloudWatch Event is created to trigger Lambda function every 1 minute. an AWS Lambda function is created using code located at source/fraud_detection/index.py in the code repository. It follows these steps: randomly selects a predefined fraud or nonfraud transaction, sends the transaction to the endpoint to obtain a fraud prediction, sends the result to a Kinesis Data Firehose after some minor processing. a Kinesis Data Firehose that stores streamed results into S3. and finally, the S3 bucket. As seen above, the resources with the blue Terraform logo are required: CloudWatch event: IAM Role and Policy for Lambda prediction function: S3 bucket for storing the function code, taken from source/fraud_detection/index.py in our code repository The Lambda function which processes new transactions: IAM Role and Policy for the Kinesis Data Firehose: S3 bucket to store processed transactions from the Kinesis Data Firehose: And finally, the Kinesis Data Firehose: Terraform code is located in the folder terraform (original CloudFormation can be found in cloudformation). Before running terraform apply, there are a few set-ups to perform: i. Copy terraform_backend.tf.template to terraform_backend.tf and modify values accordingly. You need to manually create an S3 bucket or use an existing one to store the Terraform state file. Using remote backend for Terraform state is a good practice. It should be practiced even for a simple scenario like this. ii. Copy terraform.tfvars.template to terraform.tfvars and modify values accordingly. You don’t need to create any buckets specified in here; they’re to be created by terraform apply. iii. Once the above files are created, simply run through the following terraform commands. Remember to ensure all commands return ok and to review the terraform plan before applying. # Set default AWS profile,# use 'set' instead of 'export' for Windows.export AWS_PROFILE=<your desired profile>terraform initterraform validateterraform plan -out=tfplanterraform apply --auto-approve tfplan The Terraform plan output should look like this: And the result of terraform apply: Once all Terraform resources are set up, you need to follow these manual steps as documented by the AWS site: Run the Notebook Navigate to the Amazon SageMaker console.In the navigation pane, select Notebook instances.Select FraudDetectionNotebookInstance.The notebook instance should already be running.Select Open Jupyter.In the Jupyter notebook interface, open the sagemaker_fraud_detection.ipynb file.In the Cell dropdown menu, select Run All to run the file. Navigate to the Amazon SageMaker console. In the navigation pane, select Notebook instances. Select FraudDetectionNotebookInstance. The notebook instance should already be running. Select Open Jupyter. In the Jupyter notebook interface, open the sagemaker_fraud_detection.ipynb file. In the Cell dropdown menu, select Run All to run the file. Enable the CloudWatch Events Rule Navigate to the AWS Lambda console.In the navigation pane, select Functions.Select the fraud_detection_event_processor Lambda function.In the diagram in the Designer tab, select CloudWatch Events.In the CloudWatch Events tab, select <stackname>-ScheduleRule-<id>.Select Actions > Enable.Select Enable. Navigate to the AWS Lambda console. In the navigation pane, select Functions. Select the fraud_detection_event_processor Lambda function. In the diagram in the Designer tab, select CloudWatch Events. In the CloudWatch Events tab, select <stackname>-ScheduleRule-<id>. Select Actions > Enable. Select Enable. Verify the Lambda Function Is Processing Transactions Navigate to the AWS Lambda console.In the navigation pane, select Functions.Select the fraud_detection_event_processor Lambda function.Select Monitoring and verify that the Invocations graph shows activity.After a few minutes, check the results Amazon S3 bucket for processed transactions. Navigate to the AWS Lambda console. In the navigation pane, select Functions. Select the fraud_detection_event_processor Lambda function. Select Monitoring and verify that the Invocations graph shows activity. After a few minutes, check the results Amazon S3 bucket for processed transactions. Once you are done with the experiment, simply perform the followings to delete all resources and save costs. Again, remember to review the terraform plan before applying. terraform plan -destroy -out=tfplanterraform apply tfplan You should be able to see output like this: Amazon SageMaker is a powerful platform, we have just barely touched its surface. Thanks to the AWS Solution Builders Team, we have many fantastic examples of how Amazon SageMaker can be utilized. At the same time, Terraform simplifies the infrastructure setup for an enterprise setup where DevOps and Continuous Delivery become more and more important. In future posts, I will look into more complicated examples provided by the AWS Team and will also explore how Terraform infrastructure can be designed to fit into a CI/CD pipeline within a machine learning setup. Thank you for reading. Do comment below to share your thoughts. The complete project for this article is hosted on Github. Some rights reserved
[ { "code": null, "e": 480, "s": 172, "text": "Think of Machine Learning and its “deep” child, Deep Learning, one would instantly conjure up a web of complexity solvable only by massive computing power. The advent of big data and especially cloud machine learning platforms have vastly simplified acces...
Decimal to binary number using recursion - GeeksforGeeks
06 Dec, 2021 Given a decimal number as input, we need to write a program to convert the given decimal number into equivalent binary number. Examples : Input : 7 Output :111 Input :10 Output :1010 We have discussed one iterative solution in below post. Program for Decimal to Binary ConversionBelow is Recursive solution: findBinary(decimal) if (decimal == 0) binary = 0 else binary = decimal % 2 + 10 * (findBinary(decimal / 2) Step by step process for better understanding of how the algorithm works Let decimal number be 10. Step 1-> 10 % 2 which is equal-too 0 + 10 * ( 10/2 ) % 2 Step 2-> 5 % 2 which is equal-too 1 + 10 * ( 5 / 2) % 2Step 3-> 2 % 2 which is equal-too 0 + 10 * ( 2 / 2 ) % 2Step 4-> 1 % 2 which is equal-too 1 + 10 * ( 1 / 2 ) % 2 C++ C Java Python3 C# PHP Javascript // C++ program for decimal to binary// conversion using recursion#include <bits/stdc++.h>using namespace std; // Decimal to binary conversion// using recursionint find(int decimal_number){ if (decimal_number == 0) return 0; else return (decimal_number % 2 + 10 * find(decimal_number / 2));} // Driver codeint main(){ int decimal_number = 10; cout << find(decimal_number); return 0;}// This code is contributed by shivanisinghss2110 // C/C++ program for decimal to binary// conversion using recursion#include <stdio.h> // Decimal to binary conversion// using recursionint find(int decimal_number){ if (decimal_number == 0) return 0; else return (decimal_number % 2 + 10 * find(decimal_number / 2));} // Driver codeint main(){ int decimal_number = 10; printf("%d", find(decimal_number)); return 0;} // Java program for decimal to binary// conversion using recursionimport java.io.*; class GFG{ // Decimal to binary conversion // using recursion static int find(int decimal_number) { if (decimal_number == 0) return 0; else return (decimal_number % 2 + 10 * find(decimal_number / 2)); } // Driver Codepublic static void main(String args[]){ int decimal_number = 10; System.out.println(find(decimal_number));} } // This code is contributed by Nikita Tiwari # Python3 code for decimal to binary# conversion using recursion # Decimal to binary conversion# using recursiondef find( decimal_number ): if decimal_number == 0: return 0 else: return (decimal_number % 2 + 10 * find(int(decimal_number // 2))) # Driver Codedecimal_number = 10print(find(decimal_number)) # This code is contributed# by "Sharad_Bhardwaj" // C# program for decimal to binary// conversion using recursionusing System; class GFG{ // Decimal to binary conversion // using recursion static int find(int decimal_number) { if (decimal_number == 0) return 0; else return (decimal_number % 2 + 10 * find(decimal_number / 2)); } // Driver Code public static void Main() { int decimal_number = 10; Console.WriteLine(find(decimal_number)); }} // This code is contributed by vt_m <?php// PHP program for decimal to binary// conversion using recursion // Decimal to binary// conversion using recursionfunction find($decimal_number){ if ($decimal_number == 0) return 0; else return ($decimal_number % 2 + 10 * find($decimal_number / 2));} // Driver Code$decimal_number = 10;echo(find($decimal_number)); // This code is contributed by Ajit.?> <script> // Javascript program for decimal to binary// conversion using recursion // Decimal to binary conversion// using recursionfunction find(decimal_number){ if (decimal_number == 0) return 0; else return ((decimal_number % 2) + 10 * find(parseInt(decimal_number / 2)));} // Driver codevar decimal_number = 10;document.write( find(decimal_number)); // This code is contributed by noob2000.</script> 1010 The above approach works fine unless you want to convert a number greater than 1023 in decimal to binary. The binary of 1024 is 10000000000 (one 1 and ten 0’s) which goes out of the range of int. Even with long long unsigned as return type the highest you can go is 1048575 which is way less than the range of int. An easier but effective approach would be to store the individual digits of the binary number in a vector of bool. C++ Java Python3 C# Javascript // C++ program for decimal to binary// conversion using recursion#include<bits/stdc++.h>using namespace std; // Function to convert decimal to binaryvoid deci_to_bin(int x, string & bin_num){ // Base Case if (x <= 1) bin_num += (char)(x + '0'); else { // Recursion call deci_to_bin(x / 2, bin_num); // If x is divisible by 2 if(x%2) bin_num += '1'; // otherwise else bin_num += '0'; }} // Driver Codeint main(){ string bin_num = ""; deci_to_bin(1048576, bin_num); cout<<bin_num; return 0;} // Java program for decimal to binary// conversion using recursionpublic class Main{ static String bin_num = ""; // Function to convert decimal to binary static void deci_to_bin(int x) { // Base Case if (x <= 1) bin_num += (char)(x + '0'); else { // Recursion call deci_to_bin((int)(x / 2)); // If x is divisible by 2 if(x%2 != 0) bin_num += '1'; // otherwise else bin_num += '0'; } } public static void main(String[] args) { deci_to_bin(1048576); System.out.print(bin_num); }} // This code is contributed by divyesh072019. # Python3 code for decimal to binary# conversion using recursion # Decimal to binary conversion# using recursiondef getbinary(number): # Base case if number == 0: return 0 # Recursion call and storing the result smallans = getbinary(number // 2) return number % 2 + 10 * smallans # Driver Codedecimal_number = 1048576print(getbinary(decimal_number)) # This code is contributed# by "Sarthak Sethi" // C# program for decimal to binary// conversion using recursionusing System;class GFG { static string bin_num = ""; // Function to convert decimal to binary static void deci_to_bin(int x) { // Base Case if (x <= 1) bin_num += (char)(x + '0'); else { // Recursion call deci_to_bin((int)(x / 2)); // If x is divisible by 2 if(x%2 != 0) bin_num += '1'; // otherwise else bin_num += '0'; } } static void Main() { deci_to_bin(1048576); Console.Write(bin_num); }} // This code is contributed by mukesh07. <script> // Javascript program for decimal to binary // conversion using recursion let bin_num = ""; // Function to convert decimal to binary function deci_to_bin(x) { // Base Case if (x <= 1) bin_num += String.fromCharCode(x + '0'.charCodeAt()); else { // Recursion call deci_to_bin(parseInt(x / 2, 10)); // If x is divisible by 2 if(x%2 != 0) bin_num += '1'; // otherwise else bin_num += '0'; } } deci_to_bin(1048576); document.write(bin_num); // This code is contributed by divyeshrabadiya07.</script> 100000000000000000000 jit_t mohnishsrikanth shivanisinghss2110 yugal1407 ersarthaksethi noob2000 divyeshrabadiya07 mukesh07 divyesh072019 base-conversion Recursion School Programming Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Backtracking | Introduction Print all possible combinations of r elements in a given array of size n Recursive Practice Problems with Solutions Write a program to reverse digits of a number Recursive Functions Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 26237, "s": 26209, "text": "\n06 Dec, 2021" }, { "code": null, "e": 26365, "s": 26237, "text": "Given a decimal number as input, we need to write a program to convert the given decimal number into equivalent binary number. " }, { "code": null, "e"...
How to create a subarray from another array in Java
Use Arrays.copyOfRange() method to get a subarray. import java.util.Arrays; public class Tester { public static void main(String[] args) { int[] array = new int[] {1, 2, 3, 4, 5}; int[] subArray = Arrays.copyOfRange(array, 0, 2); System.out.println("Array: "); for(int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println("\nSub array: "); for(int i = 0; i < subArray.length; i++) { System.out.print(subArray[i] + " "); } } } Array: 1 2 3 4 5 Sub array: 1 2
[ { "code": null, "e": 1113, "s": 1062, "text": "Use Arrays.copyOfRange() method to get a subarray." }, { "code": null, "e": 1594, "s": 1113, "text": "import java.util.Arrays;\npublic class Tester {\n public static void main(String[] args) {\n int[] array = new int[] {1, 2, ...
A Machine Learning Approach to Author Identification of Horror Novels from Text Snippets | by Navoneel Chakrabarty | Towards Data Science
There are many novels being written but among them, some acquire cult status over the years and are remembered for ages. The novels are of several genres and cross genres (mixture of several genres). Horror is one particular genre of novels. There are many famous horror novels, which are absolute favourites of readers even after decades of their release. For example, the Goosebumps Series (1998–2016) by RL Stine has been a household name and one of the most celebrated horror novels of the modern times. But many classic horror novels appeared prior to the 21st Century. For instance, the horror novel, The Dream-Quest of Unknown Kadath (1943) by H.P. Lovecraft has been one of the must-read horror novels of the 20th Century. From here, if we rewind further to the 19th Century, how can anyone forget Mary Shelley’s Frankenstein (1818 & 1823) and Edgar Allan Poe’s The Fall of the House of Usher (1839) ? But one thing is quite obvious that, Every author, whether it is a Lovecraft or Mary Shelley or Poe, had their own style of writing which includes their signature fashion of using certain words, making their literature unique and recognisable So, let’s use this fact to identify the author (Lovecraft/Mary Shelley/Poe) from text snippets or quotes drawn from their horror novels. Machine Learning powered by Natural Language Processing (NLP) is an excellent solution to the above problem. So, let’s state the problem clearly and get started !!! Problem Statement: “Given Text Snippets/Quotes from renowned novels of Edgar Allan Poe, Mary Shelley and HP Lovecraft, identify that who is the author of the text snippet or quote” For the purpose, Spooky Author Identification Dataset prepared by Kaggle is considered. So, let’s commence the Machine Learning Model Development in Python using NLTK (Natural Language Took Kit) and Scikit-Learn !!! I. Loading (reading) the Dataset using Pandas: import pandas as pddf = pd.read_csv('train.csv')df.head(5) # for showing a snapshot of the dataset II. Text Processing Steps: Removal of Punctuation → All the punctuation marks are removed from all the text-snippets (instances or documents) from the dataset (corpus).Lemmatisation → Inflected forms of a word are known as lemma. For example, (studying, studied) are inflected forms or lemma of the word study which is the root word. So, the lemma of a word are grouped under the single root word. This is done to make the vocabulary of words in the corpus contain distinct words only.Removal of Stopwords → Stop-words are usually articles (a, an, the), prepositions (in, on, under, ...) and other frequently occurring words that do not provide any key or necessary information. They are removed from all the text-snippets present in the dataset (corpus). Removal of Punctuation → All the punctuation marks are removed from all the text-snippets (instances or documents) from the dataset (corpus). Lemmatisation → Inflected forms of a word are known as lemma. For example, (studying, studied) are inflected forms or lemma of the word study which is the root word. So, the lemma of a word are grouped under the single root word. This is done to make the vocabulary of words in the corpus contain distinct words only. Removal of Stopwords → Stop-words are usually articles (a, an, the), prepositions (in, on, under, ...) and other frequently occurring words that do not provide any key or necessary information. They are removed from all the text-snippets present in the dataset (corpus). # Importing necessary librariesimport stringfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerlemmatiser = WordNetLemmatizer()# Defining a module for Text Processingdef text_process(tex): # 1. Removal of Punctuation Marks nopunct=[char for char in tex if char not in string.punctuation] nopunct=''.join(nopunct) # 2. Lemmatisation a='' i=0 for i in range(len(nopunct.split())): b=lemmatiser.lemmatize(nopunct.split()[i], pos="v") a=a+b+' ' # 3. Removal of Stopwords return [word for word in a.split() if word.lower() not in stopwords.words('english')] III. Label Encoding of Classes: As this is a classification problem, here classes are the 3 authors as mentioned. But in the dataset, it can be seen that labels are non-numeric (MWS, EAP and HPL). These are label encoded to make them numeric, starting from 0 depicting each label in the alphabetic order i.e., (0 → EAP, 1 → HPL and 2 → MWS) # Importing necessary librariesfrom sklearn.preprocessing import LabelEncodery = df['author']labelencoder = LabelEncoder()y = labelencoder.fit_transform(y) IV. Word Cloud Visualization: As the Machine Learning Model is being developed, banking on the fact that the authors have their own unique styles of using particular words in the text, a visualization of the mostly-used words to the least-used words by the 3 authors is done, taking 3 text snippets each belonging to the 3 authors respectively with the help of a Word Cloud. # Importing necessary librariesfrom PIL import Imagefrom wordcloud import WordCloudimport matplotlib.pyplot as pltX = df['text']wordcloud1 = WordCloud().generate(X[0]) # for EAPwordcloud2 = WordCloud().generate(X[1]) # for HPLwordcloud3 = WordCloud().generate(X[3]) # for MWS print(X[0])print(df['author'][0])plt.imshow(wordcloud1, interpolation='bilinear')plt.show()print(X[1])print(df['author'][1])plt.imshow(wordcloud2, interpolation='bilinear')plt.show()print(X[3])print(df['author'][3])plt.imshow(wordcloud3, interpolation='bilinear')plt.show() V. Feature Engineering using Bag-of-Words: Machine Learning Algorithms work only on numeric data. But here, data is present in the form of text only. For that, by some means, textual data needs to be transformed into numeric form. One such approach of doing this, is Feature Engineering. In this approach, numeric features are extracted or engineered from textual data. There are many Feature Engineering Techniques in existence. In this problem, Bag-of-Words Technique of Feature Engineering has been used. =>Bag-of-Words: Here, a vocabulary of words present in the corpus is maintained. These words serve as features for each instance or document (here text snippet). Against each word as feature, its frequency in the current document (text snippet) is considered. Hence, in this way word features are engineered or extracted from the textual data or corpus. # Importing necessary librariesfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.model_selection import train_test_split# 80-20 splitting the dataset (80%->Training and 20%->Validation)X_train, X_test, y_train, y_test = train_test_split(X, y ,test_size=0.2, random_state=1234)# defining the bag-of-words transformer on the text-processed corpus # i.e., text_process() declared in II is executed...bow_transformer=CountVectorizer(analyzer=text_process).fit(X_train)# transforming into Bag-of-Words and hence textual data to numeric..text_bow_train=bow_transformer.transform(X_train)#ONLY TRAINING DATA# transforming into Bag-of-Words and hence textual data to numeric..text_bow_test=bow_transformer.transform(X_test)#TEST DATA VI. Training the Model: Multinomial Naive Bayes Algorithm (Classifier) has been used as the Classification Machine Learning Algorithm [1]. # Importing necessary librariesfrom sklearn.naive_bayes import MultinomialNB# instantiating the model with Multinomial Naive Bayes..model = MultinomialNB()# training the model...model = model.fit(text_bow_train, y_train) VII. Model Performance Analysis: => Training Accuracy model.score(text_bow_train, y_train) => Validation Accuracy model.score(text_bow_test, y_test) => Precision, Recall and F1–Score # Importing necessary librariesfrom sklearn.metrics import classification_report # getting the predictions of the Validation Set...predictions = model.predict(text_bow_test)# getting the Precision, Recall, F1-Scoreprint(classification_report(y_test,predictions)) => Confusion Matrix # Importing necessary librariesfrom sklearn.metrics import confusion_matriximport numpy as npimport itertoolsimport matplotlib.pyplot as plt# Defining a module for Confusion Matrix...def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization')print(cm)plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes)fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]) , range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black")plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')cm = confusion_matrix(y_test,predictions)plt.figure()plot_confusion_matrix(cm, classes=[0,1,2], normalize=True, title='Confusion Matrix') According to the Performance Analysis, it can be concluded that the NLP Powered Machine Learning Model has been successful in effectively classifying 84.14% unknown (Validation Set) examples correctly. In other words, 84.14% of text-snippets are identified correctly that it belongs to which author among the three. Based on our Model Performance, can we conclude which author has the most unique style of writing? The answer is YES !!! Let’s look at the Normalized Confusion Matrix. Here label 2 is the most correctly classified. As label 2 refers to Mary Wollstonecraft Shelley, it can be concluded that Mary Wollstonecraft Shelley has the most unique style of writing Horror Novels w.r.t Edgar Allan Poe and HP Lovecraft. Also, in a different sense, can we say who is the most versatile author among Mary Shelley, Edgar Allan Poe and HP Lovecraft? Again the answer is YES !!! Again looking at the Confusion Matrix, label 0 is the least correctly classified. Label 0 refers to Edgar Allan Poe, so it can be concluded that Edgar Allan Poe is more versatile than HP Lovecraft and Mary Shelley. In this way, a Text Detection Model can be developed using Machine Learning and Natural Language Processing. A relevant web-application using trained Bernoulli Naive Bayes (instead of Multinomial Naive Bayes) has also been developed and deployed in Heroku using Flask API. The link to the Web-App is given below:
[ { "code": null, "e": 1119, "s": 172, "text": "There are many novels being written but among them, some acquire cult status over the years and are remembered for ages. The novels are of several genres and cross genres (mixture of several genres). Horror is one particular genre of novels. There are ma...
Find the closest leaf in a Binary Tree - GeeksforGeeks
14 Jan, 2022 Given a Binary Tree and a key ‘k’, find distance of the closest leaf from ‘k’. Examples: A / \ B C / \ E F / \ G H / \ / I J K Closest leaf to 'H' is 'K', so distance is 1 for 'H' Closest leaf to 'C' is 'B', so distance is 2 for 'C' Closest leaf to 'E' is either 'I' or 'J', so distance is 2 for 'E' Closest leaf to 'B' is 'B' itself, so distance is 0 for 'B' The main point to note here is that a closest key can either be a descendant of given key or can be reached through one of the ancestors. The idea is to traverse the given tree in preorder and keep track of ancestors in an array. When we reach the given key, we evaluate distance of the closest leaf in subtree rooted with given key. We also traverse all ancestors one by one and find distance of the closest leaf in the subtree rooted with ancestor. We compare all distances and return minimum. Below is the implementation of above approach. C++ Java Python3 C# Javascript // A C++ program to find the closest leaf of a given key in Binary Tree#include <bits/stdc++.h>using namespace std; /* A binary tree Node has key, pocharer to left and right children */struct Node{ char key; struct Node* left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pocharers. */Node *newNode(char k){ Node *node = new Node; node->key = k; node->right = node->left = NULL; return node;} // A utility function to find minimum of x and yint getMin(int x, int y){ return (x < y)? x :y;} // A utility function to find distance of closest leaf of the tree// rooted under given rootint closestDown(struct Node *root){ // Base cases if (root == NULL) return INT_MAX; if (root->left == NULL && root->right == NULL) return 0; // Return minimum of left and right, plus one return 1 + getMin(closestDown(root->left), closestDown(root->right));} // Returns distance of the closest leaf to a given key 'k'. The array// ancestors is used to keep track of ancestors of current node and// 'index' is used to keep track of current index in 'ancestors[]'int findClosestUtil(struct Node *root, char k, struct Node *ancestors[], int index){ // Base case if (root == NULL) return INT_MAX; // If key found if (root->key == k) { // Find the closest leaf under the subtree rooted with given key int res = closestDown(root); // Traverse all ancestors and update result if any parent node // gives smaller distance for (int i = index-1; i>=0; i--) res = getMin(res, index - i + closestDown(ancestors[i])); return res; } // If key node found, store current node and recur for left and // right childrens ancestors[index] = root; return getMin(findClosestUtil(root->left, k, ancestors, index+1), findClosestUtil(root->right, k, ancestors, index+1)); } // The main function that returns distance of the closest key to 'k'. It// mainly uses recursive function findClosestUtil() to find the closes// distance.int findClosest(struct Node *root, char k){ // Create an array to store ancestors // Assumption: Maximum height of tree is 100 struct Node *ancestors[100]; return findClosestUtil(root, k, ancestors, 0);} /* Driver program to test above functions*/int main(){ // Let us construct the BST shown in the above figure struct Node *root = newNode('A'); root->left = newNode('B'); root->right = newNode('C'); root->right->left = newNode('E'); root->right->right = newNode('F'); root->right->left->left = newNode('G'); root->right->left->left->left = newNode('I'); root->right->left->left->right = newNode('J'); root->right->right->right = newNode('H'); root->right->right->right->left = newNode('K'); char k = 'H'; cout << "Distance of the closest key from " << k << " is " << findClosest(root, k) << endl; k = 'C'; cout << "Distance of the closest key from " << k << " is " << findClosest(root, k) << endl; k = 'E'; cout << "Distance of the closest key from " << k << " is " << findClosest(root, k) << endl; k = 'B'; cout << "Distance of the closest key from " << k << " is " << findClosest(root, k) << endl; return 0;} // Java program to find closest leaf of a given key in Binary Tree /* Class containing left and right child of current node and key value*/class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; // A utility function to find minimum of x and y int getMin(int x, int y) { return (x < y) ? x : y; } // A utility function to find distance of closest leaf of the tree // rooted under given root int closestDown(Node node) { // Base cases if (node == null) return Integer.MAX_VALUE; if (node.left == null && node.right == null) return 0; // Return minimum of left and right, plus one return 1 + getMin(closestDown(node.left), closestDown(node.right)); } // Returns distance of the closest leaf to a given key 'k'. The array // ancestors is used to keep track of ancestors of current node and // 'index' is used to keep track of current index in 'ancestors[]' int findClosestUtil(Node node, char k, Node ancestors[], int index) { // Base case if (node == null) return Integer.MAX_VALUE; // If key found if (node.data == k) { // Find the closest leaf under the subtree rooted with given key int res = closestDown(node); // Traverse all ancestors and update result if any parent node // gives smaller distance for (int i = index - 1; i >= 0; i--) res = getMin(res, index - i + closestDown(ancestors[i])); return res; } // If key node found, store current node and recur for left and // right childrens ancestors[index] = node; return getMin(findClosestUtil(node.left, k, ancestors, index + 1), findClosestUtil(node.right, k, ancestors, index + 1)); } // The main function that returns distance of the closest key to 'k'. It // mainly uses recursive function findClosestUtil() to find the closes // distance. int findClosest(Node node, char k) { // Create an array to store ancestors // Assumption: Maximum height of tree is 100 Node ancestors[] = new Node[100]; return findClosestUtil(node, k, ancestors, 0); } // Driver program to test for above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node('A'); tree.root.left = new Node('B'); tree.root.right = new Node('C'); tree.root.right.left = new Node('E'); tree.root.right.right = new Node('F'); tree.root.right.left.left = new Node('G'); tree.root.right.left.left.left = new Node('I'); tree.root.right.left.left.right = new Node('J'); tree.root.right.right.right = new Node('H'); tree.root.right.right.right.left = new Node('H'); char k = 'H'; System.out.println("Distance of the closest key from " + k + " is " + tree.findClosest(tree.root, k)); k = 'C'; System.out.println("Distance of the closest key from " + k + " is " + tree.findClosest(tree.root, k)); k = 'E'; System.out.println("Distance of the closest key from " + k + " is " + tree.findClosest(tree.root, k)); k = 'B'; System.out.println("Distance of the closest key from " + k + " is " + tree.findClosest(tree.root, k)); }} // This code has been contributed by Mayank Jaiswal # Python program to find closest leaf of a# given key in binary tree INT_MAX = 2**32 # A binary tree nodeclass Node: # Constructor to create a binary tree def __init__(self ,key): self.key = key self.left = None self.right = None def closestDown(root): #Base Case if root is None: return INT_MAX if root.left is None and root.right is None: return 0 # Return minimum of left and right plus one return 1 + min(closestDown(root.left), closestDown(root.right)) # Returns distance of the closes leaf to a given key k# The array ancestors us used to keep track of ancestors# of current node and 'index' is used to keep track of# current index in 'ancestors[i]'def findClosestUtil(root, k, ancestors, index): # Base Case if root is None: return INT_MAX # if key found if root.key == k: # Find closest leaf under the subtree rooted # with given key res = closestDown(root) # Traverse ll ancestors and update result if any # parent node gives smaller distance for i in reversed(range(0,index)): res = min(res, index-i+closestDown(ancestors[i])) return res # if key node found, store current node and recur for left # and right childrens ancestors[index] = root return min( findClosestUtil(root.left, k,ancestors, index+1), findClosestUtil(root.right, k, ancestors, index+1)) # The main function that return distance of the clses key to# 'key'. It mainly uses recursive function findClosestUtil()# to find the closes distancedef findClosest(root, k): # Create an array to store ancestors # Assumption: Maximum height of tree is 100 ancestors = [None for i in range(100)] return findClosestUtil(root, k, ancestors, 0) # Driver program to test above functionroot = Node('A')root.left = Node('B')root.right = Node('C');root.right.left = Node('E');root.right.right = Node('F');root.right.left.left = Node('G');root.right.left.left.left = Node('I');root.right.left.left.right = Node('J');root.right.right.right = Node('H');root.right.right.right.left = Node('K'); k = 'H';print ("Distance of the closest key from "+ k + " is",findClosest(root, k)) k = 'C'print ("Distance of the closest key from " + k + " is",findClosest(root, k)) k = 'E'print ("Distance of the closest key from " + k + " is",findClosest(root, k)) k = 'B'print ("Distance of the closest key from " + k + " is",findClosest(root, k)) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) using System; // C# program to find closest leaf of a given key in Binary Tree /* Class containing left and right child of current node and key value*/public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; // A utility function to find minimum of x and y public virtual int getMin(int x, int y) { return (x < y) ? x : y; } // A utility function to find distance of closest leaf of the tree // rooted under given root public virtual int closestDown(Node node) { // Base cases if (node == null) { return int.MaxValue; } if (node.left == null && node.right == null) { return 0; } // Return minimum of left and right, plus one return 1 + getMin(closestDown(node.left), closestDown(node.right)); } // Returns distance of the closest leaf to a given key 'k'. The array // ancestors is used to keep track of ancestors of current node and // 'index' is used to keep track of current index in 'ancestors[]' public virtual int findClosestUtil(Node node, char k, Node[] ancestors, int index) { // Base case if (node == null) { return int.MaxValue; } // If key found if ((char)node.data == k) { // Find the closest leaf under the subtree rooted with given key int res = closestDown(node); // Traverse all ancestors and update result if any parent node // gives smaller distance for (int i = index - 1; i >= 0; i--) { res = getMin(res, index - i + closestDown(ancestors[i])); } return res; } // If key node found, store current node and recur for left and // right childrens ancestors[index] = node; return getMin(findClosestUtil(node.left, k, ancestors, index + 1), findClosestUtil(node.right, k, ancestors, index + 1)); } // The main function that returns distance of the closest key to 'k'. It // mainly uses recursive function findClosestUtil() to find the closes // distance. public virtual int findClosest(Node node, char k) { // Create an array to store ancestors // Assumption: Maximum height of tree is 100 Node[] ancestors = new Node[100]; return findClosestUtil(node, k, ancestors, 0); } // Driver program to test for above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node('A'); tree.root.left = new Node('B'); tree.root.right = new Node('C'); tree.root.right.left = new Node('E'); tree.root.right.right = new Node('F'); tree.root.right.left.left = new Node('G'); tree.root.right.left.left.left = new Node('I'); tree.root.right.left.left.right = new Node('J'); tree.root.right.right.right = new Node('H'); tree.root.right.right.right.left = new Node('H'); char k = 'H'; Console.WriteLine("Distance of the closest key from " + k + " is " + tree.findClosest(tree.root, k)); k = 'C'; Console.WriteLine("Distance of the closest key from " + k + " is " + tree.findClosest(tree.root, k)); k = 'E'; Console.WriteLine("Distance of the closest key from " + k + " is " + tree.findClosest(tree.root, k)); k = 'B'; Console.WriteLine("Distance of the closest key from " + k + " is " + tree.findClosest(tree.root, k)); }} // This code is contributed by Shrikant13 <script> // JavaScript program to find closest// leaf of a given key in Binary Tree /* Class containing left and right child of current node and key value*/class Node{ constructor(item) { this.data = item; this.left = null; this.right= null; }} var root = null; // A utility function to find minimum of x and yfunction getMin(x, y){ return (x < y) ? x : y;} // A utility function to find distance of closest leaf of the tree// rooted under given rootfunction closestDown(node){ // Base cases if (node == null) { return 1000000000; } if (node.left == null && node.right == null) { return 0; } // Return minimum of left and right, plus one return 1 + getMin(closestDown(node.left), closestDown(node.right));}// Returns distance of the closest// leaf to a given key 'k'. The array// ancestors is used to keep track of// ancestors of current node and// 'index' is used to keep track of// current index in 'ancestors[]'function findClosestUtil(node, k, ancestors, index){ // Base case if (node == null) { return 1000000000; } // If key found if (node.data == k) { // Find the closest leaf under the // subtree rooted with given key var res = closestDown(node); // Traverse all ancestors and update // result if any parent node // gives smaller distance for (var i = index - 1; i >= 0; i--) { res = getMin(res, index - i + closestDown(ancestors[i])); } return res; } // If key node found, store current // node and recur for left and // right childrens ancestors[index] = node; return getMin(findClosestUtil(node.left, k, ancestors, index + 1), findClosestUtil(node.right, k, ancestors, index + 1));}// The main function that returns// distance of the closest key to 'k'. It// mainly uses recursive function// findClosestUtil() to find the closes// distance.function findClosest(node, k){ // Create an array to store ancestors // Assumption: Maximum height of tree is 100 var ancestors = Array(100).fill(null); return findClosestUtil(node, k, ancestors, 0);}// Driver program to test for above functionsroot = new Node('A');root.left = new Node('B');root.right = new Node('C');root.right.left = new Node('E');root.right.right = new Node('F');root.right.left.left = new Node('G');root.right.left.left.left = new Node('I');root.right.left.left.right = new Node('J');root.right.right.right = new Node('H');root.right.right.right.left = new Node('H');var k = 'H';document.write("Distance of the closest key from " + k+ " is " + findClosest(root, k) + "<br>");k = 'C';document.write("Distance of the closest key from " +k + " is " + findClosest(root, k)+ "<br>");k = 'E';document.write("Distance of the closest key from " + k+ " is " + findClosest(root, k)+ "<br>");k = 'B';document.write("Distance of the closest key from " + k+ " is " + findClosest(root, k)+ "<br>"); </script> Output: Distance of the closest key from H is 1 Distance of the closest key from C is 2 Distance of the closest key from E is 2 Distance of the closest key from B is 0 The above code can be optimized by storing the left/right information also in ancestor array. The idea is, if given key is in left subtree of an ancestors, then there is no point to call closestDown(). Also, the loop can that traverses ancestors array can be optimized to not traverse ancestors which are at more distance than current result. Exercise: Extend the above solution to print not only distance, but the key of the closest leaf also.This article is contributed by Shubham. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shrikanth13 ManasChhabra2 noob2000 sweetyty surinderdawra388 surindertarika1234 prachisoda1234 akshaysingh98088 simmytarika5 amartyaghoshgfg Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) Decision Tree A program to check if a binary tree is BST or not Construct Tree from given Inorder and Preorder traversals Introduction to Tree Data Structure Expression Tree Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Lowest Common Ancestor in a Binary Tree | Set 1 Deletion in a Binary Tree
[ { "code": null, "e": 26811, "s": 26783, "text": "\n14 Jan, 2022" }, { "code": null, "e": 26890, "s": 26811, "text": "Given a Binary Tree and a key ‘k’, find distance of the closest leaf from ‘k’." }, { "code": null, "e": 26901, "s": 26890, "text": "Examples: "...
Construct Binary Search Tree from Preorder Traversal in Python
Suppose we have to create a binary search tree that matches the given preorder traversal. So if the pre-order traversal is like [8,5,1,7,10,12], then the output will be [8,5,10,1,7,null,12], so the tree will be − To solve this, we will follow these steps − root := 0th node of the preorder traversal list stack := a stack, and push root into the stack for each element i from the second element of the preorder listi := a node with value iif value of i < top of the stack top element, thenleft of stack top node := iinsert i into the stackotherwisewhile stack is not empty, and stack top element value < value of ilast := top of stackpop element from stackright of the last node := iinsert i into the stack i := a node with value i if value of i < top of the stack top element, thenleft of stack top node := iinsert i into the stack left of stack top node := i insert i into the stack otherwisewhile stack is not empty, and stack top element value < value of ilast := top of stackpop element from stackright of the last node := iinsert i into the stack while stack is not empty, and stack top element value < value of ilast := top of stackpop element from stack last := top of stack pop element from stack right of the last node := i insert i into the stack return root Let us see the following implementation to get better understanding − class Solution(object): def bstFromPreorder(self, preorder): """ :type preorder: List[int] :rtype: TreeNode """ root = TreeNode(preorder[0]) stack = [root] for i in preorder[1:]: i = TreeNode(i) if i.val<stack[-1].val: stack[-1].left = i stack.append(i) else: while stack and stack[-1].val<i.val: last = stack.pop(-1) last.right = i stack.append(i) return root [8,5,1,7,10,12] [8,5,10,1,7,null,12]
[ { "code": null, "e": 1275, "s": 1062, "text": "Suppose we have to create a binary search tree that matches the given preorder traversal. So if the pre-order traversal is like [8,5,1,7,10,12], then the output will be [8,5,10,1,7,null,12], so the tree will be −" }, { "code": null, "e": 131...