code-rag-bench/online-tutorials huggingface dataset:
Node.js crypto.createHash() Method

24 Jun, 2022
The crypto.createHash() method is used to create a Hash object that can be used to create hash digests by using the stated algorithm. 
Syntax:
crypto.createHash( algorithm, options )
Parameters: This method accept two parameters as mentioned above and described below:
algorithm: It is dependent on the accessible algorithms which are favored by the version of OpenSSL on the platform. It returns string. The examples are sha256, sha512, etc.
options: It is optional parameter and is used to control stream behavior. It returns an object. Moreover, For XOF hash functions like ‘shake256’, the option outputLength can be used to determine the required output length in bytes.
Return Type: It returns Hash object. 
Below examples illustrate the use of crypto.createHash() method in Node.js: 
Example 1: 
javascript
// Node.js program to demonstrate the    // crypto.createHash() method // Includes crypto moduleconst crypto = require('crypto'); // Defining keyconst secret = 'Hi'; // Calling createHash methodconst hash = crypto.createHash('sha256', secret)                                       // updating data                   .update('How are you?')                    // Encoding to be used                   .digest('hex'); // Displays outputconsole.log(hash);
Output:
df287dfc1406ed2b692e1c2c783bb5cec97eac53151ee1d9810397aa0afa0d89
Example 2: 
javascript
// Node.js program to demonstrate the    // crypto.createHash() method // Defining filenameconst filename = process.argv[1]; // Includes crypto and  fs moduleconst crypto = require('crypto');const fs = require('fs'); // Creating Hashconst hash = crypto.createHash('sha256', 'Geeksforgeeks'); // Creating read streamconst input = fs.createReadStream(filename); input.on('readable', () => {   // Calling read method to read data  const data = input.read();  if (data)         // Updating    hash.update(data);  else   {    // Encoding and displaying filename    console.log(`${hash.digest('base64')} ${filename}`);  }});console.log("Program done!");
Output:
Program done!
n95mt3468ZzAIwu/bbNU7dej6CoFkDRcNaJo7rGpLF4= index.js
Reference: https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm_options
vinayedula
claudioplatzx5
Node.js-crypto-module
Node.js
Web Technologies
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 ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python | Get tuple element data types

18 Oct, 2019
Tuples can be a collection of various data types, and unlike simpler data types, conventional methods of getting the type of each element of tuple is not possible. For this we need to have different ways to achieve this task. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using map() + type()Using this function is most conventional and best way to perform this task. In this, we just allow map() to extend the logic of finding data types using type() to each element of tuple.
# Python3 code to demonstrate working of# Get tuple element data types# Using map() + type()  # Initializing tupletest_tup = ('gfg', 1, ['is', 'best'])  # printing original tupleprint("The original tuple is : " + str(test_tup))  # Get tuple element data types# Using map() + type()res = list(map(type, test_tup))  # printing resultprint("The data types of tuple in order are : " + str(res))
The original tuple is : ('gfg', 1, ['is', 'best'])
The data types of tuple in order are : [<class 'str'>, <class 'int'>, <class 'list'>]

 
Method #2 : Using collections.Sequence + isinstance() + type()We can perform this task using the combination of above functions. The additional advantage of using this method it that it also provides us with the length of each element if its type is complex data type.
# Python3 code to demonstrate working of# Get tuple element data types# Using collections.Sequence + isinstance() + type()import collections  # Initializing tupletest_tup = ('gfg', 1, ['is', 'best'])  # printing original tupleprint("The original tuple is : " + str(test_tup))  # Get tuple element data types# Using collections.Sequence + isinstance() + type()res = [(type(ele), len(ele) if isinstance(ele, collections.Sequence) else None)     for ele in test_tup]  # printing resultprint("The data types of tuple in order are : " + str(res))
The original tuple is : ('gfg', 1, ['is', 'best'])
The data types of tuple in order are : [(<class 'str'>, 3), (<class 'int'>, None), (<class 'list'>, 2)]

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Interesting Patterns | Practice | GeeksforGeeks

Given an integer N. Your task is to identify the pattern from the Examples and print the pattern.
 
Example 1: 
Input:
N = 4
Output:
4444444 
4333334 
4322234 
4321234 
4322234 
4333334 
4444444
Example 2: 
Input:
N = 3
Output:
33333 
32223 
32123 
32223 
33333
 
Your Task:
You don't need to read input or print anything. Your task is to complete the function interestingPattern() which takes an Integer N as input and returns a vector of strings where each line representins each line of the pattern. For example, if N = 3, you have to return a vector v = {"33333", "32223", "32123", "32223", "33333"}.
 
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
 
Constraints:
1 <= N < 10
0
ashwinaditya214 weeks ago
Length = 2*n -1
for i,j=0 to i,j<Length (two for loops)
Find min of i, j, length-1-i, length-1-j
subtract min from N and print
 
class Solution {
    static String[] interestingPattern(int N) {
        // code here
        int length = 2*N - 1;
        String[] result = new String[length];
        
        for(int i=0; i<length; i++) {
            StringBuilder sb = new StringBuilder();
            for(int j=0; j<length; j++) {
                int a = (int)Math.min(i, j);
                int b = (int)Math.min(length-1-i, length-1-j);
                sb.append(N-(int)Math.min(a, b));
            }
            result[i] = sb.toString();
        }
        return result;
    }
};
+3
choudharymanojloul8447 months ago
code not work for 60?
 
+2
choudharymanojloul8447 months ago
vector<string> interestingPattern(int N)    {   vector<string> v;      for(int i=1;i<=2*N-1;++i)   {       string str="";       for(int j=1;j<=2*N-1;++j)       {           int k=max(abs(i-N),abs(j-N))+1;            str+=to_string(k);       }       v.push_back(str);   }   return v;   }
 
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.
Struts 2 - Control Tags

The Struts 2 tags has a set of tags that makes it easy to control the flow of page execution.
Following is the list of important Struts 2 Control Tags −
These tags perform basic condition flow found in every language.
'If' tag is used by itself or with 'Else If' Tag and/or single/multiple 'Else' Tag as shown below −
<s:if test = "%{false}">
   <div>Will Not Be Executed</div>
</s:if>

<s:elseif test = "%{true}">
   <div>Will Be Executed</div>
</s:elseif>

<s:else>
   <div>Will Not Be Executed</div>
</s:else>
Check Detailed Example
This iterator will iterate over a value. An iterable value can be either itherjava.util.Collection or java.util.Iterator file. While iterating over an iterator, you can use Sort tag to sort the result or SubSet tag to get a sub set of the list or array.
The following example retrieves the value of the getDays() method of the current object on the value stack and uses it to iterate over.
The <s:property/> tag prints out the current value of the iterator.
<s:iterator value = "days">
   <p>day is: <s:property/></p>
</s:iterator>
Check Detailed Example
These merge tag takes two or more lists as parameters and merge them all together as shown below −
<s:merge var = "myMergedIterator">
   <s:param value = "%{myList1}" />
   <s:param value = "%{myList2}" />
   <s:param value = "%{myList3}" />
</s:merge>

<s:iterator value = "%{#myMergedIterator}">
   <s:property />
</s:iterator>
Check Detailed Example
These append tag take two or more lists as parameters and append them all together as shown below −
<s:append var = "myAppendIterator">
   <s:param value = "%{myList1}" />
   <s:param value = "%{myList2}" />
   <s:param value = "%{myList3}" />
</s:append>

<s:iterator value = "%{#myAppendIterator}">
   <s:property />
</s:iterator>
Check Detailed Example
These generator tag generates an iterator based on the val attribute supplied. The following generator tag generates an iterator and prints it out using the iterator tag.
<s:generator val = "%{'aaa,bbb,ccc,ddd,eee'}">
   <s:iterator>
      <s:property /><br/>
   </s:iterator>
</s:generator>
Check Detailed Example
 Print
 Add Notes
 Bookmark this page
ES6 - getTimezoneOffset() Method

Javascript date getTimezoneOffset() method returns the time-zone offset in minutes for the current locale. The time-zone offset is the minutes in difference, the Greenwich Mean Time (GMT) is relative to your local time.
For example, if your time zone is GMT+10, -600 will be returned. Daylight savings time prevents this value from being a constant.
Date.getTimezoneOffset()   

Returns the time-zone offset in minutes for the current locale.
var dt = new Date("December 25, 1995 23:15:00"); 
console.log("getTimezoneoffset() : " + dt.getTimezoneOffset()); 
getTimezoneoffset() : -330  


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
wxPython - Layout Management

A GUI widget can be placed inside the container window by specifying its absolute coordinates measured in pixels. The coordinates are relative to the dimensions of the window defined by size argument of its constructor. Position of the widget inside the window is defined by pos argument of its constructor.
import wx  

app = wx.App() 
window = wx.Frame(None, title = "wxPython Frame", size = (300,200)) 
panel = wx.Panel(window) 
label = wx.StaticText(panel, label = "Hello World", pos = (100,50)) 
window.Show(True) 
app.MainLoop()
This Absolute Positioning however is not suitable because of the following reasons −
The position of the widget does not change even if the window is resized.
The position of the widget does not change even if the window is resized.
The appearance may not be uniform on different display devices with different resolutions.
The appearance may not be uniform on different display devices with different resolutions.
Modification in the layout is difficult as it may need redesigning the entire form.
Modification in the layout is difficult as it may need redesigning the entire form.
wxPython API provides Layout classes for more elegant management of positioning of widgets inside the container. The advantages of Layout managers over absolute positioning are −
Widgets inside the window are automatically resized.
Ensures uniform appearance on display devices with different resolutions.
Adding or removing widgets dynamically is possible without having to redesign.
Layout manager is called Sizer in wxPython. Wx.Sizer is the base class for all sizer subclasses. Let us discuss some of the important sizers such as wx.BoxSizer, wx.StaticBoxSizer, wx.GridSizer, wx.FlexGridSizer, and wx.GridBagSizer.
This sizer allows the controls to be arranged in row-wise or column-wise manner. BoxSizer’s layout is determined by its orientation argument (either wxVERTICAL or wxHORIZONTAL).
As the name suggests, a GridSizer object presents a two dimensional grid. Controls are added in the grid slot in the left-to-right and top-to-bottom order. 
This sizer also has a two dimensional grid. However, it provides little more flexibility in laying out the controls in the cells.
GridBagSizer is a versatile sizer. It offers more enhancements than FlexiGridSizer. Child widget can be added to a specific cell within the grid. 
A StaticBoxSizer puts a box sizer into a static box. It provides a border around the box along with a label at the top.
 Print
 Add Notes
 Bookmark this page
numpy.matrix() in Python - GeeksforGeeks

09 Mar, 2022
This class returns a matrix from a string of data or array-like object. Matrix obtained is a specialised 2D array.Syntax :
numpy.matrix(data, dtype = None) : 
Parameters :
data  : data needs to be array-like or string 
dtype : Data type of returned array. 
     

Returns :
data interpreted as a matrix
# Python Program illustrating# numpy.matrix class  import numpy as geek  # string inputa = geek.matrix('1 2; 3 4')print("Via string input : \n", a, "\n\n")  # array-like inputb = geek.matrix([[5, 6, 7], [4, 6]])print("Via array-like input : \n", b)
Output :
Via string input : 
 [[1 2]
 [3 4]] 


Via array-like input : 
 [[[5, 6, 7] [4, 6]]]
 
References :https://docs.scipy.org/doc/numpy/reference/generated/numpy.mat.html#numpy.mat
Note :These codes won’t run on online IDE’s. Please run them on your systems to explore the working.This article is contributed by Mohit Gupta_OMG . 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.
vinayedula
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Quine in Python

The Quine is a program, which takes no input, but it produces output. It will show it’s own source code. Additionally, Quine has some conditions. We cannot open the source code file inside the program.
 Live Demo
a='a=%r;print (a%%a)';print (a%a)
a='a=%r;print (a%%a)';print (a%a)

Here a simple string formatting is working. We are defining a variable ‘a’, and inside a, we are storing ‘a=%r;print (a%%a)’ Then we are printing the value of a, and also replacing %r with the value of a. Thus the quine is working.
We can do the same task by opening the file like this.
print(open(__file__).read())

But in this case we are violating the rule of Quine. We cannot open file in Quine.
Tryit Editor v3.7

Tryit: ABC with utf8
How to compare two strings using regex in Python?

We can compare given strings using the following code
import re
s1 = 'Pink Forest'
s2 = 'Pink Forrest'
if bool(re.search(s1,s2))==True:
   print 'Strings match'
else:
   print 'Strings do not match'
This gives the output
Strings do not match
What is pytest and what are its advantages?

Pytest is a test framework in python. To install pytest, we need to use the command pip install pytest. After installation, we can verify if python has been installed by the command pytest –version. The version of pytest shall be known.
Pytest can be used for creating and executing test cases. It can be used in wide
range testing API, UI, database and so on. The test file of pytest has a naming
convention that it starts with test_ or ends with _test keyword and every line of
code should be inside a method which should have a name starting with test
keyword. Also each method should have a unique name.
def test_f():
print("Tutorialspoint")
To run the above code, we need to move to the terminal and use the command py.test. However this will not give much details from an execution point of view. To get information on execution we should use the command py.test –v. Here v stands for verbose.
In order to print the console logs, we need to use the command py.test –v –s. Again, if we want to run tests from a specific pytest file, the command is py.test
<filename> -v.
The advantages of pytest framework are listed below −
Pytest is capable of executing multiple test cases simultaneously, thereby
reducing the execution duration.
Pytest is capable of executing multiple test cases simultaneously, thereby
reducing the execution duration.
Pytest is capable of skipping a test method from a group of test methods
during execution.
Pytest is capable of skipping a test method from a group of test methods
during execution.
Pytest is free and does not have licensing cost.
Pytest is free and does not have licensing cost.
Pytest is quick and easy to learn.
Pytest is quick and easy to learn.
Pytest can choose to run a particular test method or all the test methods of
a particular test file based on conditions.
Pytest can choose to run a particular test method or all the test methods of
a particular test file based on conditions.
Pytest is capable of skipping a few test methods out of all the test methods
during test execution.
Pytest is capable of skipping a few test methods out of all the test methods
during test execution.
Pytest can be used to test a wide range of applications on API, database and
so on.
Pytest can be used to test a wide range of applications on API, database and
so on.
java.util.regex.Matcher.appendReplacement()

The java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) method implements a non-terminal append-and-replace step.
Following is the declaration for java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) method.
public Matcher appendReplacement(StringBuffer sb, String replacement)

sb − The target string buffer.
sb − The target string buffer.
replacement − The replacement string.
replacement − The replacement string.
This matcher.
IllegalStateException − If no match has yet been attempted, or if the previous match operation failed.
IllegalStateException − If no match has yet been attempted, or if the previous match operation failed.
IllegalArgumentException − If the replacement string refers to a named-capturing group that does not exist in the pattern.
IllegalArgumentException − If the replacement string refers to a named-capturing group that does not exist in the pattern.
IndexOutOfBoundsException − If the replacement string refers to a capturing group that does not exist in the pattern.
IndexOutOfBoundsException − If the replacement string refers to a capturing group that does not exist in the pattern.
The following example shows the usage of java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) method.
package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
   private static String REGEX = "a*b";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {
      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      StringBuffer buffer = new StringBuffer();
      
      while(matcher.find()) {
         matcher.appendReplacement(buffer, REPLACE);
      }
      matcher.appendTail(buffer);
      System.out.println(buffer.toString());
   }
}
Let us compile and run the above program, this will produce the following result −
-foo-foo-foo-

 Print
 Add Notes
 Bookmark this page
Advanced Excel Statistical - STEYX Function

The STEYX function returns the standard error of the predicted y-value for each x in the regression. The standard error is a measure of the amount of error in the prediction of y for an individual x.
STEYX (known_y's, known_x's)

The equation for the standard error of the predicted y is −
$$\sqrt{\frac{1}{2}\left [ \sum \left ( y-\bar{y} \right )^2 - \frac{\left [ \sum \left ( x-\bar{x} \right )\left ( y-\bar{y} \right ) \right ]^2}{\sum \left ( x-\bar{x} \right )^2} \right ]}$$
Where x and y are the sample means AVERAGE (known_x’s) and AVERAGE (known_y’s), and n is the sample size.

The equation for the standard error of the predicted y is −
$$\sqrt{\frac{1}{2}\left [ \sum \left ( y-\bar{y} \right )^2 - \frac{\left [ \sum \left ( x-\bar{x} \right )\left ( y-\bar{y} \right ) \right ]^2}{\sum \left ( x-\bar{x} \right )^2} \right ]}$$
Where x and y are the sample means AVERAGE (known_x’s) and AVERAGE (known_y’s), and n is the sample size.
Arguments can either be numbers or names, arrays, or references that contain numbers.
Arguments can either be numbers or names, arrays, or references that contain numbers.
Logical values and text representations of numbers that you type directly into the list of arguments are counted.
Logical values and text representations of numbers that you type directly into the list of arguments are counted.
If an array or reference argument contains text, logical values, or empty cells, those values are ignored; however, cells with the value zero are included.
If an array or reference argument contains text, logical values, or empty cells, those values are ignored; however, cells with the value zero are included.
Arguments that are error values or text that cannot be translated into numbers cause errors.
Arguments that are error values or text that cannot be translated into numbers cause errors.
If known_y's and known_x's have a different number of data points, STEYX returns the #N/A error value.
If known_y's and known_x's have a different number of data points, STEYX returns the #N/A error value.
If known_y's and known_x's are empty or have less than three data points, STEYX returns the #DIV/0! error value.
Excel 2007, Excel 2010, Excel 2013, Excel 2016

    296 Lectures 
     146 hours 

 Arun Motoori

    56 Lectures 
     5.5 hours 

 Pavan Lalwani

    120 Lectures 
     6.5 hours 

 Inf Sid

    134 Lectures 
     8.5 hours 

 Yoda Learning

    46 Lectures 
     7.5 hours 

 William Fiset

    25 Lectures 
     1.5 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Check if a number can be expressed as a sum of consecutive numbers in C++

Here we will see if one number can be represented as sum of two or more consecutive numbers or not. Suppose a number is 12. This can be represented as 3+4+5.
There is a direct and easiest method to solve this problem. If a number is power of 2, then it cannot be expressed as sum of some consecutive numbers. There are two facts that we have to keep in mind.
Sum of any two consecutive numbers is odd, then one of them will be odd, another one is even.
Second fact is 2n = 2(n-1) + 2(n-1).
 Live Demo
#include <iostream>
using namespace std;
bool isSumofconsecutiveNumbers(int n) {
   if((n & (n-1)) && n){
      return true;
   } else {
      return false;
   }
}
int main() {
   int num = 36;
   if(isSumofconsecutiveNumbers(num)){
      cout << "Can be represented";
   } else {
      cout << "Cannot be represented";
   }
}
Can be represented
Jackson Annotations - @JsonRawValue

@JsonRawValue allows to serialize a text without escaping or without any decoration.
import java.io.IOException; 
import com.fasterxml.jackson.databind.ObjectMapper; 

public class JacksonTester {
   public static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper();
      try {
         Student student = new Student("Mark", 1, "{\"attr\":false}");    
         String jsonString = mapper 
            .writerWithDefaultPrettyPrinter() 
            .writeValueAsString(student); 
         System.out.println(jsonString); 
      }
      catch (IOException e) { 
         e.printStackTrace(); 
      }   
   }
}
class Student { 
   private String name; 
   private int rollNo; 
   private String json;  
   public Student(String name, int rollNo, String json){
      this.name = name; 
      this.rollNo = rollNo; 
      this.json = json; 
   }  
   public String getName(){ 
      return name; 
   } 
   public int getRollNo(){ 
      return rollNo; 
   } 
   public String getJson(){ 
      return json; 
   }  
}
{ 
   "name" : "Mark", 
   "rollNo" : 1, 
   "json" : {\"attr\":false} 
} 

import java.io.IOException; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.annotation.JsonRawValue; 

public class JacksonTester {
   public static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper(); 
      try {
         Student student = new Student("Mark", 1, "{\"attr\":false}");    
         String jsonString = mapper 
            .writerWithDefaultPrettyPrinter() 
            .writeValueAsString(student); 
         System.out.println(jsonString); 
      }
      catch (IOException e) { 
         e.printStackTrace(); 
      }   
   }
}
class Student { 
   private String name; 
   private int rollNo;
   @JsonRawValue  
   private String json;  
   public Student(String name, int rollNo, String json) {
      this.name = name; 
      this.rollNo = rollNo; 
      this.json = json; 
   }  
   public String getName(){ 
      return name; 
   } 
   public int getRollNo(){ 
      return rollNo; 
   } 
   public String getJson(){ 
      return json; 
   }  
} 
{ 
   "name" : "Mark", 
   "rollNo" : 1, 
   "json" : {"attr":false} 
}

 Print
 Add Notes
 Bookmark this page
editable=False - Django Built-in Field Validation - GeeksforGeeks

13 Feb, 2020
Built-in Field Validations in Django models are the validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. editable=False will make the field disappear from all forms including admin and ModelForm i.e., it can not be edited using any form. The field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation.
Syntax
field_name = models.Field(editable = False)
Illustration of editable=False using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options.
from django.db import modelsfrom django.db.models import Model# Create your models here.  class GeeksModel(Model):    geeks_field = models.CharField(                    max_length = 200,                      default = "GFG is best",                     editable = False                    )
After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance from Django admin interface. You can see that field doesn’t appear in admin interface. Hit Save.
Let us check in admin interface if the instance of model is created.Therefore, editable=False modifies the field so that it is not visible to admin interface.
editable=False is generally used to hide some fields such as some encrypted code or email address verification code etc from admin panel. To use editable in a field you must specify either of following settings:
null=True and blank=True, so that your field doesn’t give required error during model save.
default=value, this will also set the field to some value so that it doesn’t give suspicious errors to admin user.
NaveenArora
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Double ended priority queue in C++ Program

In this tutorial, we are going to create a double-ended priority queue using the set in c++.
Let's see the steps to create a double-ended queue.
Create a struct with a name as you wish.
Create a struct with a name as you wish.
Create a variable for the queue using the set.
Create a variable for the queue using the set.
size method that returns the size of the queue.
size method that returns the size of the queue.
is_empty method that returns whether the queue is empty or not.
is_empty method that returns whether the queue is empty or not.
insert method to insert a new element into the queue.
insert method to insert a new element into the queue.
get_start method that returns an element from the left side of the queue.
get_start method that returns an element from the left side of the queue.
get_end method that returns the element from the right side of the queue.
get_end method that returns the element from the right side of the queue.
delete_start method that deletes the first element from the left side.
delete_start method that deletes the first element from the left side.
delete_end method deletes the first element from the right side.
delete_end method deletes the first element from the right side.
Let's see the code.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
struct doubleEndedQueue {
   set<int> s;
   int size() {
      return s.size();
   }
   string is_empty() {
      return s.size() == 0 ? "True" : "False";
   }
   void insert(int x) {
      s.insert(x);
   }
   int get_start() {
      return *(s.begin());
   }
   int get_end() {
      return *(s.rbegin());
   }
   void delete_start() {
      if (s.size() == 0) {
         return;
      }  
      s.erase(s.begin());
   }
   void delete_end() {
      if (s.size() == 0) {
         return;
      }
      auto end = s.end();
      end--;
      s.erase(end);
   }
};
int main() {
   doubleEndedQueue d;
   cout << "is empty: " << d.is_empty() << endl;
   d.insert(1);
   d.insert(2);
   d.insert(3);
   d.insert(4);
   d.insert(5);
   cout << "is empty: " << d.is_empty() << endl;
   cout << "end: " << d.get_end() << endl;
   d.delete_end();
   cout << "end: " << d.get_end() << endl;
   cout << "start: " << d.get_start() << endl;
   d.delete_start();
   cout << "start: " << d.get_start() << endl;
   return 0;
}
If you run the above code, then you will get the following result.
is empty: True
is empty: False
end: 5
end: 4
start: 1
start: 2
If you have any queries in the tutorial, mention them in the comment section.
Python - Search Tree

A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties.The left sub-tree of a node has a key less than or equal to its parent node's key.The right sub-tree of a node has a key greater than to its parent node's key.Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree
left_subtree (keys)  ≤  node (key)  ≤  right_subtree (keys)

Searching for a value in a tree involves comparing the incoming value with the value exiting nodes. Here also we traverse the nodes from left to right and then finally with the parent. If the searched for value does not match any of the exiting value, then we return not found message, or else the found message is returned.
class Node:
   def __init__(self, data):
      self.left = None
      self.right = None
      self.data = data
# Insert method to create nodes
   def insert(self, data):
      if self.data:
         if data < self.data:
            if self.left is None:
               self.left = Node(data)
            else:
               self.left.insert(data)
            else data > self.data:
               if self.right is None:
                  self.right = Node(data)
               else:
                  self.right.insert(data)
         else:
            self.data = data
# findval method to compare the value with nodes
   def findval(self, lkpval):
      if lkpval < self.data:
         if self.left is None:
            return str(lkpval)+" Not Found"
         return self.left.findval(lkpval)
       else if lkpval > self.data:
            if self.right is None:
               return str(lkpval)+" Not Found"
            return self.right.findval(lkpval)
        else:
            print(str(self.data) + ' is found')
# Print the tree
   def PrintTree(self):
      if self.left:
         self.left.PrintTree()
      print( self.data),
      if self.right:
         self.right.PrintTree()
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
print(root.findval(7))
print(root.findval(14))
When the above code is executed, it produces the following result −
7 Not Found
14 is found
What is the size_t data type in C?

17 Jul, 2020
size_t is an unsigned integral data type which is defined in various header files such as:  
<stddef.h>, <stdio.h>, <stdlib.h>, <string.h>, <time.h>, <wchar.h>
It’s a type which is used to represent the size of objects in bytes and is therefore used as the return type by the sizeof operator. It is guaranteed to be big enough to contain the size of the biggest object the host system can handle. Basically the maximum permissible size is dependent on the compiler; if the compiler is 32 bit then it is simply a typedef(i.e., alias) for unsigned int but if the compiler is 64 bit then it would be a typedef for unsigned long long. The size_t data type is never negative.Therefore many C library functions like malloc, memcpy and strlen declare their arguments and return type as size_t. For instance,  
// Declaration of various standard library functions.  // Here argument of 'n' refers to maximum blocks that can be// allocated which is guaranteed to be non-negative.void *malloc(size_t n);  // While copying 'n' bytes from 's2' to 's1'// n must be non-negative integer.void *memcpy(void *s1, void const *s2, size_t n);  // strlen() uses size_t because the length of any string// will always be at least 0.size_t strlen(char const *s);
size_t or any unsigned type might be seen used as loop variable as loop variables are typically greater than or equal to 0.Note: When we use a size_t object, we have to make sure that in all the contexts it is used, including arithmetic, we want only non-negative values. For instance, the following program would definitely give the unexpected result:  
// C program to demonstrate that size_t or// any unsigned int type should be used // carefully when used in a loop.#include<stdio.h>  #define N 10  int main(){    int a[N];      // This is fine.    for (size_t n = 0; n < N; ++n) {        a[n] = n;    }              // But reverse cycles are tricky for unsigned     // types as they can lead to infinite loops.    for (size_t n = N-1; n >= 0; --n)        printf("%d ", a[n]);}
Output
Infinite loop and then segmentation fault

This article is contributed by Shubham Bansal. 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. 
jflopezfernandez
prathusingal
cpp-data-types
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Python – 68-95-99.7 rule in Statistics

01 Sep, 2021
The Empirical Rule(also called the 68-95-99.7 Rule or the Three Sigma Rule) states that for any normal distribution, we have the following observations :
68% of the observed values lie between 1 standard deviation around the mean : 
95% of the observed values lie between 2 standard deviations around the mean : 
99.7% of the observed values lie between 3 standard deviation around the mean : 
Below is a standard normal distribution graph with (mean = 0 and standard deviation = 1), illustrating the Empirical Rule.
We, can verify this using functions provided by Python’s SciPy module.
We can use the cdf() function of the scipy.stats.norm module to calculate the cumulative probability(area under a distribution curve).
Syntax : cdf(x, mean, SD)Parameters :
x : value up to which cumulative probability is to be calculated
mean : mean of the distribution
SD : standard deviation of the distribution
Below is the implementation :
import matplotlib.pyplot as pltimport numpy as npfrom scipy.stats import norm # setting the values of# mean and S.D.mean = 0SD = 1 # value of cdf between one, two# and three S.D. around the meanone_sd = norm.cdf(SD, mean, SD) - norm.cdf(-SD, mean, SD)two_sd = norm.cdf(2 * SD, mean, SD) - norm.cdf(-2 * SD, mean, SD)three_sd = norm.cdf(3 * SD, mean, SD) - norm.cdf(-3 * SD, mean, SD) # printing the value of fractions# within each bandprint("Fraction of values within one SD =", one_sd)print("Fraction of values within two SD =", two_sd)print("Fraction of values within three SD =", three_sd)
Output :
Fraction of values within one SD = 0.6826894921370859
Fraction of values within two SD = 0.9544997361036416
Fraction of values within three SD = 0.9973002039367398

Hence, we see that the fraction of values are almost equal to 0.65, 0.95 and 0.997. Thus, the empirical Rule is verified.
surinderdawra388
data-science
Probability
Python
Probability
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Index.duplicated()

16 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.duplicated() function Indicate duplicate index values. Duplicated values are indicated as True values in the resulting array. Either all duplicates, all except the first, or all except the last occurrence of duplicates can be indicated.
Syntax: Index.duplicated(keep=’first’)
Parameters :keep : {‘first’, ‘last’, False}, default ‘first’The value or values in a set of duplicates to mark as missing.-> ‘first’ : Mark duplicates as True except for the first occurrence.-> ‘last’ : Mark duplicates as True except for the last occurrence.-> False : Mark all duplicates as True.
Returns : numpy.ndarray
Example #1: Use Index.duplicated() function to indicate all the duplicated value in the Index except the first one.
# importing pandas as pdimport pandas as pd  # Creating the Indexidx = pd.Index(['Labrador', 'Beagle', 'Labrador',                       'Lhasa', 'Husky', 'Beagle'])  # Print the Indexidx
Output :
Let’s find if a value present in Index is a duplicate value or unique.
# Identify the duplicated values except the firstidx.duplicated(keep ='first')
Output :As we can see in the output, the Index.duplicated() function has marked all the occurrence of duplicate value as True except the first occurrence. Example #2: Use Index.duplicated() function to identify all the duplicate values. here all the duplicate values will be marked as True
# importing pandas as pdimport pandas as pd  # Creating the Indexidx = pd.Index([100, 50, 45, 100, 12, 50, None])  # Print the Indexidx
Output :
Let’s identify all the duplicated values in the Index.
Note : We are having NaN values in the Index.
# Identify all duplicated occurrence of valuesidx.duplicated(keep = False)
Output :
The function has marked all the duplicate value as True. It has also treated the single occurrence of NaN value as unique and has marked it false.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.count() in Python

10 Oct, 2019
numpy.core.defchararray.count(arr, substring, start=0, end=None): Counts for the non-overlapping occurrence of sub-string in the specified range.
Parameters:arr : array-like or string to be searched.substring : substring to search for.start, end : [int, optional] Range to search in.
Returns : An integer array with the number of non-overlapping occurrences of sub-string.
Code #1:
# Python Program illustrating # numpy.char.count() method   import numpy as np   # 2D array arr = ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz']  print ("arr : ", arr)  print ("Count of 'tt'", np.char.count(arr, 'tt'))print ("Count of 'tt'", np.char.count(arr, 'tt', start = 0))print ("Count of 'tt'", np.char.count(arr, 'tt', start = 8))
Output:
arr :  ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz']
Count of 'tt' [2 2 1 0]
Count of 'tt' [2 2 1 0]
Count of 'tt' [1 2 1 0]

 Code #2:
# Python Program illustrating # numpy.char.count() method import numpy as np   # 2D array arr = ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz']  print ("arr : ", arr)  print ("Count of 'Aa'", np.char.count(arr, 'Aa'))print ("Count of 'Aa'", np.char.count(arr, 'Aa', start = 8))
Output:
arr :  ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz']

Count of 'Aa' [1 1 1 1]
Count of 'Aa' [1 0 0 0]

Akanksha_Rai
Python numpy-String Operation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Program to find uncommon elements in two arrays - JavaScript

Let’s say, we have two arrays of numbers −
const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];
We are required to write a JavaScript function that takes in two such arrays and returns the element from arrays that are not common to both.
Let’s write the code for this function −
Following is the code −
const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];
const unCommonArray = (first, second) => {
   const res = [];
   for(let i = 0; i < first.length; i++){
      if(second.indexOf(first[i]) === -1){
         res.push(first[i]);
      }
   };
   for(let j = 0; j < second.length; j++){
      if(first.indexOf(second[j]) === -1){
         res.push(second[j]);
      };
   };
   return res;
};
console.log(unCommonArray(arr1, arr2));
Following is the output in the console −
[ 6, 5, 1 ]
Remove Leading Zeros From String in Java

There are many approaches to remove leading zeroes from a string in Java. Here we will use some basic functions of String and Arrays class which to remove leading zeroes from a string.
So this approach proceed as first convert string to a character array so that evaluation of each character in string becomes simpler. Now it seems simple that compare each character and find first non zero characters. But here is a constraint that in Java that array doesn't have equals method to compare its value so here we will use valueOf() method of String class to compare each character.
Now we get the position of first non zero digit in our String the only thing remaining is to trim our array upto first non zero digit position. For this use copyOfRange() method which takes three arguments one is original array second is from a position where a copy is to be started and third is to position upto which copy is to be done.
public class RemoveLeadingZeroes {
   public static void main(String[] args) {
      String str = "00099898979";
      int arrayLength = 0;
      char[] array = str.toCharArray();
      arrayLength = array.length;
      int firstNonZeroAt = 0;
      for(int i=0; i<array.length; i++) {
         if(!String.valueOf(array[i]).equalsIgnoreCase("0")) {
            firstNonZeroAt = i;
            break;
         }
      }
      System.out.println("first non zero digit at : " +firstNonZeroAt);
      char [] newArray = Arrays.copyOfRange(array, firstNonZeroAt,arrayLength);
      String resultString = new String(newArray);
      System.out.println(resultString);
   }
}
myCSV.csv file created with following text
first non zero digit at : 3
99898979
How to set the left padding of an element with JavaScript?

Use the paddingLeft property in JavaScript to set the left padding. You can try to run the following code to return the left padding of an element with JavaScript −
<!DOCTYPE html>
<html>
   <head>
      <style>
         #box {
            border: 2px solid #FF0000;
            width: 150px;
            height: 70px;
         }
      </style>
   </head>

   <body>
      <div id = "box">This is demo text.</div>
      <br><br>
      <button type = "button" onclick = "display()">Left padding</button>
      <script>
         function display() {
            document.getElementById("box").style.paddingLeft = "100px";
         }
      </script>
   </body>
</html>
Java Examples - Use Enumeration to display HashTable

How to use enumeration to display contents of HashTable ?
Following example uses hasMoreElements & nestElement Methods of Enumeration Class to display the contents of the HashTable.
import java.util.Enumeration;
import java.util.Hashtable;

public class Main {
   public static void main(String[] args) {
      Hashtable ht = new Hashtable();
      ht.put("1", "One");
      ht.put("2", "Two");
      ht.put("3", "Three");
      Enumeration e = ht.elements();
      
      while(e.hasMoreElements()) {
         System.out.println(e.nextElement());
      }
   }
}
The above code sample will produce the following result.
Three
Two
One

 Print
 Add Notes
 Bookmark this page
Scala Collections - HashSet

Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. HashSet implements immutable sets and uses hash table. Elements insertion order is not preserved.
The following is the syntax for declaring an HashSet variable.
var z : HashSet[String] = HashSet("Zara","Nuha","Ayan")

Here, z is declared as an hash-set of Strings which has three members. Values can be added by using commands like the following −
var myList1: HashSet[String] = myList + "Naira";

Below is an example program of showing how to create, initialize and process HashSet −
import scala.collection.immutable.HashSet
object Demo {
   def main(args: Array[String]) = {
      var mySet: HashSet[String] = HashSet("Zara","Nuha","Ayan");
      // Add an element
      var mySet1: HashSet[String] = mySet + "Naira";
      // Remove an element
      var mySet2: HashSet[String] = mySet - "Nuha";
      // Create empty set
      var mySet3: HashSet[String] = HashSet.empty[String];
      println(mySet);
      println(mySet1);
      println(mySet2);
      println(mySet3);	  
   }
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

HashSet(Zara, Nuha, Ayan)
HashSet(Zara, Nuha, Ayan, Naira)
HashSet(Zara, Ayan)
HashSet()


    82 Lectures 
     7 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    76 Lectures 
     5.5 hours 

 Bigdata Engineer

    69 Lectures 
     7.5 hours 

 Bigdata Engineer

    46 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page