title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to Get Started with Spark NLP in 2 Weeks — Part I | by Mustafa Aytuğ Kaya | Towards Data Science
If you want to make a head start in enterprise NLP, but have no clue about Spark, this article is for you. I have seen many colleagues wanting to step to this domain but disheartened due to the initial learning overhead that comes with Spark. It may seem inconspicuous at first glance since Spark code is a bit different than your regular Python script. However, Spark and Spark NLP basics aren’t really hard to learn. If you axiomatically accept this assertion, I will show you how easy the basics are and will provide a road map to pave the way to learn key elements, which will satisfy most use cases of an intermediate level practitioner. Due to impeccable modularity that comes with Spark NLP pipelines, for an average learner, -mark my words- two weeks will be enough to build basic models. Roll up your sleeves, here we start! Why Spark NLP?Supply and Demand is the answer: It Is The Most Widely Used Library In Enterprises! Here are a few reasons why. Common NLP packages today have been designed by academics and they favor ease of prototyping over runtime performance, eclipsing scalability, error handling, target frugal memory consumption and code reuse. Although some libraries like ‘the industrial-strength NLP library — spaCy’ might be considered an exception (since they are designed to get things done rather than doing research), they may fall short of enterprise targets when it comes to dealing with data in volume. We are going to have a different strategy here. Rather than following the crowds in the routine, we will use basic libraries to brush up ‘basics’ and then jump directly to address the enterprise sector. Our final aim is to target the niche by building continental pipelines, which are impossible to resolve with standard libraries, albeit their capacity in their league. If you are not convinced yet, please read this article for benchmarking and comparison with spaCy, which will give you five good reasons to start with Spark NLP. First of all Spark NLP has the innate trait of scalability it inherits from Spark, which was primarily used for distributed applications, it is designed to be scalable. Spark NLP benefits from this since it can scale on any Spark cluster as well as on-premise and with any cloud provider. Furthermore, Spark NLP optimizations are done in such a way that it could run orders of magnitude faster than what the inherent design limitations of legacy libraries allow. It provides the concepts of annotators and it includes more than what other NLP libs include. It includes sentence detection, tokenization, stemming, lemmatization, POS Tagger, NER, dependency parse, text matcher, date matcher, chunking, context-aware spell checking, sentiment detector, pre-trained models, and training models with very high accuracy according to academic peer-reviewed results. Spark NLP also includes production-ready implementation of BERT embeddings for named entity recognition. For example, it makes much fewer errors on NER compared to spaCy, which we tested in the second part of this article. Also, worthy of notice, Spark NLP includes features that provide full Python API, supports training on GPU, user-defined deep learning networks, Spark, and Hadoop. The library comes with a production-ready implementation of BERT embeddings and uses transfer learning for data extraction. Transfer learning is a highly-effective method of extracting data that can leverage even small amounts of data. As a result, there’s no need to collect large amounts of data to train SOTA models. Also, John Snow labs Slack channel provides top tier support that is beneficial because developers and new learners tend to band together and create resources that every one of them can benefit from. You will get answers to your questions right from the developers with dedication. I have been there a few times, can attest that they are quick and accurate in their response. Additionally, anyone finding themselves stuck can quickly get help from people that have had similar problems through Stack Overflow or similar platforms. Famous “Facts” About Spark That Are Wrong - Spark is cluster computing so it can’t be run on local machines Wrong! You can run Spark on your local machine, and each CPU core will be used to the core! That’s how it looks like when Spark NLP is in action: What’s even more, you can run Spark on GPU. - Spark is yet another language to learn! Well, if you know SQL, PySpark and Spark NLP is not going to feel like another language at all. SQL and Regex are all languages on their own, but it wasn’t hard to learn their basics, right? - Spark is built for big data, so Spark NLP is only good for big data. Yes, there is a significant overhead used for Spark internals, but Spark NLP introduces a ‘Light Pipeline’ for smaller datasets. At first, Spark seems like another challenging language to learn. Spark isn’t the easiest library to comprehend, but what we will be doing in the NLP domain has been skillfully crafted in Spark NLP’s infrastructure provided by a simple API that can be easily interacted with. While being one of the sharpest pencils in a data scientist’s toolbox, Pandas uses only a single CPU core, and in essence, it is not fast or robust enough to handle bigger datasets. Spark was designed to hurdle those deficiencies using cluster computing, and you can even run it on your local machine, assigning as many CPU cores as you want! Unfortunately, even though it runs on a local machine, pip install Pyspark is not enough to set it up, and a series of dependencies must be installed on PC and Mac. For those who want to jump into action as quickly as possible, I recommend the use of Google Colab. 1) Setting up on Mac or LinuxTo utilize Spark NLP, Apache Spark version 2.4.3 and higher must be installed. Assuming that you haven’t installed Apache Spark yet, let’s start with Java installation at first. Just go to the official website and from “Java SE Development Kit 8u191”, and install JDK 8. A necessary command-line script can be found in detail here. 2) Setting up Spark on a PC can be a little bit tricky. Having tried many methods, I found this article to be the only one that works. It also includes a clear and concise video. In addition to the provided documentation, this blog page also helped me. 3) Unless you have to run Spark on your local machine, the easiest way to get started with PySpark is using Google Colab. Since it is essentially a Jupyter Notebook that runs on Google server, you don’t need to install anything in our system locally. To run spark in Colab, first, we need to install all the dependencies in the Colab environment such as Apache Spark 2.3.2 with Hadoop 2.7, Java 8, and Findspark to locate the spark in the system. Please refer to this article for further details. import os# Install java! apt-get install -y openjdk-8-jdk-headless -qq > /dev/nullos.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64"os.environ["PATH"] = os.environ["JAVA_HOME"] + "/bin:" + os.environ["PATH"]! java -version# Install pyspark! pip install --ignore-installed -q pyspark==2.4.4# Install Spark NLP! pip install --ignore-installed -q spark-nlp==2.4.5 For PC users who don’t want to run their notebooks on Colab, I recommend installing Spark NLP on a dual boot Linux system or using WSL 2, however, this benchmarking article reflects some performance loss with WSL 2. To be more precise, I had my best Spark NLP experience after a dual boot Ubuntu 20.04 installation. Day 2: Spark Basics, RDD Structure, and NLP Baby Steps with Spark As previously mentioned, Apache Spark is a distributed cluster computing framework that is highly efficient for large data sets using in-memory computations for lightning-fast data processing. It is also considered to be more efficient than MapReduce for the complex application running on Disk. While libraries like pandas are adequate for most everyday operations, big data requires a cluster computing framework due to the volume, variety, and velocity, which are three defining properties or dimensions of big data. At the center of Spark is the Spark Core — the foundation of the overall project, on top of which the rest of Spark libraries are built. Spark SQL lets you query structured data inside Spark programs, using either SQL or a familiar DataFrame API. MLlib fits into Spark’s APIs and interoperates with NumPy in Python and R libraries. You can use any Hadoop data source, making it easy to plug into Hadoop workflows. Spark excels at iterative computation, enabling MLlib to run fast — up to 100x faster than MapReduce. Spark Mllib contains the legacy API built on top of RDDs. Although I find Spark Mllib and RDD structure easier to use as a Python practitioner, as of Spark 2.0, the RDD-based APIs in the Spark.MLlib package has entered maintenance mode. The primary Machine Learning API for Spark is now the DataFrame-based API in the Spark ML package. Transformations create new RDDs and actions to perform calculations. Lambda, Map, and Filter are some of the basic functions. Real datasets are generally key, value pairs similar to Python dictionaries but are represented like tuples. Please observe the code below for creating bigrams and word counts to see how similar to Python code it is. I would highly recommend this course for further details. import resentences = sc.textFile(“ulyses.txt”) \ .glom() \ .map(lambda x: “ “.join(x)) \ .flatMap(lambda x: x.split(“.”)).map(lambda x: re.sub(‘[^a-zA-Z\s]’,’’,x))bigrams = sentences.map(lambda x:x.split()) \ .flatMap(lambda x: [((x[i],x[i+1]),1) for i in range(0,len(x)-1) \ if all([x[i].lower() not in stop_words,x[i+1].lower() not in stop_words])])freq_bigrams = bigrams.reduceByKey(lambda x,y:x+y) \ .map(lambda x:(x[1],x[0])) \ .sortByKey(False)In [1]:freq_bigrams.take(10)Out[1]:(1, ('Author', 'James')), (1, ('Joyce', 'Release')), (1, ('EBook', 'Last')), (1, ('Last', 'Updated')), (1, ('December', 'Language')), (1, ('English', 'Character')), (1, ('Character', 'set')), (1, ('set', 'encoding')), (1, ('UTF', 'START')), (1, ('II', 'III'))] # word count exampletext_file = sc.textFile(“example_text1.txt”)counts_rdd = text_file.flatMap(lambda line: line.split(“ “)) \ .map(lambda word: (word, 1)) \ .reduceByKey(lambda a, b: a + b)# print the word frequencies in descending ordercounts_rdd.map(lambda x: (x[1], x[0])) \ .sortByKey(ascending=False)\ .collect()[:10] Output Out [3]: [(988, 'the'), (693, 'and'), (623, 'of'), (604, 'to'), (513, 'I'), (450, 'a'), (441, 'my'), (387, 'in'), (378, 'HAMLET'), (356, 'you')] Day 3/4: Feature Engineering / Cleaning Data with Pyspark Spark ML provides higher-level API built on top of DataFrames for constructing ML pipelines, standardizing APIs for machine learning algorithms to make it easier to combine multiple algorithms into a single workflow. Here we will cover the key concepts introduced by the Spark ML API. Machine learning steps can be applied to from Spark SQL to support a variety of data types under a unified Dataset concept. A SchemaRDD can be created either implicitly or explicitly from a regular RDD. A Transformer is an abstraction which includes feature transformers and learned models, implementing a method transform() which converts one SchemaRDD into another, generally by appending one or more columns. An Estimator abstracts the concept of a learning algorithm or any algorithm which fits or trains on data, implementing a method fit() which accepts a SchemaRDD and produces a Transformer. For example, a learning algorithm such as LogisticRegression is an Estimator, and calling fit() trains a LogisticRegressionModel, which is a Transformer. In machine learning, it is common to run a sequence of algorithms to process and learn from data such as splitting each document text into words, converting words into a numerical feature vector, and training a prediction model using the feature vectors and labels. Spark ML represents such workflows as Pipelines, which consist of a sequence of Transformers and Estimators to be run in a specific order, calling transform() and fit() methods respectively, to produce a Transformer (which becomes part of the PipelineModel, or fitted Pipeline), and that Transformer’s transform() method is called on the dataset. A Pipeline is an Estimator. Thus, after a Pipeline’s fit() method runs, it produces a PipelineModel which is a Transformer. Once the PipelineModel’s transform() method is called on a test dataset, the data passes through the Pipeline in order, updating the data set as each stage’s transform() method updates it and passes it to the next stage. Pipelines and PipelineModels help to ensure that training and test data go through identical feature processing steps. Below is an example of a pipeline model. Please note that data preprocessing is carried out on a Pandas Dataframe. #define regex pattern for preprocessingpat1 = r’@[A-Za-z0–9_]+’pat2 = r’https?://[^ ]+’combined_pat = r’|’.join((pat1,pat2))www_pat = r’www.[^ ]+’negations_dic = {“isn’t”:”is not”, “aren’t”:”are not”, “wasn’t”:”was not”, “weren’t”:”were not”, “haven’t”:”have not”,”hasn’t”:”has not”,”hadn’t”:”had not”,”won’t”:”will not”, “wouldn’t”:”would not”, “don’t”:”do not”, “doesn’t”:”does not”,”didn’t”:”did not”, “can’t”:”can not”,”couldn’t”:”could not”,”shouldn’t”:”should not”,”mightn’t”:”might not”, “mustn’t”:”must not”}neg_pattern = re.compile(r’\b(‘ + ‘|’.join(negations_dic.keys()) + r’)\b’)def pre_processing(column): first_process = re.sub(combined_pat, ‘’, column) second_process = re.sub(www_pat, ‘’, first_process) third_process = second_process.lower() fourth_process = neg_pattern.sub(lambda x:\ negations_dic[x.group()], third_process) result = re.sub(r’[^A-Za-z ]’,’’,fourth_process) return result.strip()df[‘text’]=df.iloc[:,:].text.apply(lambda x: pre_processing(x))df=df[~(df[‘text’]==’’)]# shuffle the datadf = df.sample(frac=1).reset_index(drop=True)# set the random seed and split train and test with 99 to 1 rationp.random.seed(777)msk = np.random.rand(len(df)) < 0.99train = df[msk].reset_index(drop=True)test = df[~msk].reset_index(drop=True)# save both train and test as CSV filestrain.to_csv(‘pyspark_train_data.csv’)test.to_csv(‘pyspark_test_data.csv’) tokenizer = [Tokenizer(inputCol='text',outputCol='words')]ngrams = [NGram(n=i, inputCol='words', outputCol='{}_grams'.format(i)) for i in range(1,4)]cv =[CountVectorizer(vocabSize=5460,inputCol='{}_grams'.format(i),\ outputCol='{}_tf'.format(i)) for i in range(1,4)]idf = [IDF(inputCol='{}_tf'.format(i),\ outputCol='{}_tfidf'.format(i), minDocFreq=5) \ for i in range(1,4)]assembler = [VectorAssembler(inputCols=['{}_tfidf'.format(i)\ for i in range(1,4)], outputCol='features')]label_stringIdx = [StringIndexer(inputCol='sentiment', \ outputCol='label')]lr = [LogisticRegression()]pipeline = Pipeline(stages=tokenizer+ngrams+cv+idf+assembler+\ label_stringIdx+lr)model = pipeline.fit(train_set)predictions = model.transform(test_set) In PySpark, interactions with SparkSQL through DataFrame API and SQL queries are priority subjects to learn. Pyspark.sql module must be perused for a better understanding of basic operations. DataFrame transformations and actions are not too hard to construct programmatically and operations on DataFrames can also be done using SQL queries. If you have time to take only one course, please spend it on Feature Engineering with Pyspark course by John Hogue. This course is also recommended, time permitting (Day 5). Day 6/7: Practice Makes Perfect The best way to learn is practice. You will need a hardened skill set for next week. Try to deep dive into Pyspark modules, since you will be extensively using them. To re-iterate “First Steps With PySpark and Big Data Processing”, please follow these exercises. It is a recommended practice to download some datasets from Kaggle or Project Gutenberg and solve pre-processing problems, as well as others. Please follow this excellent notebook from the creators of Spark NLP. For additional resources, please observe this notebook and this article. Next Up: Part II — How to Wrap Your Head Around Spark NLP. In this part, we will understand “Annotators /Transformers in Spark NLP” and emphasize “Text Preprocessing with Spark”, “Pretrained Models” and “Text Classifiers” using numerous notebooks. Moreover, we will run a complete pipeline with spaCy and SparkNLP and compare the results.
[ { "code": null, "e": 1006, "s": 172, "text": "If you want to make a head start in enterprise NLP, but have no clue about Spark, this article is for you. I have seen many colleagues wanting to step to this domain but disheartened due to the initial learning overhead that comes with Spark. It may seem inconspicuous at first glance since Spark code is a bit different than your regular Python script. However, Spark and Spark NLP basics aren’t really hard to learn. If you axiomatically accept this assertion, I will show you how easy the basics are and will provide a road map to pave the way to learn key elements, which will satisfy most use cases of an intermediate level practitioner. Due to impeccable modularity that comes with Spark NLP pipelines, for an average learner, -mark my words- two weeks will be enough to build basic models. Roll up your sleeves, here we start!" }, { "code": null, "e": 1608, "s": 1006, "text": "Why Spark NLP?Supply and Demand is the answer: It Is The Most Widely Used Library In Enterprises! Here are a few reasons why. Common NLP packages today have been designed by academics and they favor ease of prototyping over runtime performance, eclipsing scalability, error handling, target frugal memory consumption and code reuse. Although some libraries like ‘the industrial-strength NLP library — spaCy’ might be considered an exception (since they are designed to get things done rather than doing research), they may fall short of enterprise targets when it comes to dealing with data in volume." }, { "code": null, "e": 1979, "s": 1608, "text": "We are going to have a different strategy here. Rather than following the crowds in the routine, we will use basic libraries to brush up ‘basics’ and then jump directly to address the enterprise sector. Our final aim is to target the niche by building continental pipelines, which are impossible to resolve with standard libraries, albeit their capacity in their league." }, { "code": null, "e": 3388, "s": 1979, "text": "If you are not convinced yet, please read this article for benchmarking and comparison with spaCy, which will give you five good reasons to start with Spark NLP. First of all Spark NLP has the innate trait of scalability it inherits from Spark, which was primarily used for distributed applications, it is designed to be scalable. Spark NLP benefits from this since it can scale on any Spark cluster as well as on-premise and with any cloud provider. Furthermore, Spark NLP optimizations are done in such a way that it could run orders of magnitude faster than what the inherent design limitations of legacy libraries allow. It provides the concepts of annotators and it includes more than what other NLP libs include. It includes sentence detection, tokenization, stemming, lemmatization, POS Tagger, NER, dependency parse, text matcher, date matcher, chunking, context-aware spell checking, sentiment detector, pre-trained models, and training models with very high accuracy according to academic peer-reviewed results. Spark NLP also includes production-ready implementation of BERT embeddings for named entity recognition. For example, it makes much fewer errors on NER compared to spaCy, which we tested in the second part of this article. Also, worthy of notice, Spark NLP includes features that provide full Python API, supports training on GPU, user-defined deep learning networks, Spark, and Hadoop." }, { "code": null, "e": 3708, "s": 3388, "text": "The library comes with a production-ready implementation of BERT embeddings and uses transfer learning for data extraction. Transfer learning is a highly-effective method of extracting data that can leverage even small amounts of data. As a result, there’s no need to collect large amounts of data to train SOTA models." }, { "code": null, "e": 4239, "s": 3708, "text": "Also, John Snow labs Slack channel provides top tier support that is beneficial because developers and new learners tend to band together and create resources that every one of them can benefit from. You will get answers to your questions right from the developers with dedication. I have been there a few times, can attest that they are quick and accurate in their response. Additionally, anyone finding themselves stuck can quickly get help from people that have had similar problems through Stack Overflow or similar platforms." }, { "code": null, "e": 4281, "s": 4239, "text": "Famous “Facts” About Spark That Are Wrong" }, { "code": null, "e": 4347, "s": 4281, "text": "- Spark is cluster computing so it can’t be run on local machines" }, { "code": null, "e": 4493, "s": 4347, "text": "Wrong! You can run Spark on your local machine, and each CPU core will be used to the core! That’s how it looks like when Spark NLP is in action:" }, { "code": null, "e": 4537, "s": 4493, "text": "What’s even more, you can run Spark on GPU." }, { "code": null, "e": 4579, "s": 4537, "text": "- Spark is yet another language to learn!" }, { "code": null, "e": 4770, "s": 4579, "text": "Well, if you know SQL, PySpark and Spark NLP is not going to feel like another language at all. SQL and Regex are all languages on their own, but it wasn’t hard to learn their basics, right?" }, { "code": null, "e": 4841, "s": 4770, "text": "- Spark is built for big data, so Spark NLP is only good for big data." }, { "code": null, "e": 4970, "s": 4841, "text": "Yes, there is a significant overhead used for Spark internals, but Spark NLP introduces a ‘Light Pipeline’ for smaller datasets." }, { "code": null, "e": 5246, "s": 4970, "text": "At first, Spark seems like another challenging language to learn. Spark isn’t the easiest library to comprehend, but what we will be doing in the NLP domain has been skillfully crafted in Spark NLP’s infrastructure provided by a simple API that can be easily interacted with." }, { "code": null, "e": 5854, "s": 5246, "text": "While being one of the sharpest pencils in a data scientist’s toolbox, Pandas uses only a single CPU core, and in essence, it is not fast or robust enough to handle bigger datasets. Spark was designed to hurdle those deficiencies using cluster computing, and you can even run it on your local machine, assigning as many CPU cores as you want! Unfortunately, even though it runs on a local machine, pip install Pyspark is not enough to set it up, and a series of dependencies must be installed on PC and Mac. For those who want to jump into action as quickly as possible, I recommend the use of Google Colab." }, { "code": null, "e": 6215, "s": 5854, "text": "1) Setting up on Mac or LinuxTo utilize Spark NLP, Apache Spark version 2.4.3 and higher must be installed. Assuming that you haven’t installed Apache Spark yet, let’s start with Java installation at first. Just go to the official website and from “Java SE Development Kit 8u191”, and install JDK 8. A necessary command-line script can be found in detail here." }, { "code": null, "e": 6468, "s": 6215, "text": "2) Setting up Spark on a PC can be a little bit tricky. Having tried many methods, I found this article to be the only one that works. It also includes a clear and concise video. In addition to the provided documentation, this blog page also helped me." }, { "code": null, "e": 6719, "s": 6468, "text": "3) Unless you have to run Spark on your local machine, the easiest way to get started with PySpark is using Google Colab. Since it is essentially a Jupyter Notebook that runs on Google server, you don’t need to install anything in our system locally." }, { "code": null, "e": 6965, "s": 6719, "text": "To run spark in Colab, first, we need to install all the dependencies in the Colab environment such as Apache Spark 2.3.2 with Hadoop 2.7, Java 8, and Findspark to locate the spark in the system. Please refer to this article for further details." }, { "code": null, "e": 7337, "s": 6965, "text": "import os# Install java! apt-get install -y openjdk-8-jdk-headless -qq > /dev/nullos.environ[\"JAVA_HOME\"] = \"/usr/lib/jvm/java-8-openjdk-amd64\"os.environ[\"PATH\"] = os.environ[\"JAVA_HOME\"] + \"/bin:\" + os.environ[\"PATH\"]! java -version# Install pyspark! pip install --ignore-installed -q pyspark==2.4.4# Install Spark NLP! pip install --ignore-installed -q spark-nlp==2.4.5" }, { "code": null, "e": 7653, "s": 7337, "text": "For PC users who don’t want to run their notebooks on Colab, I recommend installing Spark NLP on a dual boot Linux system or using WSL 2, however, this benchmarking article reflects some performance loss with WSL 2. To be more precise, I had my best Spark NLP experience after a dual boot Ubuntu 20.04 installation." }, { "code": null, "e": 7719, "s": 7653, "text": "Day 2: Spark Basics, RDD Structure, and NLP Baby Steps with Spark" }, { "code": null, "e": 8015, "s": 7719, "text": "As previously mentioned, Apache Spark is a distributed cluster computing framework that is highly efficient for large data sets using in-memory computations for lightning-fast data processing. It is also considered to be more efficient than MapReduce for the complex application running on Disk." }, { "code": null, "e": 8239, "s": 8015, "text": "While libraries like pandas are adequate for most everyday operations, big data requires a cluster computing framework due to the volume, variety, and velocity, which are three defining properties or dimensions of big data." }, { "code": null, "e": 8486, "s": 8239, "text": "At the center of Spark is the Spark Core — the foundation of the overall project, on top of which the rest of Spark libraries are built. Spark SQL lets you query structured data inside Spark programs, using either SQL or a familiar DataFrame API." }, { "code": null, "e": 8755, "s": 8486, "text": "MLlib fits into Spark’s APIs and interoperates with NumPy in Python and R libraries. You can use any Hadoop data source, making it easy to plug into Hadoop workflows. Spark excels at iterative computation, enabling MLlib to run fast — up to 100x faster than MapReduce." }, { "code": null, "e": 9091, "s": 8755, "text": "Spark Mllib contains the legacy API built on top of RDDs. Although I find Spark Mllib and RDD structure easier to use as a Python practitioner, as of Spark 2.0, the RDD-based APIs in the Spark.MLlib package has entered maintenance mode. The primary Machine Learning API for Spark is now the DataFrame-based API in the Spark ML package." }, { "code": null, "e": 9492, "s": 9091, "text": "Transformations create new RDDs and actions to perform calculations. Lambda, Map, and Filter are some of the basic functions. Real datasets are generally key, value pairs similar to Python dictionaries but are represented like tuples. Please observe the code below for creating bigrams and word counts to see how similar to Python code it is. I would highly recommend this course for further details." }, { "code": null, "e": 10292, "s": 9492, "text": "import resentences = sc.textFile(“ulyses.txt”) \\ .glom() \\ .map(lambda x: “ “.join(x)) \\ .flatMap(lambda x: x.split(“.”)).map(lambda x: re.sub(‘[^a-zA-Z\\s]’,’’,x))bigrams = sentences.map(lambda x:x.split()) \\ .flatMap(lambda x: [((x[i],x[i+1]),1) for i in range(0,len(x)-1) \\ if all([x[i].lower() not in stop_words,x[i+1].lower() not in stop_words])])freq_bigrams = bigrams.reduceByKey(lambda x,y:x+y) \\ .map(lambda x:(x[1],x[0])) \\ .sortByKey(False)In [1]:freq_bigrams.take(10)Out[1]:(1, ('Author', 'James')), (1, ('Joyce', 'Release')), (1, ('EBook', 'Last')), (1, ('Last', 'Updated')), (1, ('December', 'Language')), (1, ('English', 'Character')), (1, ('Character', 'set')), (1, ('set', 'encoding')), (1, ('UTF', 'START')), (1, ('II', 'III'))]" }, { "code": null, "e": 10616, "s": 10292, "text": "# word count exampletext_file = sc.textFile(“example_text1.txt”)counts_rdd = text_file.flatMap(lambda line: line.split(“ “)) \\ .map(lambda word: (word, 1)) \\ .reduceByKey(lambda a, b: a + b)# print the word frequencies in descending ordercounts_rdd.map(lambda x: (x[1], x[0])) \\ .sortByKey(ascending=False)\\ .collect()[:10]" }, { "code": null, "e": 10623, "s": 10616, "text": "Output" }, { "code": null, "e": 10849, "s": 10623, "text": "Out [3]: [(988, 'the'), (693, 'and'), (623, 'of'), (604, 'to'), (513, 'I'), (450, 'a'), (441, 'my'), (387, 'in'), (378, 'HAMLET'), (356, 'you')]" }, { "code": null, "e": 10907, "s": 10849, "text": "Day 3/4: Feature Engineering / Cleaning Data with Pyspark" }, { "code": null, "e": 11192, "s": 10907, "text": "Spark ML provides higher-level API built on top of DataFrames for constructing ML pipelines, standardizing APIs for machine learning algorithms to make it easier to combine multiple algorithms into a single workflow. Here we will cover the key concepts introduced by the Spark ML API." }, { "code": null, "e": 11395, "s": 11192, "text": "Machine learning steps can be applied to from Spark SQL to support a variety of data types under a unified Dataset concept. A SchemaRDD can be created either implicitly or explicitly from a regular RDD." }, { "code": null, "e": 11604, "s": 11395, "text": "A Transformer is an abstraction which includes feature transformers and learned models, implementing a method transform() which converts one SchemaRDD into another, generally by appending one or more columns." }, { "code": null, "e": 11946, "s": 11604, "text": "An Estimator abstracts the concept of a learning algorithm or any algorithm which fits or trains on data, implementing a method fit() which accepts a SchemaRDD and produces a Transformer. For example, a learning algorithm such as LogisticRegression is an Estimator, and calling fit() trains a LogisticRegressionModel, which is a Transformer." }, { "code": null, "e": 12559, "s": 11946, "text": "In machine learning, it is common to run a sequence of algorithms to process and learn from data such as splitting each document text into words, converting words into a numerical feature vector, and training a prediction model using the feature vectors and labels. Spark ML represents such workflows as Pipelines, which consist of a sequence of Transformers and Estimators to be run in a specific order, calling transform() and fit() methods respectively, to produce a Transformer (which becomes part of the PipelineModel, or fitted Pipeline), and that Transformer’s transform() method is called on the dataset." }, { "code": null, "e": 12904, "s": 12559, "text": "A Pipeline is an Estimator. Thus, after a Pipeline’s fit() method runs, it produces a PipelineModel which is a Transformer. Once the PipelineModel’s transform() method is called on a test dataset, the data passes through the Pipeline in order, updating the data set as each stage’s transform() method updates it and passes it to the next stage." }, { "code": null, "e": 13138, "s": 12904, "text": "Pipelines and PipelineModels help to ensure that training and test data go through identical feature processing steps. Below is an example of a pipeline model. Please note that data preprocessing is carried out on a Pandas Dataframe." }, { "code": null, "e": 14526, "s": 13138, "text": "#define regex pattern for preprocessingpat1 = r’@[A-Za-z0–9_]+’pat2 = r’https?://[^ ]+’combined_pat = r’|’.join((pat1,pat2))www_pat = r’www.[^ ]+’negations_dic = {“isn’t”:”is not”, “aren’t”:”are not”, “wasn’t”:”was not”, “weren’t”:”were not”, “haven’t”:”have not”,”hasn’t”:”has not”,”hadn’t”:”had not”,”won’t”:”will not”, “wouldn’t”:”would not”, “don’t”:”do not”, “doesn’t”:”does not”,”didn’t”:”did not”, “can’t”:”can not”,”couldn’t”:”could not”,”shouldn’t”:”should not”,”mightn’t”:”might not”, “mustn’t”:”must not”}neg_pattern = re.compile(r’\\b(‘ + ‘|’.join(negations_dic.keys()) + r’)\\b’)def pre_processing(column): first_process = re.sub(combined_pat, ‘’, column) second_process = re.sub(www_pat, ‘’, first_process) third_process = second_process.lower() fourth_process = neg_pattern.sub(lambda x:\\ negations_dic[x.group()], third_process) result = re.sub(r’[^A-Za-z ]’,’’,fourth_process) return result.strip()df[‘text’]=df.iloc[:,:].text.apply(lambda x: pre_processing(x))df=df[~(df[‘text’]==’’)]# shuffle the datadf = df.sample(frac=1).reset_index(drop=True)# set the random seed and split train and test with 99 to 1 rationp.random.seed(777)msk = np.random.rand(len(df)) < 0.99train = df[msk].reset_index(drop=True)test = df[~msk].reset_index(drop=True)# save both train and test as CSV filestrain.to_csv(‘pyspark_train_data.csv’)test.to_csv(‘pyspark_test_data.csv’)" }, { "code": null, "e": 15327, "s": 14526, "text": "tokenizer = [Tokenizer(inputCol='text',outputCol='words')]ngrams = [NGram(n=i, inputCol='words', outputCol='{}_grams'.format(i)) for i in range(1,4)]cv =[CountVectorizer(vocabSize=5460,inputCol='{}_grams'.format(i),\\ outputCol='{}_tf'.format(i)) for i in range(1,4)]idf = [IDF(inputCol='{}_tf'.format(i),\\ outputCol='{}_tfidf'.format(i), minDocFreq=5) \\ for i in range(1,4)]assembler = [VectorAssembler(inputCols=['{}_tfidf'.format(i)\\ for i in range(1,4)], outputCol='features')]label_stringIdx = [StringIndexer(inputCol='sentiment', \\ outputCol='label')]lr = [LogisticRegression()]pipeline = Pipeline(stages=tokenizer+ngrams+cv+idf+assembler+\\ label_stringIdx+lr)model = pipeline.fit(train_set)predictions = model.transform(test_set)" }, { "code": null, "e": 15843, "s": 15327, "text": "In PySpark, interactions with SparkSQL through DataFrame API and SQL queries are priority subjects to learn. Pyspark.sql module must be perused for a better understanding of basic operations. DataFrame transformations and actions are not too hard to construct programmatically and operations on DataFrames can also be done using SQL queries. If you have time to take only one course, please spend it on Feature Engineering with Pyspark course by John Hogue. This course is also recommended, time permitting (Day 5)." }, { "code": null, "e": 15875, "s": 15843, "text": "Day 6/7: Practice Makes Perfect" }, { "code": null, "e": 16423, "s": 15875, "text": "The best way to learn is practice. You will need a hardened skill set for next week. Try to deep dive into Pyspark modules, since you will be extensively using them. To re-iterate “First Steps With PySpark and Big Data Processing”, please follow these exercises. It is a recommended practice to download some datasets from Kaggle or Project Gutenberg and solve pre-processing problems, as well as others. Please follow this excellent notebook from the creators of Spark NLP. For additional resources, please observe this notebook and this article." } ]
Human Resources Datafication (Part 1) | by Michelle Venables | Towards Data Science
Michelle Venables, Data Scientist and Machine Learning Engineer What is the strategy that is best aligned with business activities and human capital? Human Resource (HR) strategy is the idea that sets a direction for all the key areas of HR. It is our increasing ability to use analytics to understand more about people, HR processes, and demographics. This includes activities with hiring, performance appraisals, development and compensation As data analysts/scientists in the HR space, we would develop a strategy to tackle HR goals and insights over the entire organization. We want to start off with Data we already have within the organization starting with our current employees. This might involve strengths and job descriptions across the organization. An example of this and a good solution would be to use an interactive organizational chart. Start by collecting everyones updated resume, continuing education history, performance appraisals, and projects completed. This gives you the ability to identify your current employees’ knowledge, skills and strengths. An interactive organizational chart can be a tool beyond the basic job descriptions and skills. Evaluating performance reviews allows management to determine when employees are willing and able to assume additional responsibility. When employees consistently rank high then its time to take on some more challenging work. This blog is meant to describe some tips when analyzing HR strategy and activities within the firm. There are a few KPI’s worth mentioning in the HR analytics space. The following 8 metrics are quantitatively evaluated. Talent Retention — The ability for an organization to retain its employees. This is normally a statistical measure and sometimes thought of as an employee’s loyalty to their company.Recruiting Effectiveness — there are a couple of ways organizations measure their recruiting effectiveness. A common statisical measure can be Time to Fill, Quality of Hire, Source of Hire, etc.Employee Performance — job rating scales are a common way to evaluate performance of employees, behavioral elements such as understanding job tasks and participation in decision making.Employee Movement — when an employee transfers from one organization to another and is also called the turnover rate. Similar to assessing the retention rate.Total Rewards — this is a tool that managers or employers keep track of in order to attract, motivate and retain employees.Learning and Development — training programs allow employees to grow and succeed within an organization. It allows employees to reach a higher level of skills in knowledge within the organization. These can be evaluated and monitored with performance reviews or with rating scaled (as stated before).Diversity and Inclusion — measuring and improving ideas and creativity. Attract and attain talented people in order to form strong teams.HR-to-employee ratios — delivery of services Talent Retention — The ability for an organization to retain its employees. This is normally a statistical measure and sometimes thought of as an employee’s loyalty to their company. Recruiting Effectiveness — there are a couple of ways organizations measure their recruiting effectiveness. A common statisical measure can be Time to Fill, Quality of Hire, Source of Hire, etc. Employee Performance — job rating scales are a common way to evaluate performance of employees, behavioral elements such as understanding job tasks and participation in decision making. Employee Movement — when an employee transfers from one organization to another and is also called the turnover rate. Similar to assessing the retention rate. Total Rewards — this is a tool that managers or employers keep track of in order to attract, motivate and retain employees. Learning and Development — training programs allow employees to grow and succeed within an organization. It allows employees to reach a higher level of skills in knowledge within the organization. These can be evaluated and monitored with performance reviews or with rating scaled (as stated before). Diversity and Inclusion — measuring and improving ideas and creativity. Attract and attain talented people in order to form strong teams. HR-to-employee ratios — delivery of services We want to collect and evaluate this data in order to define where we are as an organization in terms of HR. The culture and behaviors of employees makeup an organizations team atmosphere and it is HR’s job to build a strategy for success. I have gathered Human Resource data provided by Kaggle.com in order to show an evaluation of an organization. CLICK HERE FOR LINK The first step of a data science project is to make sure we clean and evaluate our data. Cleaning involves dealing with null values, assessing what data is currently available to us, and using different cleansing techniques to organize the structure of our data. Big, dirty, messy, and incompatible data sources can lead to ineffective analytical models. We want to understand our data and here are a few ways on how to do that: hr_data.shape Our output is 300 rows by 21 columns. hr_data.isna().sum() Checking for NA results and learning how to deal with them. One way might be to fillna with 0: hr_data = hr_data.fillna(0) After some basic cleaning techniques we can start analyzing and evaluating. I personally like using Seaborn and Matplotlib in order to visualize my data. After viewing our data columns, I believe that evaluating pay_rate might be beneficial. We might even want to predict newer employees pay_rate based on performance scores, position and other characteristics! Let’s take a look on our available data before trying to solve for new employees. chart = sns.barplot(x='performance_score', y= 'pay_rate', data=hr_data, palette='Set1', ci=None) chart.set_xticklabels(chart.get_xticklabels(),rotation=90) Make sure to import seaborn as sns before running your line of code. What can we analyze employee pay rates? I’d probably ask some questions about the “Needs Improvement” performance score... Why are these employees at a higher pay rate than employees that “Exceed” the employee performance scores. “Exceptional” seems accurate. chart = sns.barplot(x = 'position', y = 'pay_rate', data=hr_data, palette='Set1', ci = None) chart.set_xticklabels(chart.get_xticklabels(),rotation=90) Our second chart shows pay rates based on positions in the company. Obviously, President and CEO are at a higher pay_rate than other employees. The positions/pay_rates seem to be accurate as long as they align with your company’s HR strategy. Our next plot will help with analyzing some diversity within the organization. Diversity is a KPI when evaluating our Human Resource Strategy. Organizational diversity in the workplace refers to the total makeup of the employee workforce and the amount of diversity included. Diversity refers to differences in various defining personal traits such as age, gender, race, marital status, and many other secondary qualities. Take a look at some of our diversity evaluation bar plots below: It’s not much of a difference but on average males have a higher pay_rate than females. We binned our ages based on decades in order to evaluate diversification based on age. We can see that our ages ranges are pretty diverse. After cleaning our data and evaluating pay rate based on performance scores positions, and diversity measures you should have a good sense of what our data looks like. Before we get into our modeling you always want to clean and evaluate our data. Stay tuned for my next blog on predicting HR analytics and for references to my code click on my github link below! Human Resources Datafication (Part 2) HR_Project — Github link Medium Link References: [1] Bizfluent. “What Is Organizational Diversity in the Workplace?” https://bizfluent.com/info-12076820-organizational-diversity-workplace.html
[ { "code": null, "e": 235, "s": 171, "text": "Michelle Venables, Data Scientist and Machine Learning Engineer" }, { "code": null, "e": 615, "s": 235, "text": "What is the strategy that is best aligned with business activities and human capital? Human Resource (HR) strategy is the idea that sets a direction for all the key areas of HR. It is our increasing ability to use analytics to understand more about people, HR processes, and demographics. This includes activities with hiring, performance appraisals, development and compensation" }, { "code": null, "e": 1025, "s": 615, "text": "As data analysts/scientists in the HR space, we would develop a strategy to tackle HR goals and insights over the entire organization. We want to start off with Data we already have within the organization starting with our current employees. This might involve strengths and job descriptions across the organization. An example of this and a good solution would be to use an interactive organizational chart." }, { "code": null, "e": 1341, "s": 1025, "text": "Start by collecting everyones updated resume, continuing education history, performance appraisals, and projects completed. This gives you the ability to identify your current employees’ knowledge, skills and strengths. An interactive organizational chart can be a tool beyond the basic job descriptions and skills." }, { "code": null, "e": 1667, "s": 1341, "text": "Evaluating performance reviews allows management to determine when employees are willing and able to assume additional responsibility. When employees consistently rank high then its time to take on some more challenging work. This blog is meant to describe some tips when analyzing HR strategy and activities within the firm." }, { "code": null, "e": 1787, "s": 1667, "text": "There are a few KPI’s worth mentioning in the HR analytics space. The following 8 metrics are quantitatively evaluated." }, { "code": null, "e": 3111, "s": 1787, "text": "Talent Retention — The ability for an organization to retain its employees. This is normally a statistical measure and sometimes thought of as an employee’s loyalty to their company.Recruiting Effectiveness — there are a couple of ways organizations measure their recruiting effectiveness. A common statisical measure can be Time to Fill, Quality of Hire, Source of Hire, etc.Employee Performance — job rating scales are a common way to evaluate performance of employees, behavioral elements such as understanding job tasks and participation in decision making.Employee Movement — when an employee transfers from one organization to another and is also called the turnover rate. Similar to assessing the retention rate.Total Rewards — this is a tool that managers or employers keep track of in order to attract, motivate and retain employees.Learning and Development — training programs allow employees to grow and succeed within an organization. It allows employees to reach a higher level of skills in knowledge within the organization. These can be evaluated and monitored with performance reviews or with rating scaled (as stated before).Diversity and Inclusion — measuring and improving ideas and creativity. Attract and attain talented people in order to form strong teams.HR-to-employee ratios — delivery of services" }, { "code": null, "e": 3294, "s": 3111, "text": "Talent Retention — The ability for an organization to retain its employees. This is normally a statistical measure and sometimes thought of as an employee’s loyalty to their company." }, { "code": null, "e": 3489, "s": 3294, "text": "Recruiting Effectiveness — there are a couple of ways organizations measure their recruiting effectiveness. A common statisical measure can be Time to Fill, Quality of Hire, Source of Hire, etc." }, { "code": null, "e": 3675, "s": 3489, "text": "Employee Performance — job rating scales are a common way to evaluate performance of employees, behavioral elements such as understanding job tasks and participation in decision making." }, { "code": null, "e": 3834, "s": 3675, "text": "Employee Movement — when an employee transfers from one organization to another and is also called the turnover rate. Similar to assessing the retention rate." }, { "code": null, "e": 3958, "s": 3834, "text": "Total Rewards — this is a tool that managers or employers keep track of in order to attract, motivate and retain employees." }, { "code": null, "e": 4259, "s": 3958, "text": "Learning and Development — training programs allow employees to grow and succeed within an organization. It allows employees to reach a higher level of skills in knowledge within the organization. These can be evaluated and monitored with performance reviews or with rating scaled (as stated before)." }, { "code": null, "e": 4397, "s": 4259, "text": "Diversity and Inclusion — measuring and improving ideas and creativity. Attract and attain talented people in order to form strong teams." }, { "code": null, "e": 4442, "s": 4397, "text": "HR-to-employee ratios — delivery of services" }, { "code": null, "e": 4812, "s": 4442, "text": "We want to collect and evaluate this data in order to define where we are as an organization in terms of HR. The culture and behaviors of employees makeup an organizations team atmosphere and it is HR’s job to build a strategy for success. I have gathered Human Resource data provided by Kaggle.com in order to show an evaluation of an organization. CLICK HERE FOR LINK" }, { "code": null, "e": 5241, "s": 4812, "text": "The first step of a data science project is to make sure we clean and evaluate our data. Cleaning involves dealing with null values, assessing what data is currently available to us, and using different cleansing techniques to organize the structure of our data. Big, dirty, messy, and incompatible data sources can lead to ineffective analytical models. We want to understand our data and here are a few ways on how to do that:" }, { "code": null, "e": 5255, "s": 5241, "text": "hr_data.shape" }, { "code": null, "e": 5293, "s": 5255, "text": "Our output is 300 rows by 21 columns." }, { "code": null, "e": 5314, "s": 5293, "text": "hr_data.isna().sum()" }, { "code": null, "e": 5409, "s": 5314, "text": "Checking for NA results and learning how to deal with them. One way might be to fillna with 0:" }, { "code": null, "e": 5437, "s": 5409, "text": "hr_data = hr_data.fillna(0)" }, { "code": null, "e": 5881, "s": 5437, "text": "After some basic cleaning techniques we can start analyzing and evaluating. I personally like using Seaborn and Matplotlib in order to visualize my data. After viewing our data columns, I believe that evaluating pay_rate might be beneficial. We might even want to predict newer employees pay_rate based on performance scores, position and other characteristics! Let’s take a look on our available data before trying to solve for new employees." }, { "code": null, "e": 6037, "s": 5881, "text": "chart = sns.barplot(x='performance_score', y= 'pay_rate', data=hr_data, palette='Set1', ci=None) chart.set_xticklabels(chart.get_xticklabels(),rotation=90)" }, { "code": null, "e": 6146, "s": 6037, "text": "Make sure to import seaborn as sns before running your line of code. What can we analyze employee pay rates?" }, { "code": null, "e": 6366, "s": 6146, "text": "I’d probably ask some questions about the “Needs Improvement” performance score... Why are these employees at a higher pay rate than employees that “Exceed” the employee performance scores. “Exceptional” seems accurate." }, { "code": null, "e": 6518, "s": 6366, "text": "chart = sns.barplot(x = 'position', y = 'pay_rate', data=hr_data, palette='Set1', ci = None) chart.set_xticklabels(chart.get_xticklabels(),rotation=90)" }, { "code": null, "e": 6761, "s": 6518, "text": "Our second chart shows pay rates based on positions in the company. Obviously, President and CEO are at a higher pay_rate than other employees. The positions/pay_rates seem to be accurate as long as they align with your company’s HR strategy." }, { "code": null, "e": 6904, "s": 6761, "text": "Our next plot will help with analyzing some diversity within the organization. Diversity is a KPI when evaluating our Human Resource Strategy." }, { "code": null, "e": 7184, "s": 6904, "text": "Organizational diversity in the workplace refers to the total makeup of the employee workforce and the amount of diversity included. Diversity refers to differences in various defining personal traits such as age, gender, race, marital status, and many other secondary qualities." }, { "code": null, "e": 7249, "s": 7184, "text": "Take a look at some of our diversity evaluation bar plots below:" }, { "code": null, "e": 7337, "s": 7249, "text": "It’s not much of a difference but on average males have a higher pay_rate than females." }, { "code": null, "e": 7476, "s": 7337, "text": "We binned our ages based on decades in order to evaluate diversification based on age. We can see that our ages ranges are pretty diverse." }, { "code": null, "e": 7840, "s": 7476, "text": "After cleaning our data and evaluating pay rate based on performance scores positions, and diversity measures you should have a good sense of what our data looks like. Before we get into our modeling you always want to clean and evaluate our data. Stay tuned for my next blog on predicting HR analytics and for references to my code click on my github link below!" }, { "code": null, "e": 7878, "s": 7840, "text": "Human Resources Datafication (Part 2)" }, { "code": null, "e": 7903, "s": 7878, "text": "HR_Project — Github link" }, { "code": null, "e": 7915, "s": 7903, "text": "Medium Link" }, { "code": null, "e": 7927, "s": 7915, "text": "References:" } ]
jQuery | multiple classes Selector - GeeksforGeeks
08 Sep, 2021 The .class selector in jquery is used to select multiple classes. Syntax: $(".class1, .class2, .class3, ...") Parameter: class: This parameter is required to specify the class of the elements to be selected. Example-1: <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function() { $(".geeks, .for, .GeeksforGeeks").css( "background-color", "green"); }); </script></head> <body> <center> <h1 class="geeks"> Welcome to GeeksforGeeks </h1> <p>Geeks1</p> <p class="for">Geeks2</p> <p>Geeks3</p> <p class="GeeksforGeeks"> Geeks3 </p> </center></body> </html> Output: Example-2: <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function() { $(".c1, .c2").css( "background-color", "green"); }); </script></head> <body> <center> <h1 class="geeks"> Welcome to GeeksforGeeks </h1> <p class="c1">Geeks1</p> <p class="for">Geeks2</p> <p class="c2">Geeks3</p> <p class= "GeeksforGeeks"> Geeks3 </p> </center></body> </html> Output: Supported Browsers: Google Chrome 90.0+ Internet Explorer 9.0 Firefox 3.6 Safari 4.0 Opera 10.5 ysachin2314 jQuery-Selectors Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments JQuery | Set the value of an input text field How to change selected value of a drop-down list using jQuery? Form validation using jQuery How to change the background color after clicking the button in JavaScript ? How to Dynamically Add/Remove Table Rows using jQuery ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 40723, "s": 40695, "text": "\n08 Sep, 2021" }, { "code": null, "e": 40789, "s": 40723, "text": "The .class selector in jquery is used to select multiple classes." }, { "code": null, "e": 40797, "s": 40789, "text": "Syntax:" }, { "code": null, "e": 40833, "s": 40797, "text": "$(\".class1, .class2, .class3, ...\")" }, { "code": null, "e": 40844, "s": 40833, "text": "Parameter:" }, { "code": null, "e": 40931, "s": 40844, "text": "class: This parameter is required to specify the class of the elements to be selected." }, { "code": null, "e": 40942, "s": 40931, "text": "Example-1:" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\".geeks, .for, .GeeksforGeeks\").css( \"background-color\", \"green\"); }); </script></head> <body> <center> <h1 class=\"geeks\"> Welcome to GeeksforGeeks </h1> <p>Geeks1</p> <p class=\"for\">Geeks2</p> <p>Geeks3</p> <p class=\"GeeksforGeeks\"> Geeks3 </p> </center></body> </html>", "e": 41502, "s": 40942, "text": null }, { "code": null, "e": 41510, "s": 41502, "text": "Output:" }, { "code": null, "e": 41521, "s": 41510, "text": "Example-2:" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\".c1, .c2\").css( \"background-color\", \"green\"); }); </script></head> <body> <center> <h1 class=\"geeks\"> Welcome to GeeksforGeeks </h1> <p class=\"c1\">Geeks1</p> <p class=\"for\">Geeks2</p> <p class=\"c2\">Geeks3</p> <p class= \"GeeksforGeeks\"> Geeks3 </p> </center></body> </html>", "e": 42094, "s": 41521, "text": null }, { "code": null, "e": 42102, "s": 42094, "text": "Output:" }, { "code": null, "e": 42122, "s": 42102, "text": "Supported Browsers:" }, { "code": null, "e": 42142, "s": 42122, "text": "Google Chrome 90.0+" }, { "code": null, "e": 42164, "s": 42142, "text": "Internet Explorer 9.0" }, { "code": null, "e": 42176, "s": 42164, "text": "Firefox 3.6" }, { "code": null, "e": 42187, "s": 42176, "text": "Safari 4.0" }, { "code": null, "e": 42198, "s": 42187, "text": "Opera 10.5" }, { "code": null, "e": 42210, "s": 42198, "text": "ysachin2314" }, { "code": null, "e": 42227, "s": 42210, "text": "jQuery-Selectors" }, { "code": null, "e": 42234, "s": 42227, "text": "Picked" }, { "code": null, "e": 42241, "s": 42234, "text": "JQuery" }, { "code": null, "e": 42258, "s": 42241, "text": "Web Technologies" }, { "code": null, "e": 42356, "s": 42258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42365, "s": 42356, "text": "Comments" }, { "code": null, "e": 42378, "s": 42365, "text": "Old Comments" }, { "code": null, "e": 42424, "s": 42378, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 42487, "s": 42424, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 42516, "s": 42487, "text": "Form validation using jQuery" }, { "code": null, "e": 42593, "s": 42516, "text": "How to change the background color after clicking the button in JavaScript ?" }, { "code": null, "e": 42649, "s": 42593, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 42691, "s": 42649, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 42724, "s": 42691, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 42774, "s": 42724, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 42817, "s": 42774, "text": "How to fetch data from an API in ReactJS ?" } ]
The complete guide to Polynomials | by Shaun Enslin | Towards Data Science
Need a brief and easy introduction to polynomials? Read ahead or watch this tutorial on youtube. You can also download the source code in this article from github. The problem with linear regression is that data does not often go in a straight line. If we look at below data set, a linear function makes perfect sense. Polynomials are defined by the formulae The shape of the polynomial depends on the number of degree terms, and I have explained below, so as you can see, once you understand the shapes of the polynomials, you can start making calculated decisions on which degree it may be. Some of the degrees have names as seen below. Blue = linear polynomial Black = quadratic polynomial Red = cubic polynomial So, increasing the degrees of the polynomial, allows you to get the line to fit the data better. But, be careful, going to high also “overfits” the data and also does not give you an accurate prediction. Now let us look at some other quadratic functions to see what happens when we vary the coefficient of x. We shall use a table of values in order to plot the graphs, but we will fill in only those values near the turning points of the functions. You can see the symmetry in each row of the table, demonstrating that we have concentrated on the region around the turning point of each function. We can now use these values to plot the graphs. Why dont you log into www.desmos.com and plot below polynomials. Try changing the coefficient and the constant terms to see the change in shape. It’s important to understand how polynomials are factorized. This will then allow for an understanding later on how zero’s are calculated to indicate intercepts on the x axis. If you prefer to watch then see my youtube tutorial. In fact, the process of factoring is so important that very little of algebra beyond this point can be accomplished without understanding it. Example 1: Quadratic with a GCF The easiest way to understand this is to do an example, let’s say we have the polynomial: So, our first step is to see if we can find the greatest common factor (gfc). In this case, it would be 3, so this allows us to divide each term by 3. This results in: Now, we need to factor 8 into 2 numbers multiplied together should equal 8, but added together, equal 6: 8 / \-4 -2 So, -4 * -2 = 8, while -4–2 = 6Now that we have our -4 and -2, we can factorize our polynomial as follows: F(x) = (x — 4) (x — 2) Plugging a value for x in our factorized polynomial or the original, will give us the same result. Example 2: Quadratic with no GCF Now, what about when there is no gcf. Let’s take the polynomial: Our first step is to multiply the 1st coefficient by the constant term.Ie. 2 * -3 = -6 Now, let’s find 2 numbers that multiply to -6, but also add to -5 -6 / \-6 +1 Next step is to expand our “- 5x” term to use above numbers. Keep in mindthat -6x + 1x = 5x. So, lets break our 2 parts up From the 1st red part, we can take out 2x, so 2x2–6x becomes Our 2nd part, we can factor the 1 and get: 1(x — 3).So, we end up with Great, lets factor out (x-3) and we end up with a factorized polynomial of f(x) = (x-3) (2x + 1) Example: Cubic polynomial factor by grouping Dealing with quadratic polynomials is dealt with as above, so now, how do we deal with factoring a cubic polynomial. Check if we can group by dividing the coefficients. In below case, both give us a value of 1.5, so we can factorize by grouping. 3/2 == -12/8 == -1.5 Group above into 2 terms and to factor them. Our GCF in the first term is x2 while the GCF in the 2nd term is -4. Now, lets split up terms and we can factor out the (3x — 2) This leaves a problem as we have a difference of perfect squares. We can correct this as follows by taking the square root of x2 and 4 to separate the term into 2 terms and we end up with our final factored polynomial. f(x) = (3x -2) (x — 2) (x + 2) What is a zero of polynomials?If you prefer to watch, then head over to youtube. We need them only because we often use polynomials in our modelling of physical and other situations! The zero is very useful because it helps find the root. So, why find the root? Well, let’s say that we know we have the problem, So, what can x be? The question becomes much more simple if we reduce one side to zero making it . Now, we can plug it in to the quadratic formula and find x. Of course, you may say that this only applies to quadratics. However, given any polynomial, if you make it equal to zero, it becomes much easier to find the roots. So, to answer your question, we don’t actually need the zeros, however they are really, really convenient! If we take the following factorized polynomial:P1(x) = (x-1)(x-2)(x-3) Well, then any value of x where the above equation = “zero”.So any time any of the above 3 expressions are zero, then naturally the product of all 3, will also be zero After factoring, this becomes easy enough to deduce and as we can see that when x is either 1, 2 or 3, the result of P1(x) will be zero. Lets take another example that we can graph. We can see from above, that our our points where each of the 3 terms will be zero, will be when x = [-2, -3/2, 2]. When we plot this polynomial, it is also evident in the graph. I trust that clears up zero’s and these can now be seen in the next article when we discuss the multiplicity of a polynomial. Briefly explained, multiplicity is the amount of times the polynomial crosses the x axis. If you prefer to watch, head over to youtube. Lets take the following two polynomials which are already in factor form. So, in our next step, if we want to figure out the multiplicity of the polynomial, we can see how many individual zero terms we have. In above examples. Our first step as below is to work out our zero values as indicated under each term. So, if we create a table, we can now enter in the multiplicity column, how many zero terms we have for that zero x value. If the multiplicity is odd, then we do have a sign change, while if the multiplicity is even, then we do not have a sign change. This tells us that: For P1, since all multiplicities are odd, every time it hits the x axis, it changes sign.For P2, however, when it hits 3, there is no sign change, since multiplicity is even. For P1, since all multiplicities are odd, every time it hits the x axis, it changes sign. For P2, however, when it hits 3, there is no sign change, since multiplicity is even. You can see this in action now below as each time P1 touches the x axis, it crosses from negative to positive or visa versa. P2 however, does cross from negative to positive where x=1, but where x=3 it bounces off and stays positive. It’s time we get to some coding, buckle up, lets give this a go...Source code available on github.If you take the following polynomial: Now, if we look at the following x values into above equation, we will then get the following y results. You can now start up Matlab and create your x and y vectors as below. Then run the polyfit command, entering 2 in the final parameter, since we are working with a quadratic function. x=[0,1,2]y=[5,3,3]polyfit(x,y,2) Running above, you should get a coefficient as below. So, perfect, from our data, polyfit found the correct polynomial coefficent. ans =1.0000 -3.0000 5.0000 So, that was a nice basic example, but lets try something a little more complicated.... 7.1 Generate sample data In this example, we don’t have a dataset, but that’s OK, we can have Matlab generate some sample data for us to suite our quadratic. First, lets define our quadratic function as below and call it f. clc;clear;close all;% declare our quadratic polynomialf = @(x) 2*x.2 — 4*x + 5; Now, lets generate some sample x values using the unifrnd function. We are adding some variations to the y values with the + 1.5*randn(size(x)). After all, we dont want the data too perfect ;-) % Create x by getting random uniform values between -1 and 5x = unifrnd(-1, 5, [100,1]);% Calculate y by running the polynomial but add some variationsy = f(x) + 1.5 * randn(size(x)); Plot the data points so we can visualise the data % plot the data pointsfigure;plot(x,y,’rx’); After executing, you will see we have generated a nice dataset to compliment our quadratic. 7.2 Find our best coefficient Now that we have our data, lets run a polyfit on a quadratic to find the best coeffecient. We are choosing a quadratic as we can see there is one turn in the data at around ‘1’ on the x axis, thus the shape fits a quadtratic. % find the best coeffeciant[p,S] = polyfit(x,y,2); Se now have our best coefficient in ‘p’ and can go ahead and plot a line for our coeffeciant using polyval. xx = linspace(-1, 5, 100); % generate even spaced xx[yy, delta] = polyval(p,xx,S); % Now get the y for xxhold on;plot(xx,yy); After executing, your coefficient should be plotted 7.3 Plot our support/resistance lines A nice little feature is that we can use the delta returned from the polyval to plot out our support and resistance lines for our polynomial. These are plotted to give us a 90% confidence that the data will fall in these ranges. % Lets use our delta to plot our support and resistance linesplot(xx, yy + 2*delta, ‘b:’);plot(xx, yy — 2*delta, ‘b:’); After reading this article, you should be able to: Explain what polynomials are Factorize polynomials Calculate the zeros Understand multiplicity of a polynomial Finally, we have build a good example in Matlab creating data which has the shape of a quadratic polynomial. This now give you your hypothesis to predict Y, based on the X values.
[ { "code": null, "e": 335, "s": 171, "text": "Need a brief and easy introduction to polynomials? Read ahead or watch this tutorial on youtube. You can also download the source code in this article from github." }, { "code": null, "e": 490, "s": 335, "text": "The problem with linear regression is that data does not often go in a straight line. If we look at below data set, a linear function makes perfect sense." }, { "code": null, "e": 530, "s": 490, "text": "Polynomials are defined by the formulae" }, { "code": null, "e": 810, "s": 530, "text": "The shape of the polynomial depends on the number of degree terms, and I have explained below, so as you can see, once you understand the shapes of the polynomials, you can start making calculated decisions on which degree it may be. Some of the degrees have names as seen below." }, { "code": null, "e": 835, "s": 810, "text": "Blue = linear polynomial" }, { "code": null, "e": 864, "s": 835, "text": "Black = quadratic polynomial" }, { "code": null, "e": 887, "s": 864, "text": "Red = cubic polynomial" }, { "code": null, "e": 1091, "s": 887, "text": "So, increasing the degrees of the polynomial, allows you to get the line to fit the data better. But, be careful, going to high also “overfits” the data and also does not give you an accurate prediction." }, { "code": null, "e": 1336, "s": 1091, "text": "Now let us look at some other quadratic functions to see what happens when we vary the coefficient of x. We shall use a table of values in order to plot the graphs, but we will fill in only those values near the turning points of the functions." }, { "code": null, "e": 1532, "s": 1336, "text": "You can see the symmetry in each row of the table, demonstrating that we have concentrated on the region around the turning point of each function. We can now use these values to plot the graphs." }, { "code": null, "e": 1677, "s": 1532, "text": "Why dont you log into www.desmos.com and plot below polynomials. Try changing the coefficient and the constant terms to see the change in shape." }, { "code": null, "e": 1906, "s": 1677, "text": "It’s important to understand how polynomials are factorized. This will then allow for an understanding later on how zero’s are calculated to indicate intercepts on the x axis. If you prefer to watch then see my youtube tutorial." }, { "code": null, "e": 2048, "s": 1906, "text": "In fact, the process of factoring is so important that very little of algebra beyond this point can be accomplished without understanding it." }, { "code": null, "e": 2080, "s": 2048, "text": "Example 1: Quadratic with a GCF" }, { "code": null, "e": 2170, "s": 2080, "text": "The easiest way to understand this is to do an example, let’s say we have the polynomial:" }, { "code": null, "e": 2338, "s": 2170, "text": "So, our first step is to see if we can find the greatest common factor (gfc). In this case, it would be 3, so this allows us to divide each term by 3. This results in:" }, { "code": null, "e": 2443, "s": 2338, "text": "Now, we need to factor 8 into 2 numbers multiplied together should equal 8, but added together, equal 6:" }, { "code": null, "e": 2456, "s": 2443, "text": " 8 / \\-4 -2" }, { "code": null, "e": 2563, "s": 2456, "text": "So, -4 * -2 = 8, while -4–2 = 6Now that we have our -4 and -2, we can factorize our polynomial as follows:" }, { "code": null, "e": 2586, "s": 2563, "text": "F(x) = (x — 4) (x — 2)" }, { "code": null, "e": 2685, "s": 2586, "text": "Plugging a value for x in our factorized polynomial or the original, will give us the same result." }, { "code": null, "e": 2718, "s": 2685, "text": "Example 2: Quadratic with no GCF" }, { "code": null, "e": 2783, "s": 2718, "text": "Now, what about when there is no gcf. Let’s take the polynomial:" }, { "code": null, "e": 2870, "s": 2783, "text": "Our first step is to multiply the 1st coefficient by the constant term.Ie. 2 * -3 = -6" }, { "code": null, "e": 2936, "s": 2870, "text": "Now, let’s find 2 numbers that multiply to -6, but also add to -5" }, { "code": null, "e": 2952, "s": 2936, "text": " -6 / \\-6 +1" }, { "code": null, "e": 3045, "s": 2952, "text": "Next step is to expand our “- 5x” term to use above numbers. Keep in mindthat -6x + 1x = 5x." }, { "code": null, "e": 3075, "s": 3045, "text": "So, lets break our 2 parts up" }, { "code": null, "e": 3136, "s": 3075, "text": "From the 1st red part, we can take out 2x, so 2x2–6x becomes" }, { "code": null, "e": 3207, "s": 3136, "text": "Our 2nd part, we can factor the 1 and get: 1(x — 3).So, we end up with" }, { "code": null, "e": 3282, "s": 3207, "text": "Great, lets factor out (x-3) and we end up with a factorized polynomial of" }, { "code": null, "e": 3304, "s": 3282, "text": "f(x) = (x-3) (2x + 1)" }, { "code": null, "e": 3349, "s": 3304, "text": "Example: Cubic polynomial factor by grouping" }, { "code": null, "e": 3466, "s": 3349, "text": "Dealing with quadratic polynomials is dealt with as above, so now, how do we deal with factoring a cubic polynomial." }, { "code": null, "e": 3595, "s": 3466, "text": "Check if we can group by dividing the coefficients. In below case, both give us a value of 1.5, so we can factorize by grouping." }, { "code": null, "e": 3616, "s": 3595, "text": "3/2 == -12/8 == -1.5" }, { "code": null, "e": 3730, "s": 3616, "text": "Group above into 2 terms and to factor them. Our GCF in the first term is x2 while the GCF in the 2nd term is -4." }, { "code": null, "e": 3790, "s": 3730, "text": "Now, lets split up terms and we can factor out the (3x — 2)" }, { "code": null, "e": 4009, "s": 3790, "text": "This leaves a problem as we have a difference of perfect squares. We can correct this as follows by taking the square root of x2 and 4 to separate the term into 2 terms and we end up with our final factored polynomial." }, { "code": null, "e": 4040, "s": 4009, "text": "f(x) = (3x -2) (x — 2) (x + 2)" }, { "code": null, "e": 4121, "s": 4040, "text": "What is a zero of polynomials?If you prefer to watch, then head over to youtube." }, { "code": null, "e": 4302, "s": 4121, "text": "We need them only because we often use polynomials in our modelling of physical and other situations! The zero is very useful because it helps find the root. So, why find the root?" }, { "code": null, "e": 4352, "s": 4302, "text": "Well, let’s say that we know we have the problem," }, { "code": null, "e": 4371, "s": 4352, "text": "So, what can x be?" }, { "code": null, "e": 4451, "s": 4371, "text": "The question becomes much more simple if we reduce one side to zero making it ." }, { "code": null, "e": 4511, "s": 4451, "text": "Now, we can plug it in to the quadratic formula and find x." }, { "code": null, "e": 4675, "s": 4511, "text": "Of course, you may say that this only applies to quadratics. However, given any polynomial, if you make it equal to zero, it becomes much easier to find the roots." }, { "code": null, "e": 4782, "s": 4675, "text": "So, to answer your question, we don’t actually need the zeros, however they are really, really convenient!" }, { "code": null, "e": 4853, "s": 4782, "text": "If we take the following factorized polynomial:P1(x) = (x-1)(x-2)(x-3)" }, { "code": null, "e": 5021, "s": 4853, "text": "Well, then any value of x where the above equation = “zero”.So any time any of the above 3 expressions are zero, then naturally the product of all 3, will also be zero" }, { "code": null, "e": 5158, "s": 5021, "text": "After factoring, this becomes easy enough to deduce and as we can see that when x is either 1, 2 or 3, the result of P1(x) will be zero." }, { "code": null, "e": 5203, "s": 5158, "text": "Lets take another example that we can graph." }, { "code": null, "e": 5381, "s": 5203, "text": "We can see from above, that our our points where each of the 3 terms will be zero, will be when x = [-2, -3/2, 2]. When we plot this polynomial, it is also evident in the graph." }, { "code": null, "e": 5507, "s": 5381, "text": "I trust that clears up zero’s and these can now be seen in the next article when we discuss the multiplicity of a polynomial." }, { "code": null, "e": 5643, "s": 5507, "text": "Briefly explained, multiplicity is the amount of times the polynomial crosses the x axis. If you prefer to watch, head over to youtube." }, { "code": null, "e": 5717, "s": 5643, "text": "Lets take the following two polynomials which are already in factor form." }, { "code": null, "e": 5955, "s": 5717, "text": "So, in our next step, if we want to figure out the multiplicity of the polynomial, we can see how many individual zero terms we have. In above examples. Our first step as below is to work out our zero values as indicated under each term." }, { "code": null, "e": 6077, "s": 5955, "text": "So, if we create a table, we can now enter in the multiplicity column, how many zero terms we have for that zero x value." }, { "code": null, "e": 6226, "s": 6077, "text": "If the multiplicity is odd, then we do have a sign change, while if the multiplicity is even, then we do not have a sign change. This tells us that:" }, { "code": null, "e": 6401, "s": 6226, "text": "For P1, since all multiplicities are odd, every time it hits the x axis, it changes sign.For P2, however, when it hits 3, there is no sign change, since multiplicity is even." }, { "code": null, "e": 6491, "s": 6401, "text": "For P1, since all multiplicities are odd, every time it hits the x axis, it changes sign." }, { "code": null, "e": 6577, "s": 6491, "text": "For P2, however, when it hits 3, there is no sign change, since multiplicity is even." }, { "code": null, "e": 6702, "s": 6577, "text": "You can see this in action now below as each time P1 touches the x axis, it crosses from negative to positive or visa versa." }, { "code": null, "e": 6811, "s": 6702, "text": "P2 however, does cross from negative to positive where x=1, but where x=3 it bounces off and stays positive." }, { "code": null, "e": 6947, "s": 6811, "text": "It’s time we get to some coding, buckle up, lets give this a go...Source code available on github.If you take the following polynomial:" }, { "code": null, "e": 7052, "s": 6947, "text": "Now, if we look at the following x values into above equation, we will then get the following y results." }, { "code": null, "e": 7235, "s": 7052, "text": "You can now start up Matlab and create your x and y vectors as below. Then run the polyfit command, entering 2 in the final parameter, since we are working with a quadratic function." }, { "code": null, "e": 7268, "s": 7235, "text": "x=[0,1,2]y=[5,3,3]polyfit(x,y,2)" }, { "code": null, "e": 7399, "s": 7268, "text": "Running above, you should get a coefficient as below. So, perfect, from our data, polyfit found the correct polynomial coefficent." }, { "code": null, "e": 7426, "s": 7399, "text": "ans =1.0000 -3.0000 5.0000" }, { "code": null, "e": 7514, "s": 7426, "text": "So, that was a nice basic example, but lets try something a little more complicated...." }, { "code": null, "e": 7539, "s": 7514, "text": "7.1 Generate sample data" }, { "code": null, "e": 7738, "s": 7539, "text": "In this example, we don’t have a dataset, but that’s OK, we can have Matlab generate some sample data for us to suite our quadratic. First, lets define our quadratic function as below and call it f." }, { "code": null, "e": 7818, "s": 7738, "text": "clc;clear;close all;% declare our quadratic polynomialf = @(x) 2*x.2 — 4*x + 5;" }, { "code": null, "e": 8012, "s": 7818, "text": "Now, lets generate some sample x values using the unifrnd function. We are adding some variations to the y values with the + 1.5*randn(size(x)). After all, we dont want the data too perfect ;-)" }, { "code": null, "e": 8196, "s": 8012, "text": "% Create x by getting random uniform values between -1 and 5x = unifrnd(-1, 5, [100,1]);% Calculate y by running the polynomial but add some variationsy = f(x) + 1.5 * randn(size(x));" }, { "code": null, "e": 8246, "s": 8196, "text": "Plot the data points so we can visualise the data" }, { "code": null, "e": 8291, "s": 8246, "text": "% plot the data pointsfigure;plot(x,y,’rx’);" }, { "code": null, "e": 8383, "s": 8291, "text": "After executing, you will see we have generated a nice dataset to compliment our quadratic." }, { "code": null, "e": 8413, "s": 8383, "text": "7.2 Find our best coefficient" }, { "code": null, "e": 8639, "s": 8413, "text": "Now that we have our data, lets run a polyfit on a quadratic to find the best coeffecient. We are choosing a quadratic as we can see there is one turn in the data at around ‘1’ on the x axis, thus the shape fits a quadtratic." }, { "code": null, "e": 8690, "s": 8639, "text": "% find the best coeffeciant[p,S] = polyfit(x,y,2);" }, { "code": null, "e": 8798, "s": 8690, "text": "Se now have our best coefficient in ‘p’ and can go ahead and plot a line for our coeffeciant using polyval." }, { "code": null, "e": 8932, "s": 8798, "text": "xx = linspace(-1, 5, 100); % generate even spaced xx[yy, delta] = polyval(p,xx,S); % Now get the y for xxhold on;plot(xx,yy);" }, { "code": null, "e": 8984, "s": 8932, "text": "After executing, your coefficient should be plotted" }, { "code": null, "e": 9022, "s": 8984, "text": "7.3 Plot our support/resistance lines" }, { "code": null, "e": 9251, "s": 9022, "text": "A nice little feature is that we can use the delta returned from the polyval to plot out our support and resistance lines for our polynomial. These are plotted to give us a 90% confidence that the data will fall in these ranges." }, { "code": null, "e": 9371, "s": 9251, "text": "% Lets use our delta to plot our support and resistance linesplot(xx, yy + 2*delta, ‘b:’);plot(xx, yy — 2*delta, ‘b:’);" }, { "code": null, "e": 9422, "s": 9371, "text": "After reading this article, you should be able to:" }, { "code": null, "e": 9451, "s": 9422, "text": "Explain what polynomials are" }, { "code": null, "e": 9473, "s": 9451, "text": "Factorize polynomials" }, { "code": null, "e": 9493, "s": 9473, "text": "Calculate the zeros" }, { "code": null, "e": 9533, "s": 9493, "text": "Understand multiplicity of a polynomial" } ]
How to plot a histogram using Matplotlib in Python with a list of data?
To plot a histogram using Matplotlib, we can follow the steps given below − Make a list of numbers and assign it to a variable x. Make a list of numbers and assign it to a variable x. Use the plt.hist() method to plot a histogram. Use the plt.hist() method to plot a histogram. Compute and draw the histogram of *x*. Compute and draw the histogram of *x*. We can pass n-Dimensional arrays in the hist argument also. We can pass n-Dimensional arrays in the hist argument also. To show the plotted figure, use the plt.show() method. To show the plotted figure, use the plt.show() method. from matplotlib import pyplot as plt x = [300, 400, 500, 2000, 10] plt.hist(x, 10) plt.show()
[ { "code": null, "e": 1138, "s": 1062, "text": "To plot a histogram using Matplotlib, we can follow the steps given below −" }, { "code": null, "e": 1192, "s": 1138, "text": "Make a list of numbers and assign it to a variable x." }, { "code": null, "e": 1246, "s": 1192, "text": "Make a list of numbers and assign it to a variable x." }, { "code": null, "e": 1293, "s": 1246, "text": "Use the plt.hist() method to plot a histogram." }, { "code": null, "e": 1340, "s": 1293, "text": "Use the plt.hist() method to plot a histogram." }, { "code": null, "e": 1379, "s": 1340, "text": "Compute and draw the histogram of *x*." }, { "code": null, "e": 1418, "s": 1379, "text": "Compute and draw the histogram of *x*." }, { "code": null, "e": 1478, "s": 1418, "text": "We can pass n-Dimensional arrays in the hist argument also." }, { "code": null, "e": 1538, "s": 1478, "text": "We can pass n-Dimensional arrays in the hist argument also." }, { "code": null, "e": 1593, "s": 1538, "text": "To show the plotted figure, use the plt.show() method." }, { "code": null, "e": 1648, "s": 1593, "text": "To show the plotted figure, use the plt.show() method." }, { "code": null, "e": 1745, "s": 1648, "text": "from matplotlib import pyplot as plt\n\nx = [300, 400, 500, 2000, 10]\n\nplt.hist(x, 10)\n\nplt.show()" } ]
2 Types of Duplicate Features in Machine Learning | by Samarth Agrawal | Towards Data Science
Two things distinguish top data scientists from others in most cases: Feature Creation and Feature Selection. i.e., creating features that capture deeper/hidden insights about the business or customer and then making the right choices about which features to choose for your model. Feature Selection is the process of reducing the number of input variables when developing a predictive model. After an extensive Feature Engineering step, you would end up with a large number of features. You may not use all the features in your model. You would be interested in feeding your model only those significant features or remove the ones that do not have any predictive power. It reduces the computational cost of model training and also improves the performance of the model. In the previous post, we have seen how to detect constant and quasi-constant features. This post is for identifying all the duplicate features. These can be of two types: Duplicate Values: When two features have the same set of valuesDuplicate Index: When the value of two features are different, but they occur at the same index Duplicate Values: When two features have the same set of values Duplicate Index: When the value of two features are different, but they occur at the same index As shown in the example image, the year of the sale for a car is the same as the manufacture year; then, these two features essentially say the same thing. Your machine learning model won’t learn anything insightful by keeping both these features in training. You are better off dropping one of the features. Likewise, there can be many more such features, and you need a programmatic way of identifying this. 1) Use the get_duplicate_features functions to get all the constant features. 2) Store all the duplicate features as a list for removing from the dataset. 3) Drop all such features from the dataset. We can see that the number of features has dropped to 251 from 301. As shown in the example image — all the ‘Camry’ cars are from 2018 and all the ‘Corolla’ cars from 2019. There is nothing insightful for your machine learning model from these features in training. I can also do integer encoding for the Car Model to replace Camry with 2018 and Corolla with 2019. Then it is the same as case 1 above of Duplicate Values. You are better off dropping one of these two features. Likewise, there can be many more such features, and you need a programmatic way of identifying this. 1) Use the get_duplicate_features functions to get all the constant features. 2) Store all the duplicate index features as a list for removing from the dataset. 3) Drop all such features from the dataset. We can see that the number of features has dropped to 226 from 251. Keeping duplicate features in your dataset introduces the problem of multicollinearity. — In the case of linear models, weights distribution between the two features will be problematic. — If you are using tree-based modes, it won’t matter unless you are looking at feature importance. — In the case of distance-based models, it will make that feature count more in the distance. Code Snippet for detecting features having Duplicate Values or Duplicate Index: # Import required functionsfrom fast_ml.utilities import display_allfrom fast_ml.feature_selection import get_duplicate_features# Use the function to get the results in dataframeduplicate_features = get_duplicate_features(df)display_all(duplicate_features)# All the constant features stored in a listduplicate_features_list = duplicate_features['feature2'].to_list()# Drop all the constant features from the datasetdf.drop(columns = duplicate_features_list, inplace=True) Package by the Data-Scientists for the Data Scientists ; with Scikit-learn type fit() transform() functionality There are numerous inbuilt functionalities to make the life of a data scientist much easier — Exploratory Data Analysis — Missing Value Treatment — Outlier Treatment — Feature Engineering — Feature Selection — Model Development — Model Evaluation If you enjoyed this, follow me on medium for more. Interested in collaborating? Let’s connect on Linkedin. Please feel free to write your thoughts/suggestions/feedback. Kaggle link Notebook is available at the following location with fully functional code:
[ { "code": null, "e": 454, "s": 172, "text": "Two things distinguish top data scientists from others in most cases: Feature Creation and Feature Selection. i.e., creating features that capture deeper/hidden insights about the business or customer and then making the right choices about which features to choose for your model." }, { "code": null, "e": 565, "s": 454, "text": "Feature Selection is the process of reducing the number of input variables when developing a predictive model." }, { "code": null, "e": 944, "s": 565, "text": "After an extensive Feature Engineering step, you would end up with a large number of features. You may not use all the features in your model. You would be interested in feeding your model only those significant features or remove the ones that do not have any predictive power. It reduces the computational cost of model training and also improves the performance of the model." }, { "code": null, "e": 1031, "s": 944, "text": "In the previous post, we have seen how to detect constant and quasi-constant features." }, { "code": null, "e": 1115, "s": 1031, "text": "This post is for identifying all the duplicate features. These can be of two types:" }, { "code": null, "e": 1274, "s": 1115, "text": "Duplicate Values: When two features have the same set of valuesDuplicate Index: When the value of two features are different, but they occur at the same index" }, { "code": null, "e": 1338, "s": 1274, "text": "Duplicate Values: When two features have the same set of values" }, { "code": null, "e": 1434, "s": 1338, "text": "Duplicate Index: When the value of two features are different, but they occur at the same index" }, { "code": null, "e": 1844, "s": 1434, "text": "As shown in the example image, the year of the sale for a car is the same as the manufacture year; then, these two features essentially say the same thing. Your machine learning model won’t learn anything insightful by keeping both these features in training. You are better off dropping one of the features. Likewise, there can be many more such features, and you need a programmatic way of identifying this." }, { "code": null, "e": 1922, "s": 1844, "text": "1) Use the get_duplicate_features functions to get all the constant features." }, { "code": null, "e": 1999, "s": 1922, "text": "2) Store all the duplicate features as a list for removing from the dataset." }, { "code": null, "e": 2111, "s": 1999, "text": "3) Drop all such features from the dataset. We can see that the number of features has dropped to 251 from 301." }, { "code": null, "e": 2621, "s": 2111, "text": "As shown in the example image — all the ‘Camry’ cars are from 2018 and all the ‘Corolla’ cars from 2019. There is nothing insightful for your machine learning model from these features in training. I can also do integer encoding for the Car Model to replace Camry with 2018 and Corolla with 2019. Then it is the same as case 1 above of Duplicate Values. You are better off dropping one of these two features. Likewise, there can be many more such features, and you need a programmatic way of identifying this." }, { "code": null, "e": 2699, "s": 2621, "text": "1) Use the get_duplicate_features functions to get all the constant features." }, { "code": null, "e": 2782, "s": 2699, "text": "2) Store all the duplicate index features as a list for removing from the dataset." }, { "code": null, "e": 2894, "s": 2782, "text": "3) Drop all such features from the dataset. We can see that the number of features has dropped to 226 from 251." }, { "code": null, "e": 3275, "s": 2894, "text": "Keeping duplicate features in your dataset introduces the problem of multicollinearity. — In the case of linear models, weights distribution between the two features will be problematic. — If you are using tree-based modes, it won’t matter unless you are looking at feature importance. — In the case of distance-based models, it will make that feature count more in the distance." }, { "code": null, "e": 3355, "s": 3275, "text": "Code Snippet for detecting features having Duplicate Values or Duplicate Index:" }, { "code": null, "e": 3827, "s": 3355, "text": "# Import required functionsfrom fast_ml.utilities import display_allfrom fast_ml.feature_selection import get_duplicate_features# Use the function to get the results in dataframeduplicate_features = get_duplicate_features(df)display_all(duplicate_features)# All the constant features stored in a listduplicate_features_list = duplicate_features['feature2'].to_list()# Drop all the constant features from the datasetdf.drop(columns = duplicate_features_list, inplace=True)" }, { "code": null, "e": 3939, "s": 3827, "text": "Package by the Data-Scientists for the Data Scientists ; with Scikit-learn type fit() transform() functionality" }, { "code": null, "e": 4031, "s": 3939, "text": "There are numerous inbuilt functionalities to make the life of a data scientist much easier" }, { "code": null, "e": 4059, "s": 4031, "text": "— Exploratory Data Analysis" }, { "code": null, "e": 4085, "s": 4059, "text": "— Missing Value Treatment" }, { "code": null, "e": 4105, "s": 4085, "text": "— Outlier Treatment" }, { "code": null, "e": 4127, "s": 4105, "text": "— Feature Engineering" }, { "code": null, "e": 4147, "s": 4127, "text": "— Feature Selection" }, { "code": null, "e": 4167, "s": 4147, "text": "— Model Development" }, { "code": null, "e": 4186, "s": 4167, "text": "— Model Evaluation" }, { "code": null, "e": 4237, "s": 4186, "text": "If you enjoyed this, follow me on medium for more." }, { "code": null, "e": 4293, "s": 4237, "text": "Interested in collaborating? Let’s connect on Linkedin." }, { "code": null, "e": 4355, "s": 4293, "text": "Please feel free to write your thoughts/suggestions/feedback." }, { "code": null, "e": 4367, "s": 4355, "text": "Kaggle link" } ]
Exporting Data from scripts in R Programming - GeeksforGeeks
01 Jun, 2020 So far the operations using R program are done on a prompt/terminal which is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. So the two most common operations that can be performed on a file are: Importing Data to R scripts Exporting Data from R scripts When a program is terminated, the entire data is lost. Storing in a file will preserve one’s data even if the program terminates. If one has to enter a large number of data, it will take a lot of time to enter them all. However, if one has a file containing all the data, he/she can easily access the contents of the file using a few commands in R. One can easily move his data from one computer to another without any changes. So those files can be stored in various formats. It may be stored in .txt(tab-separated value) file, or in a tabular format i.e .csv(comma-separated value) file or it may be on internet or cloud. R provides very easier methods to export data to those files. One of the important formats to store a file is in a text file. R provides various methods that one can export data to a text file. write.table(): The R base function write.table() can be used to export a data frame or a matrix to a text file.Syntax:write.table(x, file, append = FALSE, sep = ” “, dec = “.”, row.names = TRUE, col.names = TRUE)Parameters:x: a matrix or a data frame to be written.file: a character specifying the name of the result file.sep: the field separator string, e.g., sep = “\t” (for tab-separated value).dec: the string to be used as decimal separator. Default is “.”row.names: either a logical value indicating whether the row names of x are to be written along with x, or a character vector of row names to be written.col.names: either a logical value indicating whether the column names of x are to be written along with x, or a character vector of column names to be written.Example:# R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45) ) # Export a data frame to a text file using write.table()write.table(df, file = "myDataFrame.txt", sep = "\t", row.names = TRUE, col.names = NA)Output: Syntax:write.table(x, file, append = FALSE, sep = ” “, dec = “.”, row.names = TRUE, col.names = TRUE) Parameters:x: a matrix or a data frame to be written.file: a character specifying the name of the result file.sep: the field separator string, e.g., sep = “\t” (for tab-separated value).dec: the string to be used as decimal separator. Default is “.”row.names: either a logical value indicating whether the row names of x are to be written along with x, or a character vector of row names to be written.col.names: either a logical value indicating whether the column names of x are to be written along with x, or a character vector of column names to be written. Example: # R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45) ) # Export a data frame to a text file using write.table()write.table(df, file = "myDataFrame.txt", sep = "\t", row.names = TRUE, col.names = NA) Output: write_tsv(): This method is also used for to export data to a tab separated (“\t”) values by using the help of readr package.Syntax: write_tsv(file, path)Parameters:file: a data frame to be writtenpath: the path to the result fileExample:# R program to illustrate# Exporting data from R # Importing readr librarylibrary(readr) # Creating a dataframe df = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45) ) # Export a data frame using write_tsv() write_tsv(df, path = "MyDataFrame.txt")Output: Syntax: write_tsv(file, path) Parameters: file: a data frame to be writtenpath: the path to the result file Example: # R program to illustrate# Exporting data from R # Importing readr librarylibrary(readr) # Creating a dataframe df = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45) ) # Export a data frame using write_tsv() write_tsv(df, path = "MyDataFrame.txt") Output: Another popular format to store a file is in a csv(comma-separated value) format. R provides various methods that one can export data to a csv file. write.table(): The R base function write.table() can also be used to export a data frame or a matrix to a csv file.Syntax:write.table(x, file, append = FALSE, sep = ” “, dec = “.”, row.names = TRUE, col.names = TRUE)Parameters:x: a matrix or a data frame to be written.file: a character specifying the name of the result file.sep: the field separator string, e.g., sep = “\t” (for tab-separated value).dec: the string to be used as decimal separator. Default is “.”row.names: either a logical value indicating whether the row names of x are to be written along with x, or a character vector of row names to be written.col.names: either a logical value indicating whether the column names of x are to be written along with x, or a character vector of column names to be written.Example:# R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45) ) # Export a data frame to a text file using write.table()write.table(df, file = "myDataFrame.csv", sep = "\t", row.names = FALSE, )Output: Syntax:write.table(x, file, append = FALSE, sep = ” “, dec = “.”, row.names = TRUE, col.names = TRUE) Parameters:x: a matrix or a data frame to be written.file: a character specifying the name of the result file.sep: the field separator string, e.g., sep = “\t” (for tab-separated value).dec: the string to be used as decimal separator. Default is “.”row.names: either a logical value indicating whether the row names of x are to be written along with x, or a character vector of row names to be written.col.names: either a logical value indicating whether the column names of x are to be written along with x, or a character vector of column names to be written. Example: # R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45) ) # Export a data frame to a text file using write.table()write.table(df, file = "myDataFrame.csv", sep = "\t", row.names = FALSE, ) Output: write.csv(): This method is recommendable for exporting data to a csv file. It uses “.” for the decimal point and a comma (“, ”) for the separator.Example:# R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45) ) # Export a data frame to a text file using write.csv()write.csv(df, file = "my_data.csv")Output: Example: # R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45) ) # Export a data frame to a text file using write.csv()write.csv(df, file = "my_data.csv") Output: write.csv2(): This method is much similar as write.csv() but it uses a comma (“, ”) for the decimal point and a semicolon (“;”) for the separator.Example:# R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45) ) # Export a data frame to a text file using write.csv2()write.csv2(df, file = "my_data.csv")Output: Example: # R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45) ) # Export a data frame to a text file using write.csv2()write.csv2(df, file = "my_data.csv") Output: write_csv(): This method is also used for to export data to a comma separated (“, ”) values by using the help of readr package.Syntax: write_csv(file, path)Parameters:file: a data frame to be writtenpath: the path to the result fileExample:# R program to illustrate# Exporting data from R # Importing readr librarylibrary(readr) # Creating a dataframe df = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45) ) # Export a data frame using write_csv() write_csv(df, path = "MyDataFrame.csv")Output: Syntax: write_csv(file, path) Parameters:file: a data frame to be writtenpath: the path to the result file Example: # R program to illustrate# Exporting data from R # Importing readr librarylibrary(readr) # Creating a dataframe df = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45) ) # Export a data frame using write_csv() write_csv(df, path = "MyDataFrame.csv") Output: Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Adding elements in a vector in R programming - append() method Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R Loops in R (for, while, repeat) Convert Factor to Numeric and Numeric to Factor in R Programming How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 28964, "s": 28936, "text": "\n01 Jun, 2020" }, { "code": null, "e": 29307, "s": 28964, "text": "So far the operations using R program are done on a prompt/terminal which is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. So the two most common operations that can be performed on a file are:" }, { "code": null, "e": 29335, "s": 29307, "text": "Importing Data to R scripts" }, { "code": null, "e": 29365, "s": 29335, "text": "Exporting Data from R scripts" }, { "code": null, "e": 30051, "s": 29365, "text": "When a program is terminated, the entire data is lost. Storing in a file will preserve one’s data even if the program terminates. If one has to enter a large number of data, it will take a lot of time to enter them all. However, if one has a file containing all the data, he/she can easily access the contents of the file using a few commands in R. One can easily move his data from one computer to another without any changes. So those files can be stored in various formats. It may be stored in .txt(tab-separated value) file, or in a tabular format i.e .csv(comma-separated value) file or it may be on internet or cloud. R provides very easier methods to export data to those files." }, { "code": null, "e": 30183, "s": 30051, "text": "One of the important formats to store a file is in a text file. R provides various methods that one can export data to a text file." }, { "code": null, "e": 31357, "s": 30183, "text": "write.table(): The R base function write.table() can be used to export a data frame or a matrix to a text file.Syntax:write.table(x, file, append = FALSE, sep = ” “, dec = “.”, row.names = TRUE, col.names = TRUE)Parameters:x: a matrix or a data frame to be written.file: a character specifying the name of the result file.sep: the field separator string, e.g., sep = “\\t” (for tab-separated value).dec: the string to be used as decimal separator. Default is “.”row.names: either a logical value indicating whether the row names of x are to be written along with x, or a character vector of row names to be written.col.names: either a logical value indicating whether the column names of x are to be written along with x, or a character vector of column names to be written.Example:# R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45) ) # Export a data frame to a text file using write.table()write.table(df, file = \"myDataFrame.txt\", sep = \"\\t\", row.names = TRUE, col.names = NA)Output:" }, { "code": null, "e": 31459, "s": 31357, "text": "Syntax:write.table(x, file, append = FALSE, sep = ” “, dec = “.”, row.names = TRUE, col.names = TRUE)" }, { "code": null, "e": 32021, "s": 31459, "text": "Parameters:x: a matrix or a data frame to be written.file: a character specifying the name of the result file.sep: the field separator string, e.g., sep = “\\t” (for tab-separated value).dec: the string to be used as decimal separator. Default is “.”row.names: either a logical value indicating whether the row names of x are to be written along with x, or a character vector of row names to be written.col.names: either a logical value indicating whether the column names of x are to be written along with x, or a character vector of column names to be written." }, { "code": null, "e": 32030, "s": 32021, "text": "Example:" }, { "code": "# R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45) ) # Export a data frame to a text file using write.table()write.table(df, file = \"myDataFrame.txt\", sep = \"\\t\", row.names = TRUE, col.names = NA)", "e": 32416, "s": 32030, "text": null }, { "code": null, "e": 32424, "s": 32416, "text": "Output:" }, { "code": null, "e": 32988, "s": 32424, "text": "write_tsv(): This method is also used for to export data to a tab separated (“\\t”) values by using the help of readr package.Syntax: write_tsv(file, path)Parameters:file: a data frame to be writtenpath: the path to the result fileExample:# R program to illustrate# Exporting data from R # Importing readr librarylibrary(readr) # Creating a dataframe df = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45) ) # Export a data frame using write_tsv() write_tsv(df, path = \"MyDataFrame.txt\")Output:" }, { "code": null, "e": 33018, "s": 32988, "text": "Syntax: write_tsv(file, path)" }, { "code": null, "e": 33030, "s": 33018, "text": "Parameters:" }, { "code": null, "e": 33096, "s": 33030, "text": "file: a data frame to be writtenpath: the path to the result file" }, { "code": null, "e": 33105, "s": 33096, "text": "Example:" }, { "code": "# R program to illustrate# Exporting data from R # Importing readr librarylibrary(readr) # Creating a dataframe df = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45) ) # Export a data frame using write_tsv() write_tsv(df, path = \"MyDataFrame.txt\")", "e": 33424, "s": 33105, "text": null }, { "code": null, "e": 33432, "s": 33424, "text": "Output:" }, { "code": null, "e": 33581, "s": 33432, "text": "Another popular format to store a file is in a csv(comma-separated value) format. R provides various methods that one can export data to a csv file." }, { "code": null, "e": 34746, "s": 33581, "text": "write.table(): The R base function write.table() can also be used to export a data frame or a matrix to a csv file.Syntax:write.table(x, file, append = FALSE, sep = ” “, dec = “.”, row.names = TRUE, col.names = TRUE)Parameters:x: a matrix or a data frame to be written.file: a character specifying the name of the result file.sep: the field separator string, e.g., sep = “\\t” (for tab-separated value).dec: the string to be used as decimal separator. Default is “.”row.names: either a logical value indicating whether the row names of x are to be written along with x, or a character vector of row names to be written.col.names: either a logical value indicating whether the column names of x are to be written along with x, or a character vector of column names to be written.Example:# R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45) ) # Export a data frame to a text file using write.table()write.table(df, file = \"myDataFrame.csv\", sep = \"\\t\", row.names = FALSE, )Output:" }, { "code": null, "e": 34848, "s": 34746, "text": "Syntax:write.table(x, file, append = FALSE, sep = ” “, dec = “.”, row.names = TRUE, col.names = TRUE)" }, { "code": null, "e": 35410, "s": 34848, "text": "Parameters:x: a matrix or a data frame to be written.file: a character specifying the name of the result file.sep: the field separator string, e.g., sep = “\\t” (for tab-separated value).dec: the string to be used as decimal separator. Default is “.”row.names: either a logical value indicating whether the row names of x are to be written along with x, or a character vector of row names to be written.col.names: either a logical value indicating whether the column names of x are to be written along with x, or a character vector of column names to be written." }, { "code": null, "e": 35419, "s": 35410, "text": "Example:" }, { "code": "# R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45) ) # Export a data frame to a text file using write.table()write.table(df, file = \"myDataFrame.csv\", sep = \"\\t\", row.names = FALSE, )", "e": 35792, "s": 35419, "text": null }, { "code": null, "e": 35800, "s": 35792, "text": "Output:" }, { "code": null, "e": 36250, "s": 35800, "text": "write.csv(): This method is recommendable for exporting data to a csv file. It uses “.” for the decimal point and a comma (“, ”) for the separator.Example:# R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45) ) # Export a data frame to a text file using write.csv()write.csv(df, file = \"my_data.csv\")Output:" }, { "code": null, "e": 36259, "s": 36250, "text": "Example:" }, { "code": "# R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45) ) # Export a data frame to a text file using write.csv()write.csv(df, file = \"my_data.csv\")", "e": 36547, "s": 36259, "text": null }, { "code": null, "e": 36555, "s": 36547, "text": "Output:" }, { "code": null, "e": 37006, "s": 36555, "text": "write.csv2(): This method is much similar as write.csv() but it uses a comma (“, ”) for the decimal point and a semicolon (“;”) for the separator.Example:# R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45) ) # Export a data frame to a text file using write.csv2()write.csv2(df, file = \"my_data.csv\")Output:" }, { "code": null, "e": 37015, "s": 37006, "text": "Example:" }, { "code": "# R program to illustrate# Exporting data from R # Creating a dataframe df = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45) ) # Export a data frame to a text file using write.csv2()write.csv2(df, file = \"my_data.csv\")", "e": 37305, "s": 37015, "text": null }, { "code": null, "e": 37313, "s": 37305, "text": "Output:" }, { "code": null, "e": 37879, "s": 37313, "text": "write_csv(): This method is also used for to export data to a comma separated (“, ”) values by using the help of readr package.Syntax: write_csv(file, path)Parameters:file: a data frame to be writtenpath: the path to the result fileExample:# R program to illustrate# Exporting data from R # Importing readr librarylibrary(readr) # Creating a dataframe df = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45) ) # Export a data frame using write_csv() write_csv(df, path = \"MyDataFrame.csv\")Output:" }, { "code": null, "e": 37909, "s": 37879, "text": "Syntax: write_csv(file, path)" }, { "code": null, "e": 37986, "s": 37909, "text": "Parameters:file: a data frame to be writtenpath: the path to the result file" }, { "code": null, "e": 37995, "s": 37986, "text": "Example:" }, { "code": "# R program to illustrate# Exporting data from R # Importing readr librarylibrary(readr) # Creating a dataframe df = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45) ) # Export a data frame using write_csv() write_csv(df, path = \"MyDataFrame.csv\")", "e": 38314, "s": 37995, "text": null }, { "code": null, "e": 38322, "s": 38314, "text": "Output:" }, { "code": null, "e": 38329, "s": 38322, "text": "Picked" }, { "code": null, "e": 38340, "s": 38329, "text": "R Language" }, { "code": null, "e": 38438, "s": 38340, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38447, "s": 38438, "text": "Comments" }, { "code": null, "e": 38460, "s": 38447, "text": "Old Comments" }, { "code": null, "e": 38505, "s": 38460, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 38563, "s": 38505, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 38626, "s": 38563, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 38678, "s": 38626, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 38730, "s": 38678, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 38762, "s": 38730, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 38827, "s": 38762, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 38871, "s": 38827, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 38909, "s": 38871, "text": "How to Change Axis Scales in R Plots?" } ]
PyWebIO 1.3.0: Add Tabs, Pin Input, and Update an Input Based on Another Input | by Khuyen Tran | Towards Data Science
PyWebIO is a Python library that makes it easy for you to create a web application like below in a few lines of code. In the last article, I have introduced some basic usage of PyWebIO, but you might want to do more than just those basic functions. Luckily, PyWebIO 1.3.0 introduces more useful tools to create complicated interfaces in a few lines of code. In this article, you will learn how to: Add tabs for better navigation Update one input based on the value of another input Persist the input To install PyWebIO 1.3.0, type: pip install pywebio==1.3.0 PyWebIO 1.3.0 allows you to add tabs to your app like below: To add tabs, simply use the put_tabs widget. The arguments of put_tabs is a list of dictionaries like below: Full code: Sometimes, you might want the options of one input to change depending on the value of another input. For example, in the GIF below, when I change the topic, the options of articles also change. How can we create such dependency between two widgets? First, let’s create 2 dropdowns that don’t depend on each other: As we expect, the options of articles don’t change when we change the topic. Now let’s add a component that will create the dependency between these 2 dropdowns. That is input_update . input_update should be put in the onchange callback of an input function. This means if the input function changes, input_update will be triggered: The codeonchange=lambda t: input_update('article', options=topics_to_articles[t]) updates options of the input 'article' based on which topic is chosen. Full code: Output: PyWebIO has many useful input methods such as select , input , radio , andcheckbox . Normally, the input form will disappear after you submit an input like below: Code: But what if you don’t want the input form to disappear after submitting the input like below? That is when pin comes in handy. To allow your input to persist, first, replace the input.select widget with the pin.put_select widget. While the widgets inpywebio.input will disappear after successful submission, the widgets in pywebio.pin will not disappear after submission. Now we use pin_wait_change to listen to a list of pin widgets. If the value of any widgets changes, the function returns the name and value of that widget. In the GIF below, whenever we change a widget, the shape is printed to the terminal. This means that a new value is assigned to new_shape when we change a widget. To get the new shape and assign it to the current pin widget, use: Last but not least, wrap the code above inside with use_scope(..., clear=True) so that the old image is cleared before the new image appears. Put everything together: Output: You can find a full list of pin widgets here. Congratulations! You have just learned about 3 new features of PyWebIO. There are so many more cool features of PyWebIO that I cannot mention here. I recommend you to check out PyWebIO website for other features. Feel free to play and fork with the source code of this article here: github.com I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
[ { "code": null, "e": 290, "s": 172, "text": "PyWebIO is a Python library that makes it easy for you to create a web application like below in a few lines of code." }, { "code": null, "e": 530, "s": 290, "text": "In the last article, I have introduced some basic usage of PyWebIO, but you might want to do more than just those basic functions. Luckily, PyWebIO 1.3.0 introduces more useful tools to create complicated interfaces in a few lines of code." }, { "code": null, "e": 570, "s": 530, "text": "In this article, you will learn how to:" }, { "code": null, "e": 601, "s": 570, "text": "Add tabs for better navigation" }, { "code": null, "e": 654, "s": 601, "text": "Update one input based on the value of another input" }, { "code": null, "e": 672, "s": 654, "text": "Persist the input" }, { "code": null, "e": 704, "s": 672, "text": "To install PyWebIO 1.3.0, type:" }, { "code": null, "e": 731, "s": 704, "text": "pip install pywebio==1.3.0" }, { "code": null, "e": 792, "s": 731, "text": "PyWebIO 1.3.0 allows you to add tabs to your app like below:" }, { "code": null, "e": 901, "s": 792, "text": "To add tabs, simply use the put_tabs widget. The arguments of put_tabs is a list of dictionaries like below:" }, { "code": null, "e": 912, "s": 901, "text": "Full code:" }, { "code": null, "e": 1014, "s": 912, "text": "Sometimes, you might want the options of one input to change depending on the value of another input." }, { "code": null, "e": 1107, "s": 1014, "text": "For example, in the GIF below, when I change the topic, the options of articles also change." }, { "code": null, "e": 1227, "s": 1107, "text": "How can we create such dependency between two widgets? First, let’s create 2 dropdowns that don’t depend on each other:" }, { "code": null, "e": 1304, "s": 1227, "text": "As we expect, the options of articles don’t change when we change the topic." }, { "code": null, "e": 1412, "s": 1304, "text": "Now let’s add a component that will create the dependency between these 2 dropdowns. That is input_update ." }, { "code": null, "e": 1560, "s": 1412, "text": "input_update should be put in the onchange callback of an input function. This means if the input function changes, input_update will be triggered:" }, { "code": null, "e": 1713, "s": 1560, "text": "The codeonchange=lambda t: input_update('article', options=topics_to_articles[t]) updates options of the input 'article' based on which topic is chosen." }, { "code": null, "e": 1724, "s": 1713, "text": "Full code:" }, { "code": null, "e": 1732, "s": 1724, "text": "Output:" }, { "code": null, "e": 1895, "s": 1732, "text": "PyWebIO has many useful input methods such as select , input , radio , andcheckbox . Normally, the input form will disappear after you submit an input like below:" }, { "code": null, "e": 1901, "s": 1895, "text": "Code:" }, { "code": null, "e": 1995, "s": 1901, "text": "But what if you don’t want the input form to disappear after submitting the input like below?" }, { "code": null, "e": 2131, "s": 1995, "text": "That is when pin comes in handy. To allow your input to persist, first, replace the input.select widget with the pin.put_select widget." }, { "code": null, "e": 2273, "s": 2131, "text": "While the widgets inpywebio.input will disappear after successful submission, the widgets in pywebio.pin will not disappear after submission." }, { "code": null, "e": 2429, "s": 2273, "text": "Now we use pin_wait_change to listen to a list of pin widgets. If the value of any widgets changes, the function returns the name and value of that widget." }, { "code": null, "e": 2592, "s": 2429, "text": "In the GIF below, whenever we change a widget, the shape is printed to the terminal. This means that a new value is assigned to new_shape when we change a widget." }, { "code": null, "e": 2659, "s": 2592, "text": "To get the new shape and assign it to the current pin widget, use:" }, { "code": null, "e": 2801, "s": 2659, "text": "Last but not least, wrap the code above inside with use_scope(..., clear=True) so that the old image is cleared before the new image appears." }, { "code": null, "e": 2826, "s": 2801, "text": "Put everything together:" }, { "code": null, "e": 2834, "s": 2826, "text": "Output:" }, { "code": null, "e": 2880, "s": 2834, "text": "You can find a full list of pin widgets here." }, { "code": null, "e": 3093, "s": 2880, "text": "Congratulations! You have just learned about 3 new features of PyWebIO. There are so many more cool features of PyWebIO that I cannot mention here. I recommend you to check out PyWebIO website for other features." }, { "code": null, "e": 3163, "s": 3093, "text": "Feel free to play and fork with the source code of this article here:" }, { "code": null, "e": 3174, "s": 3163, "text": "github.com" }, { "code": null, "e": 3334, "s": 3174, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." } ]
GDB - Installation
Before you go for installation, check if you already have gdb installed on your Unix system by issuing the following command − $gdb -help If GDB is installed, then it will display all the available options within your GDB. If GDB is not installed, then proceed for a fresh installation. You can install GDB on your system by following the simple steps discussed below. Step 1 − Make sure you have the prerequisites for installing gdb − An ANSI-compliant C compiler (gcc is recommended − note that gdb can debug codes generated by other compilers) An ANSI-compliant C compiler (gcc is recommended − note that gdb can debug codes generated by other compilers) 115 MB of free disk space is required on the partition on which you're going to build gdb. 115 MB of free disk space is required on the partition on which you're going to build gdb. 20 MB of free disk space is required on the partition on which you're going to install gdb. 20 MB of free disk space is required on the partition on which you're going to install gdb. Step 2 − Use the following command to install gdb on linux machine. $ sudo apt-get install libc6-dbg gdb valgrind Step 3 − Now use the following command to find the help information. $gdb -help You now have gdb installed on your system and it is ready to use. Print Add Notes Bookmark this page
[ { "code": null, "e": 1836, "s": 1709, "text": "Before you go for installation, check if you already have gdb installed on your Unix system by issuing the following command −" }, { "code": null, "e": 1849, "s": 1836, "text": "$gdb -help \n" }, { "code": null, "e": 1998, "s": 1849, "text": "If GDB is installed, then it will display all the available options within your GDB. If GDB is not installed, then proceed for a fresh installation." }, { "code": null, "e": 2080, "s": 1998, "text": "You can install GDB on your system by following the simple steps discussed below." }, { "code": null, "e": 2147, "s": 2080, "text": "Step 1 − Make sure you have the prerequisites for installing gdb −" }, { "code": null, "e": 2258, "s": 2147, "text": "An ANSI-compliant C compiler (gcc is recommended − note that gdb can debug codes generated by other compilers)" }, { "code": null, "e": 2369, "s": 2258, "text": "An ANSI-compliant C compiler (gcc is recommended − note that gdb can debug codes generated by other compilers)" }, { "code": null, "e": 2460, "s": 2369, "text": "115 MB of free disk space is required on the partition on which you're going to build gdb." }, { "code": null, "e": 2551, "s": 2460, "text": "115 MB of free disk space is required on the partition on which you're going to build gdb." }, { "code": null, "e": 2643, "s": 2551, "text": "20 MB of free disk space is required on the partition on which you're going to install gdb." }, { "code": null, "e": 2735, "s": 2643, "text": "20 MB of free disk space is required on the partition on which you're going to install gdb." }, { "code": null, "e": 2803, "s": 2735, "text": "Step 2 − Use the following command to install gdb on linux machine." }, { "code": null, "e": 2851, "s": 2803, "text": "$ sudo apt-get install libc6-dbg gdb valgrind \n" }, { "code": null, "e": 2920, "s": 2851, "text": "Step 3 − Now use the following command to find the help information." }, { "code": null, "e": 2933, "s": 2920, "text": "$gdb -help \n" }, { "code": null, "e": 2999, "s": 2933, "text": "You now have gdb installed on your system and it is ready to use." }, { "code": null, "e": 3006, "s": 2999, "text": " Print" }, { "code": null, "e": 3017, "s": 3006, "text": " Add Notes" } ]
JavaScript program to take in a binary number as a string and returns its numerical equivalent in base 10
We are required to write a JavaScript function that takes in a binary number as a string and returns its numerical equivalent in base 10. Therefore, let’s write the code for the function. This one is quite simple, we iterate over the string using a for loop and for each passing bit, we double the number with adding the current bit value to it like this − const binaryToDecimal = binaryStr => { let num = 0; for(let i = 0; i < binaryStr.length; i++){ num *= 2; num += Number(binaryStr[i]); }; return num; }; console.log(binaryToDecimal('1101')); console.log(binaryToDecimal('1101000')); console.log(binaryToDecimal('10101')); The output in the console will be − 13 104 21
[ { "code": null, "e": 1250, "s": 1062, "text": "We are required to write a JavaScript function that takes in a binary number as a string and\nreturns its numerical equivalent in base 10. Therefore, let’s write the code for the function." }, { "code": null, "e": 1419, "s": 1250, "text": "This one is quite simple, we iterate over the string using a for loop and for each passing bit, we\ndouble the number with adding the current bit value to it like this −" }, { "code": null, "e": 1713, "s": 1419, "text": "const binaryToDecimal = binaryStr => {\n let num = 0;\n for(let i = 0; i < binaryStr.length; i++){\n num *= 2;\n num += Number(binaryStr[i]);\n };\n return num;\n};\nconsole.log(binaryToDecimal('1101'));\nconsole.log(binaryToDecimal('1101000'));\nconsole.log(binaryToDecimal('10101'));" }, { "code": null, "e": 1749, "s": 1713, "text": "The output in the console will be −" }, { "code": null, "e": 1759, "s": 1749, "text": "13\n104\n21" } ]
What is Context on Android?
it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application). In the below program you will see that we have created a textView dynamically and passed context. This context is used to get the information about the environment. This example demonstrates how do I display context in an android textView. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/linearLayout" android:orientation="vertical" android:padding="16sp" tools:context=".MainActivity"> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout linearLayout = findViewById(R.id.linearLayout); TextView textViewContext = new TextView(getApplicationContext()); textViewContext.setTextSize(30); textViewContext.setText("Application Context"); textViewContext.setTextColor(Color.RED); TextView textViewActivityContext = new TextView(this); textViewActivityContext.setTextSize(30); textViewActivityContext.setText("Activity Context"); linearLayout.addView(textViewContext); linearLayout.addView(textViewActivityContext); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
[ { "code": null, "e": 1470, "s": 1062, "text": "it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application). In the below program you will see that we have created a textView dynamically and passed context. This context is used to get the information about the environment." }, { "code": null, "e": 1545, "s": 1470, "text": "This example demonstrates how do I display context in an android textView." }, { "code": null, "e": 1674, "s": 1545, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1739, "s": 1674, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2124, "s": 1739, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:id=\"@+id/linearLayout\"\n android:orientation=\"vertical\"\n android:padding=\"16sp\"\n tools:context=\".MainActivity\">\n</LinearLayout>" }, { "code": null, "e": 2181, "s": 2124, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3114, "s": 2181, "text": "import android.graphics.Color;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n LinearLayout linearLayout = findViewById(R.id.linearLayout);\n TextView textViewContext = new TextView(getApplicationContext());\n textViewContext.setTextSize(30);\n textViewContext.setText(\"Application Context\");\n textViewContext.setTextColor(Color.RED);\n TextView textViewActivityContext = new TextView(this);\n textViewActivityContext.setTextSize(30);\n textViewActivityContext.setText(\"Activity Context\");\n linearLayout.addView(textViewContext);\n linearLayout.addView(textViewActivityContext);\n }\n}" }, { "code": null, "e": 3169, "s": 3114, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3839, "s": 3169, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4186, "s": 3839, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" } ]
Text Processing Techniques on Twitter data | by Ramya Vidiyala | Towards Data Science
There is a huge amount of data in text format. Analyzing data in the text format is the most complex task for a machine as it’s difficult for a machine to understand the semantics behind the text. To serve this purpose we process text data into a machine-understandable format. Text Processing is simply converting the data in text format to numerical values (or vectors ) so that we can give these vectors as input to the machine and analyze the data using the concepts of algebra. However, when we perform such transformation, there could be data loss. The key is to maintain an equilibrium between conversion and retaining the data. Before processing the text, preprocessing of text is essential. To have a quick glance at what text preprocessing is, check this article. medium.com In this article, we will discuss various techniques to perform text processing. Before getting started, let us understand a few commonly used terms. Each text data point is called a Document The entire set of documents is called Corpus Text processing can be done using the following techniques, Bag of WordsTF-IDFWord2Vec Bag of Words TF-IDF Word2Vec Now let us begin exploring each technique in detail. Bag of Words does a simple transformation of the document to vector by using a dictionary of unique words. This is done in just two steps, Create a dictionary of all the unique words in the data corpus in a vector form. Let the number of unique words in the corpus be, ‘d’. So each word is a dimension and hence this dictionary vector is a d-dimension vector. For each document, say, ri we create a vector, say, vi. Now, this vi which has d-dimensions can be constructed in two ways: For each document, the vi is constructed in accordance with the dictionary such that each word in the dictionary is reproduced by the number of times that word is present in the document.For each document, the vi is constructed in accordance with the dictionary such that each word in the dictionary is reproduced to, For each document, the vi is constructed in accordance with the dictionary such that each word in the dictionary is reproduced by the number of times that word is present in the document. For each document, the vi is constructed in accordance with the dictionary such that each word in the dictionary is reproduced to, 1 if the word is present in the document or 0 if the word is not present in the document This type is known as Binary Bag of Words. Now, we have vectors for each document and a dictionary that has a set of unique words of the data corpus. These vectors can be analyzed by plotting in d-dimension space or calculating distance between vectors to get the similarity (the closer the vectors are, more similar they are) Problem: Bag of Words does not consider the semantic of the words. Means words that have the same semantic as tasty, delicious are classified into 2 different words.Solution: Preprocessing the data in using techniques like Stemming and Lemmatization. Problem: Bag of Words does not retain the sequential information of the document which means, ‘not good’ which is clearly not- good. Bag of words classifies it as ‘not’ and ‘good’, which is clearly not good. Solution: Instead of creating vectors where each cell is a word, we can create vectors where each cell has 2 words ( called bi-grams) or 3 words (called tri-grams). Using these n-grams, sequential information can be retained. However, when we use n-grams instead of uni-grams, the dimensionality of features increases. There are three elements here — word, document, corpus. Term Frequency — Inverse Document Frequency, TF-IDF, in short, uses the relationship between these to convert text data into vectors. Term Frequency says about the relationship between a word and a document. Whereas, Inverse Document Frequency says about the relationship between a word and the corpus. Term frequency is the probability of the word wj in the document ri. And is calculated as, If Term Frequency of a word in a review is high implies, the word is frequent in that review. If Term Frequency of a word in a review is low implies, the word is rare in that review. Inverse Document Frequency says how frequently the word is in the entire corpus. And is calculated as, If Inverse Document Frequency is low, implies the word is frequent in the corpus.If Inverse Document Frequency is high, implies the word is rare in the corpus. The reason to use log instead of the simple inverse ratio is scaling. Term Frequency which is a probability ranges between 0 and 1. When we simply take this inverse ratio it will be a huge value, thus the entire TF-IDF value will be biased to IDF. This is one of the simple and highly accepted reasons for using the log in IDF term. TF-IDF of a word in review is TF(word, review) *IDF(word, document corpus). Now in the vector form of each document, we have this TF-IDF of the word. Converting a document into a vector, using TF-IDF values is called TF-IDF vectorization. TF-IDF vectorization gives high importance to words which are frequent in a document (from TF) rare in the corpus (from IDF) In Bag of Words and TF-IDF, we convert sentences into vectors. But in Word2Vec, we convert word into a vector. Hence the name, word2vec! Word2Vec takes as its input a large corpus of text and produces a vector space, typically of several hundred dimensions, with each unique word in the corpus being assigned a corresponding vector in the space. Word vectors are positioned in the vector space such that words that share common contexts in the corpus are located close to one another in the space. Each word is closer in the space to the word which has the same semantic(meaning like woman, girl)It retains the relationship between words (vector of man to woman is parallel to the vector of king to queen) Each word is closer in the space to the word which has the same semantic(meaning like woman, girl) It retains the relationship between words (vector of man to woman is parallel to the vector of king to queen) In this article, we will be using Customer Support on the Twitter dataset from Kaggle. www.kaggle.com The Customer Support on the Twitter dataset is a large, modern corpus of tweets and replies to aid innovation in natural language understanding and conversational models, and for the study of modern customer support practices and impact. This dataset offers a large corpus of modern English (mostly) conversations between consumers and customer support agents on Twitter. Let us use the preprocessed data and perform each text preprocessing on it. Let us look at the preprocessed data data["preprocessed_text"] Sckit learns provides us with many libraries. It makes us so easy to implement any functionality in a single line. from sklearn.feature_extraction.text import CountVectorizer Sckit learn provides CountVectorizer to perform Bag of Words. bow=CountVectorizer( min_df=2, max_features=1000)bow.fit(data['preprocessed_text'])bow_df=bow.transform(data['preprocessed_text']).toarray() Creating an object of count vectorizer and fitting, transforming with the preprocessed data. bow_df is a sparse vector which contains more number of zeros than ones. from sklearn.feature_extraction.text import TfidfVectorizer Sckit learn provides TFIDfVectorizer to perform TF-IDF Vectorization. tfidf = TfidfVectorizer( min_df=2, max_features=1000)tfidf.fit(data['preprocessed_text'])tfidf_df=bow.transform(data['preprocessed_text']).toarray() tfidf_df contains the tf-idf values of each word in a document in a 1000 dimensional vector. Google provides a huge list of vectors trained on humongous data of google news. To use these vectors, we need to import Gensim. import gensimtokenize=data['preprocessed_text'].apply(lambda x: x.split())w2vec_model=gensim.models.Word2Vec(tokenize,min_count = 1, size = 100, window = 5, sg = 1)w2vec_model.train(tokenize,total_examples= len(data['preprocessed_text']),epochs=20) Output : (18237, 22200) data points. This means 18237 data points of text is now converted to a 22200-dimension vector each. There is no obvious answer to this question: it really depends on the application. For example, the Bag of Words is commonly used for document classification applications where the occurrence of each word is used as a feature for training a classifier. TF-IDF is used by search engines like Google, as a ranking factor for content. When the application is about understanding the context of words or, detecting the similarity of the words or, translating given documents into another language, which requires a lot of information on the document, Word2vec comes into the picture. Thanks for the read. I am going to write more beginner-friendly posts in the future. Follow me up on Medium to be informed about them. I welcome feedback and can be reached out on Twitter ramya_vidiyala and LinkedIn RamyaVidiyala. Happy learning!
[ { "code": null, "e": 450, "s": 172, "text": "There is a huge amount of data in text format. Analyzing data in the text format is the most complex task for a machine as it’s difficult for a machine to understand the semantics behind the text. To serve this purpose we process text data into a machine-understandable format." }, { "code": null, "e": 655, "s": 450, "text": "Text Processing is simply converting the data in text format to numerical values (or vectors ) so that we can give these vectors as input to the machine and analyze the data using the concepts of algebra." }, { "code": null, "e": 808, "s": 655, "text": "However, when we perform such transformation, there could be data loss. The key is to maintain an equilibrium between conversion and retaining the data." }, { "code": null, "e": 946, "s": 808, "text": "Before processing the text, preprocessing of text is essential. To have a quick glance at what text preprocessing is, check this article." }, { "code": null, "e": 957, "s": 946, "text": "medium.com" }, { "code": null, "e": 1037, "s": 957, "text": "In this article, we will discuss various techniques to perform text processing." }, { "code": null, "e": 1106, "s": 1037, "text": "Before getting started, let us understand a few commonly used terms." }, { "code": null, "e": 1148, "s": 1106, "text": "Each text data point is called a Document" }, { "code": null, "e": 1193, "s": 1148, "text": "The entire set of documents is called Corpus" }, { "code": null, "e": 1253, "s": 1193, "text": "Text processing can be done using the following techniques," }, { "code": null, "e": 1280, "s": 1253, "text": "Bag of WordsTF-IDFWord2Vec" }, { "code": null, "e": 1293, "s": 1280, "text": "Bag of Words" }, { "code": null, "e": 1300, "s": 1293, "text": "TF-IDF" }, { "code": null, "e": 1309, "s": 1300, "text": "Word2Vec" }, { "code": null, "e": 1362, "s": 1309, "text": "Now let us begin exploring each technique in detail." }, { "code": null, "e": 1501, "s": 1362, "text": "Bag of Words does a simple transformation of the document to vector by using a dictionary of unique words. This is done in just two steps," }, { "code": null, "e": 1722, "s": 1501, "text": "Create a dictionary of all the unique words in the data corpus in a vector form. Let the number of unique words in the corpus be, ‘d’. So each word is a dimension and hence this dictionary vector is a d-dimension vector." }, { "code": null, "e": 1846, "s": 1722, "text": "For each document, say, ri we create a vector, say, vi. Now, this vi which has d-dimensions can be constructed in two ways:" }, { "code": null, "e": 2164, "s": 1846, "text": "For each document, the vi is constructed in accordance with the dictionary such that each word in the dictionary is reproduced by the number of times that word is present in the document.For each document, the vi is constructed in accordance with the dictionary such that each word in the dictionary is reproduced to," }, { "code": null, "e": 2352, "s": 2164, "text": "For each document, the vi is constructed in accordance with the dictionary such that each word in the dictionary is reproduced by the number of times that word is present in the document." }, { "code": null, "e": 2483, "s": 2352, "text": "For each document, the vi is constructed in accordance with the dictionary such that each word in the dictionary is reproduced to," }, { "code": null, "e": 2527, "s": 2483, "text": "1 if the word is present in the document or" }, { "code": null, "e": 2572, "s": 2527, "text": "0 if the word is not present in the document" }, { "code": null, "e": 2615, "s": 2572, "text": "This type is known as Binary Bag of Words." }, { "code": null, "e": 2755, "s": 2615, "text": "Now, we have vectors for each document and a dictionary that has a set of unique words of the data corpus. These vectors can be analyzed by" }, { "code": null, "e": 2788, "s": 2755, "text": "plotting in d-dimension space or" }, { "code": null, "e": 2899, "s": 2788, "text": "calculating distance between vectors to get the similarity (the closer the vectors are, more similar they are)" }, { "code": null, "e": 3150, "s": 2899, "text": "Problem: Bag of Words does not consider the semantic of the words. Means words that have the same semantic as tasty, delicious are classified into 2 different words.Solution: Preprocessing the data in using techniques like Stemming and Lemmatization." }, { "code": null, "e": 3677, "s": 3150, "text": "Problem: Bag of Words does not retain the sequential information of the document which means, ‘not good’ which is clearly not- good. Bag of words classifies it as ‘not’ and ‘good’, which is clearly not good. Solution: Instead of creating vectors where each cell is a word, we can create vectors where each cell has 2 words ( called bi-grams) or 3 words (called tri-grams). Using these n-grams, sequential information can be retained. However, when we use n-grams instead of uni-grams, the dimensionality of features increases." }, { "code": null, "e": 3867, "s": 3677, "text": "There are three elements here — word, document, corpus. Term Frequency — Inverse Document Frequency, TF-IDF, in short, uses the relationship between these to convert text data into vectors." }, { "code": null, "e": 4036, "s": 3867, "text": "Term Frequency says about the relationship between a word and a document. Whereas, Inverse Document Frequency says about the relationship between a word and the corpus." }, { "code": null, "e": 4127, "s": 4036, "text": "Term frequency is the probability of the word wj in the document ri. And is calculated as," }, { "code": null, "e": 4310, "s": 4127, "text": "If Term Frequency of a word in a review is high implies, the word is frequent in that review. If Term Frequency of a word in a review is low implies, the word is rare in that review." }, { "code": null, "e": 4413, "s": 4310, "text": "Inverse Document Frequency says how frequently the word is in the entire corpus. And is calculated as," }, { "code": null, "e": 4573, "s": 4413, "text": "If Inverse Document Frequency is low, implies the word is frequent in the corpus.If Inverse Document Frequency is high, implies the word is rare in the corpus." }, { "code": null, "e": 4906, "s": 4573, "text": "The reason to use log instead of the simple inverse ratio is scaling. Term Frequency which is a probability ranges between 0 and 1. When we simply take this inverse ratio it will be a huge value, thus the entire TF-IDF value will be biased to IDF. This is one of the simple and highly accepted reasons for using the log in IDF term." }, { "code": null, "e": 4982, "s": 4906, "text": "TF-IDF of a word in review is TF(word, review) *IDF(word, document corpus)." }, { "code": null, "e": 5145, "s": 4982, "text": "Now in the vector form of each document, we have this TF-IDF of the word. Converting a document into a vector, using TF-IDF values is called TF-IDF vectorization." }, { "code": null, "e": 5207, "s": 5145, "text": "TF-IDF vectorization gives high importance to words which are" }, { "code": null, "e": 5240, "s": 5207, "text": "frequent in a document (from TF)" }, { "code": null, "e": 5270, "s": 5240, "text": "rare in the corpus (from IDF)" }, { "code": null, "e": 5407, "s": 5270, "text": "In Bag of Words and TF-IDF, we convert sentences into vectors. But in Word2Vec, we convert word into a vector. Hence the name, word2vec!" }, { "code": null, "e": 5768, "s": 5407, "text": "Word2Vec takes as its input a large corpus of text and produces a vector space, typically of several hundred dimensions, with each unique word in the corpus being assigned a corresponding vector in the space. Word vectors are positioned in the vector space such that words that share common contexts in the corpus are located close to one another in the space." }, { "code": null, "e": 5976, "s": 5768, "text": "Each word is closer in the space to the word which has the same semantic(meaning like woman, girl)It retains the relationship between words (vector of man to woman is parallel to the vector of king to queen)" }, { "code": null, "e": 6075, "s": 5976, "text": "Each word is closer in the space to the word which has the same semantic(meaning like woman, girl)" }, { "code": null, "e": 6185, "s": 6075, "text": "It retains the relationship between words (vector of man to woman is parallel to the vector of king to queen)" }, { "code": null, "e": 6272, "s": 6185, "text": "In this article, we will be using Customer Support on the Twitter dataset from Kaggle." }, { "code": null, "e": 6287, "s": 6272, "text": "www.kaggle.com" }, { "code": null, "e": 6659, "s": 6287, "text": "The Customer Support on the Twitter dataset is a large, modern corpus of tweets and replies to aid innovation in natural language understanding and conversational models, and for the study of modern customer support practices and impact. This dataset offers a large corpus of modern English (mostly) conversations between consumers and customer support agents on Twitter." }, { "code": null, "e": 6772, "s": 6659, "text": "Let us use the preprocessed data and perform each text preprocessing on it. Let us look at the preprocessed data" }, { "code": null, "e": 6798, "s": 6772, "text": "data[\"preprocessed_text\"]" }, { "code": null, "e": 6913, "s": 6798, "text": "Sckit learns provides us with many libraries. It makes us so easy to implement any functionality in a single line." }, { "code": null, "e": 6973, "s": 6913, "text": "from sklearn.feature_extraction.text import CountVectorizer" }, { "code": null, "e": 7035, "s": 6973, "text": "Sckit learn provides CountVectorizer to perform Bag of Words." }, { "code": null, "e": 7176, "s": 7035, "text": "bow=CountVectorizer( min_df=2, max_features=1000)bow.fit(data['preprocessed_text'])bow_df=bow.transform(data['preprocessed_text']).toarray()" }, { "code": null, "e": 7342, "s": 7176, "text": "Creating an object of count vectorizer and fitting, transforming with the preprocessed data. bow_df is a sparse vector which contains more number of zeros than ones." }, { "code": null, "e": 7402, "s": 7342, "text": "from sklearn.feature_extraction.text import TfidfVectorizer" }, { "code": null, "e": 7472, "s": 7402, "text": "Sckit learn provides TFIDfVectorizer to perform TF-IDF Vectorization." }, { "code": null, "e": 7621, "s": 7472, "text": "tfidf = TfidfVectorizer( min_df=2, max_features=1000)tfidf.fit(data['preprocessed_text'])tfidf_df=bow.transform(data['preprocessed_text']).toarray()" }, { "code": null, "e": 7714, "s": 7621, "text": "tfidf_df contains the tf-idf values of each word in a document in a 1000 dimensional vector." }, { "code": null, "e": 7843, "s": 7714, "text": "Google provides a huge list of vectors trained on humongous data of google news. To use these vectors, we need to import Gensim." }, { "code": null, "e": 8092, "s": 7843, "text": "import gensimtokenize=data['preprocessed_text'].apply(lambda x: x.split())w2vec_model=gensim.models.Word2Vec(tokenize,min_count = 1, size = 100, window = 5, sg = 1)w2vec_model.train(tokenize,total_examples= len(data['preprocessed_text']),epochs=20)" }, { "code": null, "e": 8217, "s": 8092, "text": "Output : (18237, 22200) data points. This means 18237 data points of text is now converted to a 22200-dimension vector each." }, { "code": null, "e": 8300, "s": 8217, "text": "There is no obvious answer to this question: it really depends on the application." }, { "code": null, "e": 8470, "s": 8300, "text": "For example, the Bag of Words is commonly used for document classification applications where the occurrence of each word is used as a feature for training a classifier." }, { "code": null, "e": 8549, "s": 8470, "text": "TF-IDF is used by search engines like Google, as a ranking factor for content." }, { "code": null, "e": 8797, "s": 8549, "text": "When the application is about understanding the context of words or, detecting the similarity of the words or, translating given documents into another language, which requires a lot of information on the document, Word2vec comes into the picture." } ]
Generation of triangular wave using DAC interface
We write an 8085 assembly language program for the generation of triangular waveform using the Digital to Analog Converter (DAC) interface. The display of the waveform is seen on the CRO. Let us consider a problem solution in this domain. The problem states that: To get unipolar output, J1 is shorted to J2 on the interface. To display the waveform on a CRO, connect pin 1 of connector P1 to CRO signal pin, and pin 2 of connector P1 to CRO ground pin. ; FILE NAME DAC_TO_TRIANG.ASM ORG C100H X DW 00FFH ; the fall of rise and time I proportional directly to the value. ORG C000H PA EQU D8H PB EQU D9H PC EQU DAH CTRL EQU DBH MVI A, 88H OUT CTRL ; Purpose to configure 8255 ports ; The next 7 instructions will generate rising portion of the triangular waveform. ; And it is done by sending to DAC through Port A values from 00H to FFH, ; in steps of 01. Also the increment will be done after a small time delay here. LOOP: MVI A, 00H ASCEND: OUT PA PUSH PSW CALL DELAY POP PSW INR A JNZ ASCEND DCR A ; Now A contents will be FFH DESCEND: OUT PA PUSH PSW CALL DELAY POP PSW DCR A CPI FFH JNZ DESCEND JMP LOOP ; These Subroutines are used only for the generation of delay ; which is proportional to all the contents of word located at X. DELAY: LHLD X AGAIN: DCX H MOV A, H ORA L JNZ AGAIN RET
[ { "code": null, "e": 1250, "s": 1062, "text": "We write an 8085 assembly language program for the generation of triangular waveform using the Digital to Analog Converter (DAC) interface. The display of the waveform is seen on the CRO." }, { "code": null, "e": 1516, "s": 1250, "text": "Let us consider a problem solution in this domain. The problem states that: To get unipolar output, J1 is shorted to J2 on the interface. To display the waveform on a CRO, connect pin 1 of connector P1 to CRO signal pin, and pin 2 of connector P1 to CRO ground pin." }, { "code": null, "e": 2367, "s": 1516, "text": "; FILE NAME DAC_TO_TRIANG.ASM\nORG C100H\nX DW 00FFH ; the fall of rise and time I proportional directly to the value.\n\nORG C000H\nPA EQU D8H\nPB EQU D9H\nPC EQU DAH\nCTRL EQU DBH\n\nMVI A, 88H\nOUT CTRL ; Purpose to configure 8255 ports\n; The next 7 instructions will generate rising portion of the triangular waveform.\n; And it is done by sending to DAC through Port A values from 00H to FFH,\n; in steps of 01. Also the increment will be done after a small time delay here.\n\nLOOP: MVI A, 00H\nASCEND: OUT PA\nPUSH PSW\nCALL DELAY\n\nPOP PSW\nINR A\nJNZ ASCEND\n\nDCR A ; Now A contents will be FFH\n\nDESCEND: OUT PA\nPUSH PSW\n\nCALL DELAY\n\nPOP PSW\nDCR A\nCPI FFH\nJNZ DESCEND\n\nJMP LOOP\n; These Subroutines are used only for the generation of delay\n; which is proportional to all the contents of word located at X.\n\nDELAY: LHLD X\nAGAIN: DCX H\nMOV A, H\nORA L\nJNZ AGAIN\nRET\n" } ]
How to Write/create a JSON file using Java?
JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc. Sample JSON document − { "book": [ { "id": "01", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "07", "language": "C++", "edition": "second", "author": "E.Balagurusamy" } ] } The json-simple is a light weight library which is used to process JSON objects. Using this you can read or, write the contents of a JSON document using Java program. Following is the maven dependency for the JSON-simple library − <dependencies> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency> </dependencies> Paste this with in the <dependencies> </dependencies> tag at the end of your pom.xml file. (before </project> tag) To create a JSON document using a Java program − Instantiate the JSONObject class of the json-simple library. //Creating a JSONObject object JSONObject jsonObject = new JSONObject(); Insert the required key-value pairs using the put() method of the JSONObject class. jsonObject.put("key", "value"); Write the created JSON object into a file using the FileWriter class as − FileWriter file = new FileWriter("E:/output.json"); file.write(jsonObject.toJSONString()); file.close(); Following Java program creates a JSON object and writes it into a file named output.json. import java.io.FileWriter; import java.io.IOException; import org.json.simple.JSONObject; public class CreatingJSONDocument { public static void main(String args[]) { //Creating a JSONObject object JSONObject jsonObject = new JSONObject(); //Inserting key-value pairs into the json object jsonObject.put("ID", "1"); jsonObject.put("First_Name", "Shikhar"); jsonObject.put("Last_Name", "Dhawan"); jsonObject.put("Date_Of_Birth", "1981-12-05"); jsonObject.put("Place_Of_Birth", "Delhi"); jsonObject.put("Country", "India"); try { FileWriter file = new FileWriter("E:/output.json"); file.write(jsonObject.toJSONString()); file.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("JSON file created: "+jsonObject); } } JSON file created: { "First_Name":"Shikhar", "Place_Of_Birth":"Delhi", "Last_Name":"Dhawan", "Country":"India", "ID":"1", "Date_Of_Birth": "1981-12-05"} If you observe the contents of the JSON file you can see the created data as −
[ { "code": null, "e": 1306, "s": 1062, "text": "JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc. Sample JSON document −" }, { "code": null, "e": 1592, "s": 1306, "text": "{\n \"book\": [\n {\n \"id\": \"01\",\n \"language\": \"Java\",\n \"edition\": \"third\",\n \"author\": \"Herbert Schildt\"\n },\n {\n \"id\": \"07\",\n \"language\": \"C++\",\n \"edition\": \"second\",\n \"author\": \"E.Balagurusamy\"\n }\n ]\n}" }, { "code": null, "e": 1759, "s": 1592, "text": "The json-simple is a light weight library which is used to process JSON objects. Using this you can read or, write the contents of a JSON document using Java program." }, { "code": null, "e": 1823, "s": 1759, "text": "Following is the maven dependency for the JSON-simple library −" }, { "code": null, "e": 2013, "s": 1823, "text": "<dependencies>\n <dependency>\n <groupId>com.googlecode.json-simple</groupId>\n <artifactId>json-simple</artifactId>\n <version>1.1.1</version>\n </dependency>\n</dependencies>" }, { "code": null, "e": 2128, "s": 2013, "text": "Paste this with in the <dependencies> </dependencies> tag at the end of your pom.xml file. (before </project> tag)" }, { "code": null, "e": 2177, "s": 2128, "text": "To create a JSON document using a Java program −" }, { "code": null, "e": 2238, "s": 2177, "text": "Instantiate the JSONObject class of the json-simple library." }, { "code": null, "e": 2311, "s": 2238, "text": "//Creating a JSONObject object\nJSONObject jsonObject = new JSONObject();" }, { "code": null, "e": 2395, "s": 2311, "text": "Insert the required key-value pairs using the put() method of the JSONObject class." }, { "code": null, "e": 2427, "s": 2395, "text": "jsonObject.put(\"key\", \"value\");" }, { "code": null, "e": 2501, "s": 2427, "text": "Write the created JSON object into a file using the FileWriter class as −" }, { "code": null, "e": 2606, "s": 2501, "text": "FileWriter file = new FileWriter(\"E:/output.json\");\nfile.write(jsonObject.toJSONString());\nfile.close();" }, { "code": null, "e": 2696, "s": 2606, "text": "Following Java program creates a JSON object and writes it into a file named output.json." }, { "code": null, "e": 3600, "s": 2696, "text": "import java.io.FileWriter;\nimport java.io.IOException;\nimport org.json.simple.JSONObject;\npublic class CreatingJSONDocument {\n public static void main(String args[]) {\n //Creating a JSONObject object\n JSONObject jsonObject = new JSONObject();\n //Inserting key-value pairs into the json object\n jsonObject.put(\"ID\", \"1\");\n jsonObject.put(\"First_Name\", \"Shikhar\");\n jsonObject.put(\"Last_Name\", \"Dhawan\");\n jsonObject.put(\"Date_Of_Birth\", \"1981-12-05\");\n jsonObject.put(\"Place_Of_Birth\", \"Delhi\");\n jsonObject.put(\"Country\", \"India\");\n try {\n FileWriter file = new FileWriter(\"E:/output.json\");\n file.write(jsonObject.toJSONString());\n file.close();\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n System.out.println(\"JSON file created: \"+jsonObject);\n }\n}" }, { "code": null, "e": 3753, "s": 3600, "text": "JSON file created: {\n\"First_Name\":\"Shikhar\",\n\"Place_Of_Birth\":\"Delhi\",\n\"Last_Name\":\"Dhawan\",\n\"Country\":\"India\",\n\"ID\":\"1\",\n\"Date_Of_Birth\":\n\"1981-12-05\"}" }, { "code": null, "e": 3832, "s": 3753, "text": "If you observe the contents of the JSON file you can see the created data as −" } ]
Rat Maze With Multiple Jumps | Practice | GeeksforGeeks
A Maze is given as n*n matrix of blocks where source block is the upper left most block i.e., matrix[0][0] and destination block is lower rightmost block i.e., matrix[n-1][n-1]. A rat starts from source and has to reach the destination. The rat can move in only two directions: first forward if possible or down. If multiple solutions exist, the shortest earliest hop will be accepted. For the same hop distance at any point, forward will be preferred over downward. In the maze matrix, 0 means the block is the dead end and non-zero number means the block can be used in the path from source to destination. The non-zero value of mat[i][j] indicates number of maximum jumps rat can make from cell mat[i][j]. In this variation, Rat is allowed to jump multiple steps at a time instead of 1. Find a matrix which describes the position the rat to reach at the destination. Example: Input: {{2,1,0,0},{3,0,0,1},{0,1,0,1}, {0,0,0,1}} Output: {{1,0,0,0},{1,0,0,1},{0,0,0,1}, {0,0,0,1}} Explanation: Rat started with matrix[0][0] and can jump up to 2 steps right/down. First check matrix[0][1] as it is 1, next check matrix[0][2] ,this won't lead to the solution. Then check matrix[1][0], as this is 3(non-zero) ,so we can make 3 jumps to reach matrix[1][3]. From matrix[1][3] we can move downwards taking 1 jump each time to reach destination at matrix[3][3]. Example 2: Input: {{2,1,0,0},{2,0,0,1},{0,1,0,1}, {0,0,0,1}} Output: {{-1}} Explanation: As no path exists so, -1. Your Task: You don't need to read or print anyhting, Your task is to complete the function ShortestDistance() which takes the matrix as input parameter and returns a matrix of size n if path exists otherwise returns a matrix of 1x1 which contains -1. In output matrix, 1 at (i, j) represents the cell is taken into the path otherwise 0 if any path exists. Expected Time Complexity: O(n*n*k) where k is max(matrix[i][j]) Expected Space Complexity: O(1) Constraints: 1 <= n <= 50 1 <= matrix[i][j] <= 20 +3 rainx6 months ago EASY QUESTION We first try the forward way i.e. y+jump and then we try x+jump since according to question we have to prioritize forward direction path. Just set that cell to 1 and if it doesn't make a path backtrack and make it 0 again. CODE IMPLEMENTATION bool isSafe(vector<vector<int>> &matrix, int x, int y){ if(x>=matrix.size() || y>=matrix[0].size() || matrix[x][y]==0){ return false; } return true; } bool helper(vector<vector<int>> &matrix, vector<vector<int>> &res, int x, int y, int n){ if(x==n-1 && y==n-1){ res[x][y]=1; return true; } if(isSafe(matrix,x,y)==true){ res[x][y]=1; for(int i=1;i<=matrix[x][y] && i<n;i++){ if(helper(matrix,res,x,y+i,n)==true){ return true; } if(helper(matrix,res,x+i,y,n)==true){ return true; } } res[x][y]=0; return false; } return false; } vector<vector<int>> ShortestDistance(vector<vector<int>> &matrix){ int n=matrix.size(); if(matrix[0][0]==0 && n!=1){ return {{-1}}; } vector<vector<int>> res(n,vector<int>(n,0)); helper(matrix,res,0,0,n); return res; } keep coding and upvote -2 shivam1706207 months ago WHATS WRONG WITH CODE ?? OR PROVIDE SOLUTION !! bool issafe(vector<vector<int>>&matrix,int x,int y,int n) { if(x>=0 && x<n && y>=0 && y<n && matrix[x][y]!=0) { return true; } return false; } bool mazehelper(vector<vector<int>>&matrix,int x,int y,vector<vector<int>> ans ,int n,int arr[MAX][MAX]) { if(x==n-1 && y==n-1) { arr[x][y]=1; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { ans[i][j]=arr[i][j]; } } return true; } if(issafe(matrix,x,y,n)==true) { arr[x][y]=1; for(int i=1;i<=matrix[x][y] && i<n;i++) { if(mazehelper(matrix,x+i,y,ans,n,arr)==true) { return true; } if(mazehelper(matrix,x,y+i,ans,n,arr)==true) { return true; } } arr[x][y]=0; return false; } return false; }vector<vector<int>> ShortestDistance(vector<vector<int>>&matrix){ // Code here int n=matrix.size(); int arr[MAX][MAX]; vector<vector<int>> ans(n,vector<int>(n));/* for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { arr[i][j]=0; } }*/ memset(arr,0,n*n*sizeof(int)); bool res=mazehelper(matrix,0,0,ans,n,arr); if(res==true) { return ans; } else { vector<vector<int>> buffer(1,vector<int>(1,-1));// buffer[0][0]=-1; return buffer; } } +1 Navin Ojha8 months ago Navin Ojha Very Tricky Question : Destination will not always be set to 1 so make sure you set it to 1 and then traverse. 0 Shivesh Bharti10 months ago Shivesh Bharti there is error in the matrix name in python driver code ,its written matirx instead of matrix please fix that soon 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": 1098, "s": 226, "text": "A Maze is given as n*n matrix of blocks where source block is the upper left most block i.e., matrix[0][0] and destination block is lower rightmost block i.e., matrix[n-1][n-1]. A rat starts from source and has to reach the destination. The rat can move in only two directions: first forward if possible or down. If multiple solutions exist, the shortest earliest hop will be accepted. For the same hop distance at any point, forward will be preferred over downward. In the maze matrix, 0 means the block is the dead end and non-zero number means the block can be used in the path from source to destination. The non-zero value of mat[i][j] indicates number of maximum jumps rat can make from cell mat[i][j]. In this variation, Rat is allowed to jump multiple steps at a time instead of 1. Find a matrix which describes the position the rat to reach at the destination.\n " }, { "code": null, "e": 1107, "s": 1098, "text": "Example:" }, { "code": null, "e": 1590, "s": 1107, "text": "Input: {{2,1,0,0},{3,0,0,1},{0,1,0,1},\n{0,0,0,1}}\nOutput: {{1,0,0,0},{1,0,0,1},{0,0,0,1},\n{0,0,0,1}}\nExplanation: Rat started with matrix[0][0] and \ncan jump up to 2 steps right/down. First check \nmatrix[0][1] as it is 1, next check \nmatrix[0][2] ,this won't lead to the solution. \nThen check matrix[1][0], as this is 3(non-zero)\n,so we can make 3 jumps to reach matrix[1][3]. \nFrom matrix[1][3] we can move downwards taking \n1 jump each time to reach destination at \nmatrix[3][3].\n" }, { "code": null, "e": 1601, "s": 1590, "text": "Example 2:" }, { "code": null, "e": 1706, "s": 1601, "text": "Input: {{2,1,0,0},{2,0,0,1},{0,1,0,1},\n{0,0,0,1}}\nOutput: {{-1}}\nExplanation: As no path exists so, -1.\n" }, { "code": null, "e": 2066, "s": 1708, "text": "Your Task:\nYou don't need to read or print anyhting, Your task is to complete the function ShortestDistance() which takes the matrix as input parameter and returns a matrix of size n if path exists otherwise returns a matrix of 1x1 which contains -1. In output matrix, 1 at (i, j) represents the cell is taken into the path otherwise 0 if any path exists.\n " }, { "code": null, "e": 2164, "s": 2066, "text": "Expected Time Complexity: O(n*n*k) where k is max(matrix[i][j])\nExpected Space Complexity: O(1)\n " }, { "code": null, "e": 2214, "s": 2164, "text": "Constraints:\n1 <= n <= 50\n1 <= matrix[i][j] <= 20" }, { "code": null, "e": 2217, "s": 2214, "text": "+3" }, { "code": null, "e": 2235, "s": 2217, "text": "rainx6 months ago" }, { "code": null, "e": 2251, "s": 2237, "text": "EASY QUESTION" }, { "code": null, "e": 2475, "s": 2251, "text": "We first try the forward way i.e. y+jump and then we try x+jump since according to question we have to prioritize forward direction path. Just set that cell to 1 and if it doesn't make a path backtrack and make it 0 again. " }, { "code": null, "e": 2497, "s": 2477, "text": "CODE IMPLEMENTATION" }, { "code": null, "e": 2686, "s": 2499, "text": "bool isSafe(vector<vector<int>> &matrix, int x, int y){\n if(x>=matrix.size() || y>=matrix[0].size() || matrix[x][y]==0){\n return false;\n }\n return true;\n}" }, { "code": null, "e": 3290, "s": 2686, "text": "bool helper(vector<vector<int>> &matrix, vector<vector<int>> &res, int x, int y, int n){\n if(x==n-1 && y==n-1){\n res[x][y]=1;\n return true;\n }\n if(isSafe(matrix,x,y)==true){\n res[x][y]=1;\n for(int i=1;i<=matrix[x][y] && i<n;i++){\n if(helper(matrix,res,x,y+i,n)==true){\n return true;\n }\n if(helper(matrix,res,x+i,y,n)==true){\n return true;\n }\n }\n res[x][y]=0;\n return false;\n }\n return false;\n}" }, { "code": null, "e": 3548, "s": 3290, "text": "vector<vector<int>> ShortestDistance(vector<vector<int>> &matrix){\n\t int n=matrix.size();\n\t if(matrix[0][0]==0 && n!=1){\n\t return {{-1}};\n\t }\n\t vector<vector<int>> res(n,vector<int>(n,0));\n\t helper(matrix,res,0,0,n);\n\t return res;\n}" }, { "code": null, "e": 3571, "s": 3548, "text": "keep coding and upvote" }, { "code": null, "e": 3574, "s": 3571, "text": "-2" }, { "code": null, "e": 3599, "s": 3574, "text": "shivam1706207 months ago" }, { "code": null, "e": 3655, "s": 3607, "text": "WHATS WRONG WITH CODE ?? OR PROVIDE SOLUTION !!" }, { "code": null, "e": 5031, "s": 3661, "text": "bool issafe(vector<vector<int>>&matrix,int x,int y,int n) { if(x>=0 && x<n && y>=0 && y<n && matrix[x][y]!=0) { return true; } return false; } bool mazehelper(vector<vector<int>>&matrix,int x,int y,vector<vector<int>> ans ,int n,int arr[MAX][MAX]) { if(x==n-1 && y==n-1) { arr[x][y]=1; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { ans[i][j]=arr[i][j]; } } return true; } if(issafe(matrix,x,y,n)==true) { arr[x][y]=1; for(int i=1;i<=matrix[x][y] && i<n;i++) { if(mazehelper(matrix,x+i,y,ans,n,arr)==true) { return true; } if(mazehelper(matrix,x,y+i,ans,n,arr)==true) { return true; } } arr[x][y]=0; return false; } return false; }vector<vector<int>> ShortestDistance(vector<vector<int>>&matrix){ // Code here int n=matrix.size(); int arr[MAX][MAX]; vector<vector<int>> ans(n,vector<int>(n));/* for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { arr[i][j]=0; } }*/ memset(arr,0,n*n*sizeof(int));" }, { "code": null, "e": 5241, "s": 5031, "text": " bool res=mazehelper(matrix,0,0,ans,n,arr); if(res==true) { return ans; } else { vector<vector<int>> buffer(1,vector<int>(1,-1));// buffer[0][0]=-1; return buffer; } }" }, { "code": null, "e": 5244, "s": 5241, "text": "+1" }, { "code": null, "e": 5267, "s": 5244, "text": "Navin Ojha8 months ago" }, { "code": null, "e": 5278, "s": 5267, "text": "Navin Ojha" }, { "code": null, "e": 5301, "s": 5278, "text": "Very Tricky Question :" }, { "code": null, "e": 5389, "s": 5301, "text": "Destination will not always be set to 1 so make sure you set it to 1 and then traverse." }, { "code": null, "e": 5391, "s": 5389, "text": "0" }, { "code": null, "e": 5419, "s": 5391, "text": "Shivesh Bharti10 months ago" }, { "code": null, "e": 5434, "s": 5419, "text": "Shivesh Bharti" }, { "code": null, "e": 5549, "s": 5434, "text": "there is error in the matrix name in python driver code ,its written matirx instead of matrix please fix that soon" }, { "code": null, "e": 5695, "s": 5549, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5731, "s": 5695, "text": " Login to access your submissions. " }, { "code": null, "e": 5741, "s": 5731, "text": "\nProblem\n" }, { "code": null, "e": 5751, "s": 5741, "text": "\nContest\n" }, { "code": null, "e": 5814, "s": 5751, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5962, "s": 5814, "text": "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." }, { "code": null, "e": 6170, "s": 5962, "text": "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." }, { "code": null, "e": 6276, "s": 6170, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Repeat Rows of DataFrame N Times in R - GeeksforGeeks
14 Sep, 2021 In this article, we will discuss how to repeat rows of Dataframe for a given number of times using R programming language. A replication factor is declared to define the number of times the data frame rows are to be repeated. The do.call() method in R is used to perform an R function while taking as input various arguments. The rbind() method is taken as the first argument of this method to combine data frames together. The second argument is the replicate() method which is used to create multiple copies of the rows of the data frames equivalent to the number of times same as replication factor. Syntax: replicate(n, expr, simplify) Parameter : n – Number of replications to be performed. expr – Expression to be performed repeatedly. simplify – Type of output the results of expr are saved into. Example: Repeating rows n times R # creating a data framedata_frame <- data.frame(col1 = c(6:8), col2 = letters[1:3], col3 = c(1,4,NA)) print ("Original DataFrame") print (data_frame) # replication factorn <- 3 data_frame_mod <- do.call("rbind", replicate( n, data_frame, simplify = FALSE)) print ("Modified DataFrame") print(data_frame_mod) Output [1] "Original DataFrame" col1 col2 col3 1 6 a 1 2 7 b 4 3 8 c NA [1] "Modified DataFrame" col1 col2 col3 1 6 a 1 2 7 b 4 3 8 c NA 4 6 a 1 5 7 b 4 6 8 c NA 7 6 a 1 8 7 b 4 9 8 c NA The purr package in R is used to simplify the functioning and working with both functions as well as vectors. The package can be installed into the working space using the following command : install.packages("purrr") The seq_len() method in R is used to create a sequence taking as input an integer value and then generating a sequence of numbers beginning from 1 to the specified integer with steps equivalent to 1. Syntax: vec <- seq_len(number) The map_dfr() function of the purrr in R is used to create a data frame formed by row appending. It is used for row binding. Syntax: map_dfr(vec, ~data-frame) Example: Repeating rows n times R library("purrr") # creating a data framedata_frame <- data.frame(col1 = c(6:8), col2 = letters[1:3], col3 = c(1,4,NA)) print ("Original DataFrame")print (data_frame) # replication factorn <- 2data_frame_mod <- purrr::map_dfr(seq_len(n), ~data_frame) print ("Modified DataFrame")print(data_frame_mod) Output [1] "Original DataFrame" col1 col2 col3 1 6 a 1 2 7 b 4 3 8 c NA [1] "Modified DataFrame" col1 col2 col3 1 6 a 1 2 7 b 4 3 8 c NA 4 6 a 1 5 7 b 4 6 8 c NA The nrow() method in R is used to determine the number of rows of the data frame. Syntax: nrow(data-frame) The vector sequence is then generated using the seq_len() method described in the previous method. This is followed by the application of rep() method which is used to replicate numeric values a specified number of times. The first argument is the vector generated by seq_len() method and n is the replication factor. Syntax: rep(vec, n) Data frame indexing is used to append the generated rows to the original data frame rows and stored as the modified data frame. Example: Repeating rows n times R # creating a data framedata_frame <- data.frame(col1 = c(6:8), col2 = letters[1:3], col3 = c(1,4,NA)) print ("Original DataFrame")print (data_frame) # replication factorn <- 3data_frame_mod <- data_frame[rep(seq_len(nrow(data_frame)), n), ] print ("Modified DataFrame")print(data_frame_mod) Output [1] "Original DataFrame" col1 col2 col3 1 6 a 1 2 7 b 4 3 8 c NA [1] "Modified DataFrame" col1 col2 col3 1 6 a 1 2 7 b 4 3 8 c NA 1.1 6 a 1 2.1 7 b 4 3.1 8 c NA 1.2 6 a 1 2.2 7 b 4 3.2 8 c NA Picked R DataFrame-Programs R-DataFrame R Language R Programs 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 How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n14 Sep, 2021" }, { "code": null, "e": 24975, "s": 24851, "text": "In this article, we will discuss how to repeat rows of Dataframe for a given number of times using R programming language. " }, { "code": null, "e": 25456, "s": 24975, "text": "A replication factor is declared to define the number of times the data frame rows are to be repeated. The do.call() method in R is used to perform an R function while taking as input various arguments. The rbind() method is taken as the first argument of this method to combine data frames together. The second argument is the replicate() method which is used to create multiple copies of the rows of the data frames equivalent to the number of times same as replication factor. " }, { "code": null, "e": 25494, "s": 25456, "text": "Syntax: replicate(n, expr, simplify) " }, { "code": null, "e": 25507, "s": 25494, "text": "Parameter : " }, { "code": null, "e": 25551, "s": 25507, "text": "n – Number of replications to be performed." }, { "code": null, "e": 25597, "s": 25551, "text": "expr – Expression to be performed repeatedly." }, { "code": null, "e": 25659, "s": 25597, "text": "simplify – Type of output the results of expr are saved into." }, { "code": null, "e": 25691, "s": 25659, "text": "Example: Repeating rows n times" }, { "code": null, "e": 25693, "s": 25691, "text": "R" }, { "code": "# creating a data framedata_frame <- data.frame(col1 = c(6:8), col2 = letters[1:3], col3 = c(1,4,NA)) print (\"Original DataFrame\") print (data_frame) # replication factorn <- 3 data_frame_mod <- do.call(\"rbind\", replicate( n, data_frame, simplify = FALSE)) print (\"Modified DataFrame\") print(data_frame_mod)", "e": 26054, "s": 25693, "text": null }, { "code": null, "e": 26061, "s": 26054, "text": "Output" }, { "code": null, "e": 26345, "s": 26061, "text": "[1] \"Original DataFrame\"\ncol1 col2 col3\n1 6 a 1\n2 7 b 4\n3 8 c NA\n[1] \"Modified DataFrame\"\ncol1 col2 col3\n1 6 a 1\n2 7 b 4\n3 8 c NA\n4 6 a 1\n5 7 b 4\n6 8 c NA\n7 6 a 1\n8 7 b 4\n9 8 c NA" }, { "code": null, "e": 26538, "s": 26345, "text": "The purr package in R is used to simplify the functioning and working with both functions as well as vectors. The package can be installed into the working space using the following command : " }, { "code": null, "e": 26564, "s": 26538, "text": "install.packages(\"purrr\")" }, { "code": null, "e": 26765, "s": 26564, "text": "The seq_len() method in R is used to create a sequence taking as input an integer value and then generating a sequence of numbers beginning from 1 to the specified integer with steps equivalent to 1. " }, { "code": null, "e": 26773, "s": 26765, "text": "Syntax:" }, { "code": null, "e": 26796, "s": 26773, "text": "vec <- seq_len(number)" }, { "code": null, "e": 26922, "s": 26796, "text": "The map_dfr() function of the purrr in R is used to create a data frame formed by row appending. It is used for row binding. " }, { "code": null, "e": 26930, "s": 26922, "text": "Syntax:" }, { "code": null, "e": 26956, "s": 26930, "text": "map_dfr(vec, ~data-frame)" }, { "code": null, "e": 26988, "s": 26956, "text": "Example: Repeating rows n times" }, { "code": null, "e": 26990, "s": 26988, "text": "R" }, { "code": "library(\"purrr\") # creating a data framedata_frame <- data.frame(col1 = c(6:8), col2 = letters[1:3], col3 = c(1,4,NA)) print (\"Original DataFrame\")print (data_frame) # replication factorn <- 2data_frame_mod <- purrr::map_dfr(seq_len(n), ~data_frame) print (\"Modified DataFrame\")print(data_frame_mod)", "e": 27341, "s": 26990, "text": null }, { "code": null, "e": 27348, "s": 27341, "text": "Output" }, { "code": null, "e": 27581, "s": 27348, "text": "[1] \"Original DataFrame\"\ncol1 col2 col3\n1 6 a 1\n2 7 b 4\n3 8 c NA\n[1] \"Modified DataFrame\"\ncol1 col2 col3\n1 6 a 1\n2 7 b 4\n3 8 c NA\n4 6 a 1\n5 7 b 4\n6 8 c NA" }, { "code": null, "e": 27664, "s": 27581, "text": "The nrow() method in R is used to determine the number of rows of the data frame. " }, { "code": null, "e": 27672, "s": 27664, "text": "Syntax:" }, { "code": null, "e": 27689, "s": 27672, "text": "nrow(data-frame)" }, { "code": null, "e": 28008, "s": 27689, "text": "The vector sequence is then generated using the seq_len() method described in the previous method. This is followed by the application of rep() method which is used to replicate numeric values a specified number of times. The first argument is the vector generated by seq_len() method and n is the replication factor. " }, { "code": null, "e": 28016, "s": 28008, "text": "Syntax:" }, { "code": null, "e": 28028, "s": 28016, "text": "rep(vec, n)" }, { "code": null, "e": 28157, "s": 28028, "text": "Data frame indexing is used to append the generated rows to the original data frame rows and stored as the modified data frame. " }, { "code": null, "e": 28189, "s": 28157, "text": "Example: Repeating rows n times" }, { "code": null, "e": 28191, "s": 28189, "text": "R" }, { "code": "# creating a data framedata_frame <- data.frame(col1 = c(6:8), col2 = letters[1:3], col3 = c(1,4,NA)) print (\"Original DataFrame\")print (data_frame) # replication factorn <- 3data_frame_mod <- data_frame[rep(seq_len(nrow(data_frame)), n), ] print (\"Modified DataFrame\")print(data_frame_mod)", "e": 28531, "s": 28191, "text": null }, { "code": null, "e": 28538, "s": 28531, "text": "Output" }, { "code": null, "e": 28840, "s": 28538, "text": "[1] \"Original DataFrame\"\ncol1 col2 col3\n1 6 a 1\n2 7 b 4\n3 8 c NA\n[1] \"Modified DataFrame\"\ncol1 col2 col3\n1 6 a 1\n2 7 b 4\n3 8 c NA\n1.1 6 a 1\n2.1 7 b 4\n3.1 8 c NA\n1.2 6 a 1\n2.2 7 b 4\n3.2 8 c NA" }, { "code": null, "e": 28847, "s": 28840, "text": "Picked" }, { "code": null, "e": 28868, "s": 28847, "text": "R DataFrame-Programs" }, { "code": null, "e": 28880, "s": 28868, "text": "R-DataFrame" }, { "code": null, "e": 28891, "s": 28880, "text": "R Language" }, { "code": null, "e": 28902, "s": 28891, "text": "R Programs" }, { "code": null, "e": 29000, "s": 28902, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29009, "s": 29000, "text": "Comments" }, { "code": null, "e": 29022, "s": 29009, "text": "Old Comments" }, { "code": null, "e": 29074, "s": 29022, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29112, "s": 29074, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29147, "s": 29112, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29205, "s": 29147, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29254, "s": 29205, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29312, "s": 29254, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29361, "s": 29312, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29404, "s": 29361, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29454, "s": 29404, "text": "How to filter R dataframe by multiple conditions?" } ]
Framework7 - Card HTML Layout
The card HTML layout contains many classes, which are listed below − cards It is the card container. card-header It is the optional card header that is used to display card title. card-footer It is optional and used for specifying additional information or custom links. card-content It is the main container for content of the card and is required. card-content-inner It is the optional additional inner wrapper that is used for additional padding to content. Both the card-header and the card-footer has flexbox layout where items have center vertical alignment. If you want to order your items to top or to bottom of header/footer, then you can use valign attribute. The following example demonstrates the use of cards HTML layouts in Framework7 − <!DOCTYPE html> <html class="with-statusbar-overlay"> <head> <meta name = "viewport" content = "width = device-width, initial-scale = 1, maximum-scale = 1, minimum-scale = 1, user-scalable = no, minimal-ui" /> <meta name = "apple-mobile-web-app-capable" content = "yes" /> <meta name = "apple-mobile-web-app-status-bar-style" content = "black" /> <title>Card HTML Layout</title> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/css/framework7.ios.min.css" /> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/css/framework7.ios.colors.min.css" /> <link rel = "stylesheet" href = "custom.css" /> </head> <body> <style> .demo-card-header-pic .card-header { height:40vw; background-size:cover; background-position:center; } .facebook-card .card-header { display:block;padding:10px; } .facebook-card .facebook-avatar { float:left; } .facebook-card .facebook-name { margin-left:44px; font-size:14px; font-weight:500; } .facebook-card .facebook-date { margin-left:44px; font-size:13px; color:#8e8e93; } .facebook-card .card-footer { background:#fafafa; } .facebook-card .card-footer a { color:#81848b; font-weight:500; } .facebook-card .card-content img { display:block; } .facebook-card .card-content-inner { padding:15px 10px; } </style> <div class = "views"> <div class = "view view-main"> <div class = "pages"> <div data-page = "home" class = "page navbar-fixed"> <div class = "navbar"> <div class = "navbar-inner"> <div class = "left"> </div> <div class = "center">Card HTML Layout</div> <div class = "right"> </div> </div> </div> <div class = "page-content"> <div class = "content-block-title">Simple Cards</div> <div class = "card"> <div class = "card-content"> <div class = "card-content-inner">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div> </div> </div> <div class = "card"> <div class = "card-header">Card header</div> <div class = "card-content"> <div class = "card-content-inner">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div> </div> <div class = "card-footer">Card Footer</div> </div> <div class = "card"> <div class = "card-content"> <div class = "card-content-inner">Another card. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </div> </div> </div> <div class = "content-block-title">Styled Cards</div> <div class = "card demo-card-header-pic"> <div style = "background-image:url(/framework7/images/nature.jpg)" valign = "bottom" class = "card-header color-white no-border">Beautiful Mountains</div> <div class = "card-content"> <div class = "card-content-inner"> <p class = "color-gray">Posted on May 20, 2015</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> </div> </div> <div class = "card-footer"><a href = "#" class = "link">Like</a><a href = "#" class = "link">Comment</a></div> </div> <div class = "card facebook-card"> <div class = "card-header"> <div class = "facebook-avatar"><img src = "/framework7/images/cat.jpg" width = "34" height = "34"></div> <div class = "facebook-name">John Doe</div> <div class = "facebook-date">Monday at 2:15 PM</div> </div> <div class = "card-content"> <div class = "card-content-inner"> <p>What a nice view!!</p> <img src = "/framework7/images/blue_hills1.jpg" width = "100%"> <p class = "color-gray">Likes: 112 Comments: 43</p> </div> </div> <div class = "card-footer"><a href = "#" class = "link">Like</a><a href = "#" class = "link">Comment</a><a href = "#" class = "link">Share</a></div> </div> <div class = "content-block-title">Cards With List View</div> <div class = "card"> <div class = "card-content"> <div class = "list-block"> <ul> <li> <a href = "#" class = "item-link item-content"> <div class = "item-media"><i class = "icon icon-form-name"></i></div> <div class = "item-inner"> <div class = "item-title">Link 1</div> </div> </a> </li> <li> <a href = "#" class = "item-link item-content"> <div class = "item-media"><i class = "icon icon-form-name"></i></div> <div class = "item-inner"> <div class = "item-title">Link 2</div> </div> </a> </li> <li> <a href = "#" class = "item-link item-content"> <div class = "item-media"><i class = "icon icon-form-name"></i></div> <div class = "item-inner"> <div class = "item-title">Link 3</div> </div> </a> </li> <li> <a href = "#" class = "item-link item-content"> <div class = "item-media"><i class = "icon icon-form-name"></i></div> <div class = "item-inner"> <div class = "item-title">Link 4</div> </div> </a> </li> <li> <a href = "#" class = "item-link item-content"> <div class = "item-media"><i class = "icon icon-form-name"></i></div> <div class = "item-inner"> <div class = "item-title">Link 5</div> </div> </a> </li> </ul> </div> </div> </div> <div class = "card"> <div class = "card-header">Albums:</div> <div class = "card-content"> <div class = "list-block media-list"> <ul> <li class = "item-content"> <div class = "item-media"><img src = "/framework7/images/pic.jpg" width = "44"></div> <div class = "item-inner"> <div class = "item-title-row"> <div class = "item-title">Cast away</div> </div> <div class = "item-subtitle">James</div> </div> </li> <li class = "item-content"> <div class = "item-media"><img src = "/framework7/images/pic3.jpg" width = "44"></div> <div class = "item-inner"> <div class = "item-title-row"> <div class = "item-title">Don't Follow me</div> </div> <div class = "item-subtitle">Rema Taylor</div> </div> </li> <li class = "item-content"> <div class = "item-media"><img src = "/framework7/images/pic2.jpg" width = "44"></div> <div class = "item-inner"> <div class = "item-title-row"> <div class = "item-title">Billion words</div> </div> <div class = "item-subtitle">Kaveen sharma</div> </div> </li> </ul> </div> </div> <div class = "card-footer"> <span>May 1, 2016</span><span>45 comments</span></div> </div> </div> </div> </div> </div> </div> <script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/js/framework7.min.js"></script> <script>var myApp = new Framework7();</script> </body> </html> Let us carry out the following steps to see how the above given code works − Save the above given HTML code as cards_html_layout.html file in your server root folder. Save the above given HTML code as cards_html_layout.html file in your server root folder. Open this HTML file as http://localhost/cards_html_layout.html and the output is displayed as shown below. Open this HTML file as http://localhost/cards_html_layout.html and the output is displayed as shown below. The example defines the card layout, which contains unique related data, such as photo, text, link. The example defines the card layout, which contains unique related data, such as photo, text, link. Posted on May 20, 2015 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. What a nice view!! Likes: 112 Comments: 43 Link 1 Link 2 Link 3 Link 4 Link 5 Cast away James Don't Follow me Rema Taylor Billion words Kaveen sharma 7 Lectures 1 hours Anadi Sharma 22 Lectures 6 hours Malhar Lathkar 102 Lectures 8 hours Karthikeya T 19 Lectures 5 hours Trevoir Williams 20 Lectures 1 hours John Elder 13 Lectures 3 hours Darwish Print Add Notes Bookmark this page
[ { "code": null, "e": 2720, "s": 2651, "text": "The card HTML layout contains many classes, which are listed below −" }, { "code": null, "e": 2726, "s": 2720, "text": "cards" }, { "code": null, "e": 2752, "s": 2726, "text": "It is the card container." }, { "code": null, "e": 2764, "s": 2752, "text": "card-header" }, { "code": null, "e": 2831, "s": 2764, "text": "It is the optional card header that is used to display card title." }, { "code": null, "e": 2843, "s": 2831, "text": "card-footer" }, { "code": null, "e": 2922, "s": 2843, "text": "It is optional and used for specifying additional information or custom links." }, { "code": null, "e": 2935, "s": 2922, "text": "card-content" }, { "code": null, "e": 3001, "s": 2935, "text": "It is the main container for content of the card and is required." }, { "code": null, "e": 3020, "s": 3001, "text": "card-content-inner" }, { "code": null, "e": 3112, "s": 3020, "text": "It is the optional additional inner wrapper that is used for additional padding to content." }, { "code": null, "e": 3321, "s": 3112, "text": "Both the card-header and the card-footer has flexbox layout where items have center vertical alignment. If you want to order your items to top or to bottom of header/footer, then you can use valign attribute." }, { "code": null, "e": 3402, "s": 3321, "text": "The following example demonstrates the use of cards HTML layouts in Framework7 −" }, { "code": null, "e": 15338, "s": 3402, "text": "<!DOCTYPE html>\n<html class=\"with-statusbar-overlay\">\n <head>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, \n maximum-scale = 1, minimum-scale = 1, user-scalable = no, minimal-ui\" />\n <meta name = \"apple-mobile-web-app-capable\" content = \"yes\" />\n <meta name = \"apple-mobile-web-app-status-bar-style\" content = \"black\" />\n <title>Card HTML Layout</title>\n <link rel = \"stylesheet\" \n href = \"https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/css/framework7.ios.min.css\" />\n <link rel = \"stylesheet\" \n href = \"https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/css/framework7.ios.colors.min.css\" />\n <link rel = \"stylesheet\" \n href = \"custom.css\" />\n </head>\n\n <body>\n <style>\n .demo-card-header-pic .card-header {\n height:40vw;\n background-size:cover;\n background-position:center;\n }\n \n .facebook-card .card-header {\n display:block;padding:10px;\n }\n \n .facebook-card .facebook-avatar {\n float:left;\n }\n \n .facebook-card .facebook-name {\n margin-left:44px;\n font-size:14px;\n font-weight:500;\n }\n \n .facebook-card .facebook-date {\n margin-left:44px;\n font-size:13px;\n color:#8e8e93;\n }\n \n .facebook-card .card-footer {\n background:#fafafa;\n }\n \n .facebook-card .card-footer a {\n color:#81848b;\n font-weight:500;\n }\n \n .facebook-card .card-content img {\n display:block;\n }\n \n .facebook-card .card-content-inner {\n padding:15px 10px;\n }\n </style>\n \n <div class = \"views\">\n <div class = \"view view-main\">\n <div class = \"pages\">\n <div data-page = \"home\" class = \"page navbar-fixed\">\n \n <div class = \"navbar\">\n <div class = \"navbar-inner\">\n <div class = \"left\"> </div>\n <div class = \"center\">Card HTML Layout</div>\n <div class = \"right\"> </div>\n </div>\n </div>\n\n <div class = \"page-content\">\n <div class = \"content-block-title\">Simple Cards</div>\n \n <div class = \"card\">\n <div class = \"card-content\">\n <div class = \"card-content-inner\">Lorem ipsum dolor sit amet, \n consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et \n dolore magna aliqua.</div>\n </div>\n </div>\n \n <div class = \"card\">\n <div class = \"card-header\">Card header</div>\n <div class = \"card-content\">\n <div class = \"card-content-inner\">Lorem ipsum dolor sit amet, \n consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et \n dolore magna aliqua.</div>\n </div>\n <div class = \"card-footer\">Card Footer</div>\n </div>\n \n <div class = \"card\">\n <div class = \"card-content\">\n <div class = \"card-content-inner\">Another card. Lorem ipsum dolor sit \n amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore \n et dolore magna aliqua. </div>\n </div>\n </div>\n \n <div class = \"content-block-title\">Styled Cards</div>\n \n <div class = \"card demo-card-header-pic\">\n <div style = \"background-image:url(/framework7/images/nature.jpg)\" valign = \"bottom\" class = \"card-header color-white no-border\">Beautiful Mountains</div>\n \n <div class = \"card-content\">\n <div class = \"card-content-inner\">\n <p class = \"color-gray\">Posted on May 20, 2015</p>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n </div>\n </div>\n \n <div class = \"card-footer\"><a href = \"#\" class = \"link\">Like</a><a href = \"#\" class = \"link\">Comment</a></div>\n </div>\n \n <div class = \"card facebook-card\">\n <div class = \"card-header\">\n <div class = \"facebook-avatar\"><img src = \"/framework7/images/cat.jpg\" width = \"34\" height = \"34\"></div>\n <div class = \"facebook-name\">John Doe</div>\n <div class = \"facebook-date\">Monday at 2:15 PM</div>\n </div>\n \n <div class = \"card-content\">\n <div class = \"card-content-inner\">\n <p>What a nice view!!</p>\n <img src = \"/framework7/images/blue_hills1.jpg\" width = \"100%\">\n <p class = \"color-gray\">Likes: 112 Comments: 43</p>\n </div>\n </div>\n \n <div class = \"card-footer\"><a href = \"#\" class = \"link\">Like</a><a href = \"#\" class = \"link\">Comment</a><a href = \"#\" class = \"link\">Share</a></div>\n </div>\n \n <div class = \"content-block-title\">Cards With List View</div>\n \n <div class = \"card\">\n <div class = \"card-content\">\n <div class = \"list-block\">\n <ul>\n <li>\n <a href = \"#\" class = \"item-link item-content\">\n <div class = \"item-media\"><i class = \"icon icon-form-name\"></i></div>\n <div class = \"item-inner\">\n <div class = \"item-title\">Link 1</div>\n </div>\n </a>\n </li>\n \n <li>\n <a href = \"#\" class = \"item-link item-content\">\n <div class = \"item-media\"><i class = \"icon icon-form-name\"></i></div>\n <div class = \"item-inner\">\n <div class = \"item-title\">Link 2</div>\n </div>\n </a>\n </li>\n \n <li>\n <a href = \"#\" class = \"item-link item-content\">\n <div class = \"item-media\"><i class = \"icon icon-form-name\"></i></div>\n <div class = \"item-inner\">\n <div class = \"item-title\">Link 3</div>\n </div>\n </a>\n </li>\n \n <li>\n <a href = \"#\" class = \"item-link item-content\">\n <div class = \"item-media\"><i class = \"icon icon-form-name\"></i></div>\n <div class = \"item-inner\">\n <div class = \"item-title\">Link 4</div>\n </div>\n </a>\n </li>\n \n <li>\n <a href = \"#\" class = \"item-link item-content\">\n <div class = \"item-media\"><i class = \"icon icon-form-name\"></i></div>\n <div class = \"item-inner\">\n <div class = \"item-title\">Link 5</div>\n </div>\n </a>\n </li>\n </ul>\n </div>\n </div>\n </div>\n \n <div class = \"card\">\n <div class = \"card-header\">Albums:</div>\n <div class = \"card-content\">\n <div class = \"list-block media-list\">\n <ul>\n <li class = \"item-content\">\n <div class = \"item-media\"><img src = \"/framework7/images/pic.jpg\" width = \"44\"></div>\n <div class = \"item-inner\">\n <div class = \"item-title-row\">\n <div class = \"item-title\">Cast away</div>\n </div>\n <div class = \"item-subtitle\">James</div>\n </div>\n </li>\n \n <li class = \"item-content\">\n <div class = \"item-media\"><img src = \"/framework7/images/pic3.jpg\" width = \"44\"></div>\n <div class = \"item-inner\">\n <div class = \"item-title-row\">\n <div class = \"item-title\">Don't Follow me</div>\n </div>\n <div class = \"item-subtitle\">Rema Taylor</div>\n </div>\n </li>\n \n <li class = \"item-content\">\n <div class = \"item-media\"><img src = \"/framework7/images/pic2.jpg\" width = \"44\"></div>\n <div class = \"item-inner\">\n <div class = \"item-title-row\">\n <div class = \"item-title\">Billion words</div>\n </div>\n <div class = \"item-subtitle\">Kaveen sharma</div>\n </div>\n </li>\n </ul>\n </div>\n </div>\n \n <div class = \"card-footer\"> <span>May 1, 2016</span><span>45 comments</span></div>\n </div>\n \n </div>\n </div>\n </div>\n </div>\n </div>\n \n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/js/framework7.min.js\"></script>\n \n <script>var myApp = new Framework7();</script>\n </body>\n\n</html>" }, { "code": null, "e": 15415, "s": 15338, "text": "Let us carry out the following steps to see how the above given code works −" }, { "code": null, "e": 15505, "s": 15415, "text": "Save the above given HTML code as cards_html_layout.html file in your server root folder." }, { "code": null, "e": 15595, "s": 15505, "text": "Save the above given HTML code as cards_html_layout.html file in your server root folder." }, { "code": null, "e": 15702, "s": 15595, "text": "Open this HTML file as http://localhost/cards_html_layout.html and the output is displayed as shown below." }, { "code": null, "e": 15809, "s": 15702, "text": "Open this HTML file as http://localhost/cards_html_layout.html and the output is displayed as shown below." }, { "code": null, "e": 15909, "s": 15809, "text": "The example defines the card layout, which contains unique related data, such as photo, text, link." }, { "code": null, "e": 16009, "s": 15909, "text": "The example defines the card layout, which contains unique related data, such as photo, text, link." }, { "code": null, "e": 16032, "s": 16009, "text": "Posted on May 20, 2015" }, { "code": null, "e": 16156, "s": 16032, "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." }, { "code": null, "e": 16175, "s": 16156, "text": "What a nice view!!" }, { "code": null, "e": 16202, "s": 16175, "text": "Likes: 112 Comments: 43" }, { "code": null, "e": 16216, "s": 16202, "text": "\n\n\n\nLink 1\n\n\n" }, { "code": null, "e": 16230, "s": 16216, "text": "\n\n\n\nLink 2\n\n\n" }, { "code": null, "e": 16244, "s": 16230, "text": "\n\n\n\nLink 3\n\n\n" }, { "code": null, "e": 16258, "s": 16244, "text": "\n\n\n\nLink 4\n\n\n" }, { "code": null, "e": 16272, "s": 16258, "text": "\n\n\n\nLink 5\n\n\n" }, { "code": null, "e": 16295, "s": 16272, "text": "\n\n\n\nCast away\n\nJames\n\n" }, { "code": null, "e": 16330, "s": 16295, "text": "\n\n\n\nDon't Follow me\n\nRema Taylor\n\n" }, { "code": null, "e": 16365, "s": 16330, "text": "\n\n\n\nBillion words\n\nKaveen sharma\n\n" }, { "code": null, "e": 16397, "s": 16365, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 16411, "s": 16397, "text": " Anadi Sharma" }, { "code": null, "e": 16444, "s": 16411, "text": "\n 22 Lectures \n 6 hours \n" }, { "code": null, "e": 16460, "s": 16444, "text": " Malhar Lathkar" }, { "code": null, "e": 16494, "s": 16460, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 16508, "s": 16494, "text": " Karthikeya T" }, { "code": null, "e": 16541, "s": 16508, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 16559, "s": 16541, "text": " Trevoir Williams" }, { "code": null, "e": 16592, "s": 16559, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 16604, "s": 16592, "text": " John Elder" }, { "code": null, "e": 16637, "s": 16604, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 16646, "s": 16637, "text": " Darwish" }, { "code": null, "e": 16653, "s": 16646, "text": " Print" }, { "code": null, "e": 16664, "s": 16653, "text": " Add Notes" } ]
How to make an HTTP POST request on iOS App using Swift?
To make an http request in iOS we’ll make use of DataTask and sessions. We’ll create configuration, sessions, url, request, and dataTask objects. Let’s see the steps that we’ll go through. First of all we need to create a session object, which default configuration. First of all we need to create a session object, which default configuration. let configuration = URLSessionConfiguration.default let session = URLSession(configuration: configuration) Then we need to create an URL Request of The type we need, it can be get, post, delete or put. In this example we are seeing ”POST” type. Then we need to create an URL Request of The type we need, it can be get, post, delete or put. In this example we are seeing ”POST” type. let url = URL(string: URLString) //let url = NSURL(string: urlString as String) var request : URLRequest = URLRequest(url: url!) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") Once we have created the request object, we need to perfrom dataTask, with URL we just created above. This is how our complete dataTask method should look like now. Once we have created the request object, we need to perfrom dataTask, with URL we just created above. This is how our complete dataTask method should look like now. let dataTask = session.dataTask(with: url!) { data,response,error in guard let httpResponse = response as? HTTPURLResponse, let receivedData = data else { print("error: not a valid http response") return } switch (httpResponse.statusCode) { case 200: //success response. break case 400: break default: break } } dataTask.resume() Now we can embed this in a function and use in our code. Now we can embed this in a function and use in our code. func hitAPI(_for URLString:String) { let configuration = URLSessionConfiguration.default let session = URLSession(configuration: configuration) let url = URL(string: URLString) //let url = NSURL(string: urlString as String) var request : URLRequest = URLRequest(url: url!) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let dataTask = session.dataTask(with: url!) { data,response,error in // 1: Check HTTP Response for successful GET request guard let httpResponse = response as? HTTPURLResponse, let receivedData = data else { print("error: not a valid http response") return } switch (httpResponse.statusCode) { case 200: //success response. break case 400: break default: break } } dataTask.resume() } Note: You may need to allow Transport Security exceptions in your info.plist file to access some APIs. There is no output shown with this example as an API is required to post some data.
[ { "code": null, "e": 1251, "s": 1062, "text": "To make an http request in iOS we’ll make use of DataTask and sessions. We’ll create configuration, sessions, url, request, and dataTask objects. Let’s see the steps that we’ll go through." }, { "code": null, "e": 1329, "s": 1251, "text": "First of all we need to create a session object, which default configuration." }, { "code": null, "e": 1407, "s": 1329, "text": "First of all we need to create a session object, which default configuration." }, { "code": null, "e": 1514, "s": 1407, "text": "let configuration = URLSessionConfiguration.default\nlet session = URLSession(configuration: configuration)" }, { "code": null, "e": 1652, "s": 1514, "text": "Then we need to create an URL Request of The type we need, it can be get, post, delete or put. In this example we are seeing ”POST” type." }, { "code": null, "e": 1790, "s": 1652, "text": "Then we need to create an URL Request of The type we need, it can be get, post, delete or put. In this example we are seeing ”POST” type." }, { "code": null, "e": 2087, "s": 1790, "text": "let url = URL(string: URLString)\n//let url = NSURL(string: urlString as String)\nvar request : URLRequest = URLRequest(url: url!)\nrequest.httpMethod = \"POST\"\nrequest.addValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\nrequest.addValue(\"application/json\", forHTTPHeaderField: \"Accept\")" }, { "code": null, "e": 2252, "s": 2087, "text": "Once we have created the request object, we need to perfrom dataTask, with URL we just created above. This is how our complete dataTask method should look like now." }, { "code": null, "e": 2417, "s": 2252, "text": "Once we have created the request object, we need to perfrom dataTask, with URL we just created above. This is how our complete dataTask method should look like now." }, { "code": null, "e": 2819, "s": 2417, "text": "let dataTask = session.dataTask(with: url!) { data,response,error in\n guard let httpResponse = response as? HTTPURLResponse, let receivedData = data\n else {\n print(\"error: not a valid http response\")\n return\n }\n switch (httpResponse.statusCode) {\n case 200: //success response.\n break\n case 400:\n break\n default:\n break\n }\n}\ndataTask.resume()" }, { "code": null, "e": 2876, "s": 2819, "text": "Now we can embed this in a function and use in our code." }, { "code": null, "e": 2933, "s": 2876, "text": "Now we can embed this in a function and use in our code." }, { "code": null, "e": 3927, "s": 2933, "text": "func hitAPI(_for URLString:String) {\n let configuration = URLSessionConfiguration.default\n let session = URLSession(configuration: configuration)\n let url = URL(string: URLString)\n //let url = NSURL(string: urlString as String)\n var request : URLRequest = URLRequest(url: url!)\n request.httpMethod = \"POST\"\n request.addValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n request.addValue(\"application/json\", forHTTPHeaderField: \"Accept\")\n let dataTask = session.dataTask(with: url!) {\n data,response,error in\n // 1: Check HTTP Response for successful GET request\n guard let httpResponse = response as? HTTPURLResponse, let receivedData = data\n else {\n print(\"error: not a valid http response\")\n return\n }\n switch (httpResponse.statusCode) {\n case 200:\n //success response.\n break\n case 400:\n break\n default:\n break\n }\n }\n dataTask.resume()\n}" }, { "code": null, "e": 4030, "s": 3927, "text": "Note: You may need to allow Transport Security exceptions in your info.plist file to access some APIs." }, { "code": null, "e": 4114, "s": 4030, "text": "There is no output shown with this example as an API is required to post some data." } ]
Split array into two subarrays such that difference of their maximum is minimum - GeeksforGeeks
07 May, 2021 Given an array arr[] consisting of integers, the task is to split the given array into two sub-arrays such that the difference between their maximum elements is minimum. Example: Input: arr[] = {7, 9, 5, 10} Output: 1 Explanation: The subarrays are {5, 10} and {7, 9} with the difference between their maximums = 10 – 9 = 1.Input: arr[] = {6, 6, 6} Output: 0 Approach: We can observe that we need to split the array into two subarrays such that: If the maximum element occurs more than once in the array, it needs to be present in both the subarrays at least once. Otherwise, the largest and the second-largest elements should be present in different subarrays. This ensures that the difference between the maximum elements of the two subarrays is maximized. Hence, we need to sort the array, and then the difference between the largest 2 elements, i.e. arr[n – 1] and arr[n – 2], is the required answer.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to split a given// array such that the difference// between their maximums is minimized. #include <bits/stdc++.h>using namespace std; int findMinDif(int arr[], int N){ // Sort the array sort(arr, arr + N); // Return the difference // between two highest // elements return (arr[N - 1] - arr[N - 2]);} // Driver Programint main(){ int arr[] = { 7, 9, 5, 10 }; int N = sizeof(arr) / sizeof(arr[0]); cout << findMinDif(arr, N); return 0;} // Java Program to split a given array// such that the difference between// their maximums is minimized.import java.util.*; class GFG{ static int findMinDif(int arr[], int N){ // Sort the array Arrays.sort(arr); // Return the difference between // two highest elements return (arr[N - 1] - arr[N - 2]);} // Driver codepublic static void main(String[] args){ int arr[] = { 7, 9, 5, 10 }; int N = arr.length; System.out.println(findMinDif(arr, N));}} // This code is contributed by offbeat # Python3 Program to split a given# array such that the difference# between their maximums is minimized.def findMinDif(arr, N): # Sort the array arr.sort() # Return the difference # between two highest # elements return (arr[N - 1] - arr[N - 2]) # Driver Programarr = [ 7, 9, 5, 10 ]N = len(arr)print(findMinDif(arr, N)) # This code is contributed by yatinagg // C# Program to split a given array// such that the difference between// their maximums is minimized.using System;class GFG{ static int findMinDif(int []arr, int N){ // Sort the array Array.Sort(arr); // Return the difference between // two highest elements return (arr[N - 1] - arr[N - 2]);} // Driver codepublic static void Main(){ int []arr = { 7, 9, 5, 10 }; int N = arr.Length; Console.Write(findMinDif(arr, N));}} // This code is contributed by Code_Mech <script>// javascript Program to split a given array// such that the difference between// their maximums is minimized. function findMinDif(arr , N) { // Sort the array arr.sort((a,b)=>a-b); // Return the difference between // two highest elements return (arr[N - 1] - arr[N - 2]); } // Driver code var arr = [ 7, 9, 5, 10 ]; var N = arr.length; document.write(findMinDif(arr, N)); // This code contributed by gauravrajput1</script> 1 Time complexity: O(N*log(N)), N is the number of elements of the array. yatinagg offbeat Code_Mech GauravRajput1 subarray Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java
[ { "code": null, "e": 24975, "s": 24947, "text": "\n07 May, 2021" }, { "code": null, "e": 25147, "s": 24975, "text": "Given an array arr[] consisting of integers, the task is to split the given array into two sub-arrays such that the difference between their maximum elements is minimum. " }, { "code": null, "e": 25157, "s": 25147, "text": "Example: " }, { "code": null, "e": 25339, "s": 25157, "text": "Input: arr[] = {7, 9, 5, 10} Output: 1 Explanation: The subarrays are {5, 10} and {7, 9} with the difference between their maximums = 10 – 9 = 1.Input: arr[] = {6, 6, 6} Output: 0 " }, { "code": null, "e": 25428, "s": 25339, "text": "Approach: We can observe that we need to split the array into two subarrays such that: " }, { "code": null, "e": 25547, "s": 25428, "text": "If the maximum element occurs more than once in the array, it needs to be present in both the subarrays at least once." }, { "code": null, "e": 25644, "s": 25547, "text": "Otherwise, the largest and the second-largest elements should be present in different subarrays." }, { "code": null, "e": 25938, "s": 25644, "text": "This ensures that the difference between the maximum elements of the two subarrays is maximized. Hence, we need to sort the array, and then the difference between the largest 2 elements, i.e. arr[n – 1] and arr[n – 2], is the required answer.Below is the implementation of the above approach: " }, { "code": null, "e": 25942, "s": 25938, "text": "C++" }, { "code": null, "e": 25947, "s": 25942, "text": "Java" }, { "code": null, "e": 25955, "s": 25947, "text": "Python3" }, { "code": null, "e": 25958, "s": 25955, "text": "C#" }, { "code": null, "e": 25969, "s": 25958, "text": "Javascript" }, { "code": "// C++ Program to split a given// array such that the difference// between their maximums is minimized. #include <bits/stdc++.h>using namespace std; int findMinDif(int arr[], int N){ // Sort the array sort(arr, arr + N); // Return the difference // between two highest // elements return (arr[N - 1] - arr[N - 2]);} // Driver Programint main(){ int arr[] = { 7, 9, 5, 10 }; int N = sizeof(arr) / sizeof(arr[0]); cout << findMinDif(arr, N); return 0;}", "e": 26453, "s": 25969, "text": null }, { "code": "// Java Program to split a given array// such that the difference between// their maximums is minimized.import java.util.*; class GFG{ static int findMinDif(int arr[], int N){ // Sort the array Arrays.sort(arr); // Return the difference between // two highest elements return (arr[N - 1] - arr[N - 2]);} // Driver codepublic static void main(String[] args){ int arr[] = { 7, 9, 5, 10 }; int N = arr.length; System.out.println(findMinDif(arr, N));}} // This code is contributed by offbeat", "e": 26976, "s": 26453, "text": null }, { "code": "# Python3 Program to split a given# array such that the difference# between their maximums is minimized.def findMinDif(arr, N): # Sort the array arr.sort() # Return the difference # between two highest # elements return (arr[N - 1] - arr[N - 2]) # Driver Programarr = [ 7, 9, 5, 10 ]N = len(arr)print(findMinDif(arr, N)) # This code is contributed by yatinagg", "e": 27360, "s": 26976, "text": null }, { "code": "// C# Program to split a given array// such that the difference between// their maximums is minimized.using System;class GFG{ static int findMinDif(int []arr, int N){ // Sort the array Array.Sort(arr); // Return the difference between // two highest elements return (arr[N - 1] - arr[N - 2]);} // Driver codepublic static void Main(){ int []arr = { 7, 9, 5, 10 }; int N = arr.Length; Console.Write(findMinDif(arr, N));}} // This code is contributed by Code_Mech", "e": 27857, "s": 27360, "text": null }, { "code": "<script>// javascript Program to split a given array// such that the difference between// their maximums is minimized. function findMinDif(arr , N) { // Sort the array arr.sort((a,b)=>a-b); // Return the difference between // two highest elements return (arr[N - 1] - arr[N - 2]); } // Driver code var arr = [ 7, 9, 5, 10 ]; var N = arr.length; document.write(findMinDif(arr, N)); // This code contributed by gauravrajput1</script>", "e": 28364, "s": 27857, "text": null }, { "code": null, "e": 28366, "s": 28364, "text": "1" }, { "code": null, "e": 28441, "s": 28368, "text": "Time complexity: O(N*log(N)), N is the number of elements of the array. " }, { "code": null, "e": 28450, "s": 28441, "text": "yatinagg" }, { "code": null, "e": 28458, "s": 28450, "text": "offbeat" }, { "code": null, "e": 28468, "s": 28458, "text": "Code_Mech" }, { "code": null, "e": 28482, "s": 28468, "text": "GauravRajput1" }, { "code": null, "e": 28491, "s": 28482, "text": "subarray" }, { "code": null, "e": 28498, "s": 28491, "text": "Arrays" }, { "code": null, "e": 28506, "s": 28498, "text": "Sorting" }, { "code": null, "e": 28513, "s": 28506, "text": "Arrays" }, { "code": null, "e": 28521, "s": 28513, "text": "Sorting" }, { "code": null, "e": 28619, "s": 28521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28628, "s": 28619, "text": "Comments" }, { "code": null, "e": 28641, "s": 28628, "text": "Old Comments" }, { "code": null, "e": 28689, "s": 28641, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 28733, "s": 28689, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 28756, "s": 28733, "text": "Introduction to Arrays" } ]
6 simple tips for prettier and customised plots in Seaborn (Python) | by Zolzaya Luvsandorj | Towards Data Science
In this post, we will look at simple ways to customise your plots to make them aesthetically more pleasing. I hope these simple tricks will help you get better-looking plots and save you time from adjusting individual plots. The scripts in this post are tested in Python 3.8.3 in Jupyter Notebook. Let’s use Seaborn’s built-in dataset on penguins as our sample data: # Import packagesimport matplotlib.pyplot as pltimport seaborn as sns# Import datadf = sns.load_dataset('penguins').rename(columns={'sex': 'gender'})df We will build a standard scatter plot with the default chart settings to use it as our baseline: # Plotsns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender') We will see the journey of how this plot alters with each tip. You will see that the first two tips are for individual plots whereas the remaining four tips are for changing the default settings for all charts. Did you notice the text output right above the chart in the previous plot? A simple way to suppress this text output is to use ; at the end of your plot. # Plotsns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender'); By only adding ; at the end of our code, we get a cleaner output. Plots can often benefit from resizing. If we wanted to resize, this is how we would do it: # Plotplt.figure(figsize=(9, 5))sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender'); When we resized, the legend moved to the upper left corner. Let’s move the legend outside the chart so that it doesn’t accidentally cover data points: # Plotplt.figure(figsize=(9, 5))sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender')plt.legend(loc='upper right', bbox_to_anchor=(1.2, 1)); If you are wondering how to know what number combinations to use for figsize() or bbox_to_anchor(), you will need to trial and error which numbers work best for the plot. This function helps to change the overall style of the plots if we don’t like the default style. This includes things like the aesthetics of the axis colours and background. Let’s change the style to whitegrid and see how the plot appearance changes: # Change default stylesns.set_style('whitegrid')# Plotplt.figure(figsize=(9, 5))sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender')plt.legend(loc='upper right', bbox_to_anchor=(1.2, 1)); Here are some more other options to try out: 'darkgrid', 'dark' and 'ticks' to find the one you fancy more. The label sizes look quite small in the previous plot. With sns.set_context(), we could change the context parameters if we don’t like the default settings. I use this function mainly to control the default font size for labels in the plots. By changing the default, we can save time from not having to tweak the font size for different elements (e.g. axis label, title, legend) of individual plots. Let’s change the context to 'talk' and look at the plot again: # Change default contextsns.set_context('talk')# Plotplt.figure(figsize=(9, 5))sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender')plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1)); It’s more easily legible, isn’t it? Another option to try out is: 'poster' which will increase the default size even more. If you ever want to customise the default colour palette to your preferred colour combinations, this function comes in handy. We can use colourmaps from Matplotlib. Here are the lists of Matplotlib colourmaps to choose from. Let’s change the palette to 'rainbow' and look at the plot again: # Change default palettesns.set_palette('rainbow')# Plotplt.figure(figsize=(9, 5))sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender')plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1)); If you can’t find a Matplotlib colourmap that you like, you can hand pick colours to create your own unique colour palette. 🎨 One way to create your own palette is to pass a list of colour names to the function like in the example below. Here is the list of colour names. # Change default palettesns.set_palette(['green', 'purple', 'red'])# Plotplt.figure(figsize=(9, 5))sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender')plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1)); If the colour names don’t quite capture what you are after, you can build your own palette using hexadecimal colours to access a wider range of options (over 16 million colours!). Here’s my favourite resource to find a custom colour palette in hexadecimal. Let’s see an example: # Change default palettesns.set_palette(['#62C370', '#FFD166', '#EF476F'])# Plotplt.figure(figsize=(9, 5))sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender')plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1)); From the previous three tips, I hope you will find your favourite combination (in some cases, it could be leaving the default as is). If we were to update chart default settings, it’s better to do it just after importing the visualisation packages. This means we will have a snippet like this at the beginning of our scripts: # Import packagesimport matplotlib.pyplot as pltimport seaborn as sns# Change defaultssns.set_style('whitegrid')sns.set_context('talk')sns.set_palette('rainbow') Updating multiple defaults like above can be done more succinctly with sns.set(). Here’s the succinct version of the same code: # Import packagesimport matplotlib.pyplot as pltimport seaborn as sns# Change defaultssns.set(style='whitegrid', context='talk', palette='rainbow') Voila❕ These were the six tips. These are the comparison of the plots before and after tweaking: Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me. I hope you learned a few easy ways to tweak your plots without having to spend too much time. I hope this post has given you starter ideas to begin personalising your plots and make them more visually pleasing. If you are interested, here are links to some of my posts: ◼️ Exploratory text analysis in Python◼️️ 5 tips for pandas users◼️️ 5 tips for data aggregation in pandas◼️️ Writing 5 common SQL queries in pandas◼️️ Writing advanced SQL queries in pandas Bye for now 🏃💨
[ { "code": null, "e": 396, "s": 171, "text": "In this post, we will look at simple ways to customise your plots to make them aesthetically more pleasing. I hope these simple tricks will help you get better-looking plots and save you time from adjusting individual plots." }, { "code": null, "e": 469, "s": 396, "text": "The scripts in this post are tested in Python 3.8.3 in Jupyter Notebook." }, { "code": null, "e": 538, "s": 469, "text": "Let’s use Seaborn’s built-in dataset on penguins as our sample data:" }, { "code": null, "e": 690, "s": 538, "text": "# Import packagesimport matplotlib.pyplot as pltimport seaborn as sns# Import datadf = sns.load_dataset('penguins').rename(columns={'sex': 'gender'})df" }, { "code": null, "e": 787, "s": 690, "text": "We will build a standard scatter plot with the default chart settings to use it as our baseline:" }, { "code": null, "e": 912, "s": 787, "text": "# Plotsns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender')" }, { "code": null, "e": 975, "s": 912, "text": "We will see the journey of how this plot alters with each tip." }, { "code": null, "e": 1123, "s": 975, "text": "You will see that the first two tips are for individual plots whereas the remaining four tips are for changing the default settings for all charts." }, { "code": null, "e": 1277, "s": 1123, "text": "Did you notice the text output right above the chart in the previous plot? A simple way to suppress this text output is to use ; at the end of your plot." }, { "code": null, "e": 1403, "s": 1277, "text": "# Plotsns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender');" }, { "code": null, "e": 1469, "s": 1403, "text": "By only adding ; at the end of our code, we get a cleaner output." }, { "code": null, "e": 1560, "s": 1469, "text": "Plots can often benefit from resizing. If we wanted to resize, this is how we would do it:" }, { "code": null, "e": 1712, "s": 1560, "text": "# Plotplt.figure(figsize=(9, 5))sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender');" }, { "code": null, "e": 1863, "s": 1712, "text": "When we resized, the legend moved to the upper left corner. Let’s move the legend outside the chart so that it doesn’t accidentally cover data points:" }, { "code": null, "e": 2069, "s": 1863, "text": "# Plotplt.figure(figsize=(9, 5))sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender')plt.legend(loc='upper right', bbox_to_anchor=(1.2, 1));" }, { "code": null, "e": 2240, "s": 2069, "text": "If you are wondering how to know what number combinations to use for figsize() or bbox_to_anchor(), you will need to trial and error which numbers work best for the plot." }, { "code": null, "e": 2491, "s": 2240, "text": "This function helps to change the overall style of the plots if we don’t like the default style. This includes things like the aesthetics of the axis colours and background. Let’s change the style to whitegrid and see how the plot appearance changes:" }, { "code": null, "e": 2745, "s": 2491, "text": "# Change default stylesns.set_style('whitegrid')# Plotplt.figure(figsize=(9, 5))sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender')plt.legend(loc='upper right', bbox_to_anchor=(1.2, 1));" }, { "code": null, "e": 2853, "s": 2745, "text": "Here are some more other options to try out: 'darkgrid', 'dark' and 'ticks' to find the one you fancy more." }, { "code": null, "e": 3316, "s": 2853, "text": "The label sizes look quite small in the previous plot. With sns.set_context(), we could change the context parameters if we don’t like the default settings. I use this function mainly to control the default font size for labels in the plots. By changing the default, we can save time from not having to tweak the font size for different elements (e.g. axis label, title, legend) of individual plots. Let’s change the context to 'talk' and look at the plot again:" }, { "code": null, "e": 3569, "s": 3316, "text": "# Change default contextsns.set_context('talk')# Plotplt.figure(figsize=(9, 5))sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender')plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1));" }, { "code": null, "e": 3692, "s": 3569, "text": "It’s more easily legible, isn’t it? Another option to try out is: 'poster' which will increase the default size even more." }, { "code": null, "e": 3983, "s": 3692, "text": "If you ever want to customise the default colour palette to your preferred colour combinations, this function comes in handy. We can use colourmaps from Matplotlib. Here are the lists of Matplotlib colourmaps to choose from. Let’s change the palette to 'rainbow' and look at the plot again:" }, { "code": null, "e": 4239, "s": 3983, "text": "# Change default palettesns.set_palette('rainbow')# Plotplt.figure(figsize=(9, 5))sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender')plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1));" }, { "code": null, "e": 4511, "s": 4239, "text": "If you can’t find a Matplotlib colourmap that you like, you can hand pick colours to create your own unique colour palette. 🎨 One way to create your own palette is to pass a list of colour names to the function like in the example below. Here is the list of colour names." }, { "code": null, "e": 4784, "s": 4511, "text": "# Change default palettesns.set_palette(['green', 'purple', 'red'])# Plotplt.figure(figsize=(9, 5))sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender')plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1));" }, { "code": null, "e": 5063, "s": 4784, "text": "If the colour names don’t quite capture what you are after, you can build your own palette using hexadecimal colours to access a wider range of options (over 16 million colours!). Here’s my favourite resource to find a custom colour palette in hexadecimal. Let’s see an example:" }, { "code": null, "e": 5343, "s": 5063, "text": "# Change default palettesns.set_palette(['#62C370', '#FFD166', '#EF476F'])# Plotplt.figure(figsize=(9, 5))sns.scatterplot(data=df, x='body_mass_g', y='bill_length_mm', alpha=0.7, hue='species', size='gender')plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1));" }, { "code": null, "e": 5669, "s": 5343, "text": "From the previous three tips, I hope you will find your favourite combination (in some cases, it could be leaving the default as is). If we were to update chart default settings, it’s better to do it just after importing the visualisation packages. This means we will have a snippet like this at the beginning of our scripts:" }, { "code": null, "e": 5831, "s": 5669, "text": "# Import packagesimport matplotlib.pyplot as pltimport seaborn as sns# Change defaultssns.set_style('whitegrid')sns.set_context('talk')sns.set_palette('rainbow')" }, { "code": null, "e": 5959, "s": 5831, "text": "Updating multiple defaults like above can be done more succinctly with sns.set(). Here’s the succinct version of the same code:" }, { "code": null, "e": 6107, "s": 5959, "text": "# Import packagesimport matplotlib.pyplot as pltimport seaborn as sns# Change defaultssns.set(style='whitegrid', context='talk', palette='rainbow')" }, { "code": null, "e": 6204, "s": 6107, "text": "Voila❕ These were the six tips. These are the comparison of the plots before and after tweaking:" }, { "code": null, "e": 6428, "s": 6204, "text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me." }, { "code": null, "e": 6698, "s": 6428, "text": "I hope you learned a few easy ways to tweak your plots without having to spend too much time. I hope this post has given you starter ideas to begin personalising your plots and make them more visually pleasing. If you are interested, here are links to some of my posts:" }, { "code": null, "e": 6889, "s": 6698, "text": "◼️ Exploratory text analysis in Python◼️️ 5 tips for pandas users◼️️ 5 tips for data aggregation in pandas◼️️ Writing 5 common SQL queries in pandas◼️️ Writing advanced SQL queries in pandas" } ]
Difference between require() and require_once() in PHP - GeeksforGeeks
21 Oct, 2021 PHP require() Function: The require() function in PHP is mostly used to include the code/data of one PHP file to another file. During this process, if there are any kind of errors then this require() function will display a warning along with a fatal error which will immediately stop the execution of the script. In order to use this require() function, we will first need to create two PHP files. Include one PHP file into another one by using the include() function. The two PHP files are combined into one HTML file. This require() function will not see whether the code is included in the specified file before, rather it will include the code as many times the require() function is used. Example: HTML <html> <body> <h1>Welcome to geeks for geeks!</h1> <p>Myself, Gaurav Gandal</p> <p>Thank you</p> <?php require 'requiregfg.php'; ?></body> </html> requiregfg.php <?php echo "<p>visit Again-" . date("Y") . " geeks for geeks.com</p>"; ?> Output: PHP require_once() Function: The require_once() function in PHP is used to include one PHP file into another PHP file. It provides us with a feature that if a code from a PHP file is already included in a specified file then it will not include that code again if we use the require_once() function. It means that this function will add a file into another only once. In case this function does not locate a specified file then it will produce a fatal error and will immediately stop the execution. Example: PHP <?php require_once('demo.php'); require_once('demo.php');?> The following code is used in the above PHP code. demo.php <?php echo "Hello from Geeks for Geeks";?> Output: Difference between require() and require_once(): PHP-function PHP-Questions Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to fetch data from localserver database and display on HTML table using PHP ? How to pass form variables from one page to other page in PHP ? Create a drop-down list that options fetched from a MySQL database in PHP How to create admin login page using PHP? Different ways for passing data to view in Laravel Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24581, "s": 24553, "text": "\n21 Oct, 2021" }, { "code": null, "e": 24896, "s": 24581, "text": "PHP require() Function: The require() function in PHP is mostly used to include the code/data of one PHP file to another file. During this process, if there are any kind of errors then this require() function will display a warning along with a fatal error which will immediately stop the execution of the script. " }, { "code": null, "e": 25278, "s": 24896, "text": "In order to use this require() function, we will first need to create two PHP files. Include one PHP file into another one by using the include() function. The two PHP files are combined into one HTML file. This require() function will not see whether the code is included in the specified file before, rather it will include the code as many times the require() function is used." }, { "code": null, "e": 25287, "s": 25278, "text": "Example:" }, { "code": null, "e": 25292, "s": 25287, "text": "HTML" }, { "code": "<html> <body> <h1>Welcome to geeks for geeks!</h1> <p>Myself, Gaurav Gandal</p> <p>Thank you</p> <?php require 'requiregfg.php'; ?></body> </html>", "e": 25457, "s": 25292, "text": null }, { "code": null, "e": 25474, "s": 25459, "text": "requiregfg.php" }, { "code": "<?php echo \"<p>visit Again-\" . date(\"Y\") . \" geeks for geeks.com</p>\"; ?>", "e": 25562, "s": 25474, "text": null }, { "code": null, "e": 25570, "s": 25562, "text": "Output:" }, { "code": null, "e": 25939, "s": 25570, "text": "PHP require_once() Function: The require_once() function in PHP is used to include one PHP file into another PHP file. It provides us with a feature that if a code from a PHP file is already included in a specified file then it will not include that code again if we use the require_once() function. It means that this function will add a file into another only once. " }, { "code": null, "e": 26070, "s": 25939, "text": "In case this function does not locate a specified file then it will produce a fatal error and will immediately stop the execution." }, { "code": null, "e": 26079, "s": 26070, "text": "Example:" }, { "code": null, "e": 26083, "s": 26079, "text": "PHP" }, { "code": "<?php require_once('demo.php'); require_once('demo.php');?>", "e": 26149, "s": 26083, "text": null }, { "code": null, "e": 26199, "s": 26149, "text": "The following code is used in the above PHP code." }, { "code": null, "e": 26208, "s": 26199, "text": "demo.php" }, { "code": "<?php echo \"Hello from Geeks for Geeks\";?>", "e": 26254, "s": 26208, "text": null }, { "code": null, "e": 26262, "s": 26254, "text": "Output:" }, { "code": null, "e": 26311, "s": 26262, "text": "Difference between require() and require_once():" }, { "code": null, "e": 26324, "s": 26311, "text": "PHP-function" }, { "code": null, "e": 26338, "s": 26324, "text": "PHP-Questions" }, { "code": null, "e": 26345, "s": 26338, "text": "Picked" }, { "code": null, "e": 26349, "s": 26345, "text": "PHP" }, { "code": null, "e": 26366, "s": 26349, "text": "Web Technologies" }, { "code": null, "e": 26370, "s": 26366, "text": "PHP" }, { "code": null, "e": 26468, "s": 26370, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26477, "s": 26468, "text": "Comments" }, { "code": null, "e": 26490, "s": 26477, "text": "Old Comments" }, { "code": null, "e": 26572, "s": 26490, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 26636, "s": 26572, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 26710, "s": 26636, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 26752, "s": 26710, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 26803, "s": 26752, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 26859, "s": 26803, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26892, "s": 26859, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26954, "s": 26892, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26997, "s": 26954, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Deal with Imbalanced Multiclass Datasets in Python | by Angelica Lo Duca | Towards Data Science
Imbalanced datasets may often produce poor performance when running a Machine Learning model, although, in some cases the evaluation metrics produce good results. This can be due to the fact that the model is good at predicting the majority class, but it has poor performance while predicting the minority class. Since the evaluation metrics calculate the average value between the majority and minority classes, the final performance looks ok. By majority class I mean the most represented class in the dataset, while by minority class I mean the less represented class in the dataset. In other words, for the majority class there are more samples than for the minority class. In this case, the dataset is imbalanced. In most cases balancing improves the model performance, although this is not always true. In this tutorial I deal with multiclass datasets. A multiclass dataset is a dataset where the number of output classes is greater than two. I propose two strategies to balance a multiclass dataset: pipeline undersampling and oversampling play with class weights. Firstly, I load the dataset as a pandas dataframe. I exploit the Glass Dataset and their names. This dataset describes the chemical properties of glass. More details can be found at this link. import pandas as pddf = pd.read_csv('glass.csv')df.head() The dataset is composed of 214 samples and 7 classes. I build two variables, X and y containing the input features and the output classes, respectively. In order to do so, I calculate the input features and I store them into a variable called features. features = []for feature in df.columns: if feature != 'target': features.append(feature)X = df[features]y = df['target'] split the dataset into two parts: training and test sets by exploiting the train_test_split() function, provided by the sklearn library. I set the test set size to 0.2 (i.e. 20% of the whole dataset). from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=100) Now I calculate the number of samples for each target class in the training set. I exploit the value_counts() function. I note that the dataset is imbalanced. Balancing is applied only to the training set. import matplotlib.pyplot as pltcount = y_train.value_counts()count.plot.bar()plt.ylabel('Number of records')plt.xlabel('Target Class')plt.show() Before balancing the training set, I calculate the performance of the model with imbalanced data. I exploit a KNeighborsClassifier for my tests. I also import other useful functions from the scikitplot library, to plot the ROC and precision recall curves. In detail, firstly I build the model, then I fit with the training set and finally I calculate the perfomance of the model through the predict_proba() function applied to the test set. from sklearn.neighbors import KNeighborsClassifierfrom scikitplot.metrics import plot_rocfrom scikitplot.metrics import plot_precision_recallmodel = DecisionTreeClassifier()model.fit(X_train, y_train)y_score = model.predict_proba(X_test)y_pred = model.predict(X_test)# Plot metrics plot_roc(y_test, y_score)plt.show() plot_precision_recall(y_test, y_score)plt.show() The first strategy involves the creation of a pipeline, which undersamples the majority classes and oversamples the minority classes. The point here is to define a threshold which splits majority and minority classes, as well as the number of desired samples for each class. In this specific example we set the threshold equal to the number of desired samples for each class. One possible solution could be to set the threshold to the median value of the number of samples in the classes. Thus I can set the threshold to 19 and consider a majority class a class with a number of samples greater than the threshold. Similarly, a minority class is a class with a number of samples less than the threshold. I calculate the median and I convert it to integer. import numpy as npn_samples = count.median().astype(np.int64) Now I can undersample the most represented classes. Firstly, I suppress warnings. import warningswarnings.filterwarnings('ignore') Then, I define a utility function, which receives as input the dataset, the threshold (n_samples) and the involved classes (majority or minority). This function returns a dict which contains the number of desired samples for each class belonging to the involved classes. def sampling_strategy(X,y,n_samples, t='majority'): target_classes = '' if t == 'majority': target_classes = y.value_counts() > n_samples elif t == 'minority': target_classes = y.value_counts() < n_samples tc = target_classes[target_classes == True].index #target_classes_all = y.value_counts().index sampling_strategy = {} for target in tc: sampling_strategy[target] = n_samples return sampling_strategy Now I perform undersampling of the majority classes. I exploit the imblearn library. from imblearn.under_sampling import ClusterCentroidsunder_sampler = ClusterCentroids(sampling_strategy=sampling_strategy(X_train,y_train,n_samples,t='majority'))X_under, y_under = under_sampler.fit_resample(X_train, y_train) I note that the number of records in the majority classes have been set to n_samples. Then I oversample the less represented classes. I exploit the SMOTE oversampling strategy. from imblearn.over_sampling import SMOTEover_sampler = SMOTE(sampling_strategy=sampling_strategy(X_under, y_under,n_samples, t='minority'),k_neighbors=2)X_bal, y_bal = over_sampler.fit_resample(X_under, y_under) Eventually I have a balanced dataset. I train the model on the new balanced dataset and I note that the ROC curve improves, while the precision recall curve seems to decrease. However, looking at the class 3, in the original model the precision and recall were lower than in the balanced model. This means that the model now is able to predict better the minority classes. model = KNeighborsClassifier()model.fit(X_bal, y_bal)y_score = model.predict_proba(X_test)y_pred = model.predict(X_test)# Plot metrics plot_roc(y_test, y_score)plt.show() plot_precision_recall(y_test, y_score)plt.show() An alternative to balancing is to specify class weights in the original dataset while building the model. This permits the algorithm to give more importance to minority classes. Class weights can be calculated through the class_weight() function of the sklearn.utils library. from sklearn.utils import class_weightclasses = np.unique(y_train)cw = class_weight.compute_class_weight('balanced', classes, y_train)weights = dict(zip(classes,cw)) Now I can provide the class weights as input to a classifier, such as a DecisionTreeClassifier, and calculate the performance of the model. I do not use the KNeighborsClassifier as in the previous part of the tutorial, since it does not support class weights. from sklearn.tree import DecisionTreeClassifiermodel = DecisionTreeClassifier(class_weight=weights)model.fit(X_train, y_train)y_score = model.predict_proba(X_test)y_pred = model.predict(X_test)# Plot metrics plot_roc(y_test, y_score)plt.show() plot_precision_recall(y_test, y_score)plt.show() In this tutorial, I have illustrated how to perform balancing of a multiclass dataset. Two possible strategies can be adopted: undersampling followed by oversampling, or define class weights. If you are interested to data preprocessing, you can find other articles in my home page. If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and and Github. Thanks for reading! You can download the full code from my Github repository.
[ { "code": null, "e": 617, "s": 172, "text": "Imbalanced datasets may often produce poor performance when running a Machine Learning model, although, in some cases the evaluation metrics produce good results. This can be due to the fact that the model is good at predicting the majority class, but it has poor performance while predicting the minority class. Since the evaluation metrics calculate the average value between the majority and minority classes, the final performance looks ok." }, { "code": null, "e": 891, "s": 617, "text": "By majority class I mean the most represented class in the dataset, while by minority class I mean the less represented class in the dataset. In other words, for the majority class there are more samples than for the minority class. In this case, the dataset is imbalanced." }, { "code": null, "e": 981, "s": 891, "text": "In most cases balancing improves the model performance, although this is not always true." }, { "code": null, "e": 1179, "s": 981, "text": "In this tutorial I deal with multiclass datasets. A multiclass dataset is a dataset where the number of output classes is greater than two. I propose two strategies to balance a multiclass dataset:" }, { "code": null, "e": 1219, "s": 1179, "text": "pipeline undersampling and oversampling" }, { "code": null, "e": 1244, "s": 1219, "text": "play with class weights." }, { "code": null, "e": 1437, "s": 1244, "text": "Firstly, I load the dataset as a pandas dataframe. I exploit the Glass Dataset and their names. This dataset describes the chemical properties of glass. More details can be found at this link." }, { "code": null, "e": 1495, "s": 1437, "text": "import pandas as pddf = pd.read_csv('glass.csv')df.head()" }, { "code": null, "e": 1549, "s": 1495, "text": "The dataset is composed of 214 samples and 7 classes." }, { "code": null, "e": 1748, "s": 1549, "text": "I build two variables, X and y containing the input features and the output classes, respectively. In order to do so, I calculate the input features and I store them into a variable called features." }, { "code": null, "e": 1879, "s": 1748, "text": "features = []for feature in df.columns: if feature != 'target': features.append(feature)X = df[features]y = df['target']" }, { "code": null, "e": 2080, "s": 1879, "text": "split the dataset into two parts: training and test sets by exploiting the train_test_split() function, provided by the sklearn library. I set the test set size to 0.2 (i.e. 20% of the whole dataset)." }, { "code": null, "e": 2223, "s": 2080, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=100)" }, { "code": null, "e": 2382, "s": 2223, "text": "Now I calculate the number of samples for each target class in the training set. I exploit the value_counts() function. I note that the dataset is imbalanced." }, { "code": null, "e": 2429, "s": 2382, "text": "Balancing is applied only to the training set." }, { "code": null, "e": 2574, "s": 2429, "text": "import matplotlib.pyplot as pltcount = y_train.value_counts()count.plot.bar()plt.ylabel('Number of records')plt.xlabel('Target Class')plt.show()" }, { "code": null, "e": 3015, "s": 2574, "text": "Before balancing the training set, I calculate the performance of the model with imbalanced data. I exploit a KNeighborsClassifier for my tests. I also import other useful functions from the scikitplot library, to plot the ROC and precision recall curves. In detail, firstly I build the model, then I fit with the training set and finally I calculate the perfomance of the model through the predict_proba() function applied to the test set." }, { "code": null, "e": 3385, "s": 3015, "text": "from sklearn.neighbors import KNeighborsClassifierfrom scikitplot.metrics import plot_rocfrom scikitplot.metrics import plot_precision_recallmodel = DecisionTreeClassifier()model.fit(X_train, y_train)y_score = model.predict_proba(X_test)y_pred = model.predict(X_test)# Plot metrics plot_roc(y_test, y_score)plt.show() plot_precision_recall(y_test, y_score)plt.show()" }, { "code": null, "e": 3761, "s": 3385, "text": "The first strategy involves the creation of a pipeline, which undersamples the majority classes and oversamples the minority classes. The point here is to define a threshold which splits majority and minority classes, as well as the number of desired samples for each class. In this specific example we set the threshold equal to the number of desired samples for each class." }, { "code": null, "e": 4089, "s": 3761, "text": "One possible solution could be to set the threshold to the median value of the number of samples in the classes. Thus I can set the threshold to 19 and consider a majority class a class with a number of samples greater than the threshold. Similarly, a minority class is a class with a number of samples less than the threshold." }, { "code": null, "e": 4141, "s": 4089, "text": "I calculate the median and I convert it to integer." }, { "code": null, "e": 4203, "s": 4141, "text": "import numpy as npn_samples = count.median().astype(np.int64)" }, { "code": null, "e": 4285, "s": 4203, "text": "Now I can undersample the most represented classes. Firstly, I suppress warnings." }, { "code": null, "e": 4334, "s": 4285, "text": "import warningswarnings.filterwarnings('ignore')" }, { "code": null, "e": 4605, "s": 4334, "text": "Then, I define a utility function, which receives as input the dataset, the threshold (n_samples) and the involved classes (majority or minority). This function returns a dict which contains the number of desired samples for each class belonging to the involved classes." }, { "code": null, "e": 5055, "s": 4605, "text": "def sampling_strategy(X,y,n_samples, t='majority'): target_classes = '' if t == 'majority': target_classes = y.value_counts() > n_samples elif t == 'minority': target_classes = y.value_counts() < n_samples tc = target_classes[target_classes == True].index #target_classes_all = y.value_counts().index sampling_strategy = {} for target in tc: sampling_strategy[target] = n_samples return sampling_strategy" }, { "code": null, "e": 5140, "s": 5055, "text": "Now I perform undersampling of the majority classes. I exploit the imblearn library." }, { "code": null, "e": 5365, "s": 5140, "text": "from imblearn.under_sampling import ClusterCentroidsunder_sampler = ClusterCentroids(sampling_strategy=sampling_strategy(X_train,y_train,n_samples,t='majority'))X_under, y_under = under_sampler.fit_resample(X_train, y_train)" }, { "code": null, "e": 5451, "s": 5365, "text": "I note that the number of records in the majority classes have been set to n_samples." }, { "code": null, "e": 5542, "s": 5451, "text": "Then I oversample the less represented classes. I exploit the SMOTE oversampling strategy." }, { "code": null, "e": 5754, "s": 5542, "text": "from imblearn.over_sampling import SMOTEover_sampler = SMOTE(sampling_strategy=sampling_strategy(X_under, y_under,n_samples, t='minority'),k_neighbors=2)X_bal, y_bal = over_sampler.fit_resample(X_under, y_under)" }, { "code": null, "e": 5792, "s": 5754, "text": "Eventually I have a balanced dataset." }, { "code": null, "e": 6127, "s": 5792, "text": "I train the model on the new balanced dataset and I note that the ROC curve improves, while the precision recall curve seems to decrease. However, looking at the class 3, in the original model the precision and recall were lower than in the balanced model. This means that the model now is able to predict better the minority classes." }, { "code": null, "e": 6350, "s": 6127, "text": "model = KNeighborsClassifier()model.fit(X_bal, y_bal)y_score = model.predict_proba(X_test)y_pred = model.predict(X_test)# Plot metrics plot_roc(y_test, y_score)plt.show() plot_precision_recall(y_test, y_score)plt.show()" }, { "code": null, "e": 6626, "s": 6350, "text": "An alternative to balancing is to specify class weights in the original dataset while building the model. This permits the algorithm to give more importance to minority classes. Class weights can be calculated through the class_weight() function of the sklearn.utils library." }, { "code": null, "e": 6792, "s": 6626, "text": "from sklearn.utils import class_weightclasses = np.unique(y_train)cw = class_weight.compute_class_weight('balanced', classes, y_train)weights = dict(zip(classes,cw))" }, { "code": null, "e": 7052, "s": 6792, "text": "Now I can provide the class weights as input to a classifier, such as a DecisionTreeClassifier, and calculate the performance of the model. I do not use the KNeighborsClassifier as in the previous part of the tutorial, since it does not support class weights." }, { "code": null, "e": 7348, "s": 7052, "text": "from sklearn.tree import DecisionTreeClassifiermodel = DecisionTreeClassifier(class_weight=weights)model.fit(X_train, y_train)y_score = model.predict_proba(X_test)y_pred = model.predict(X_test)# Plot metrics plot_roc(y_test, y_score)plt.show() plot_precision_recall(y_test, y_score)plt.show()" }, { "code": null, "e": 7540, "s": 7348, "text": "In this tutorial, I have illustrated how to perform balancing of a multiclass dataset. Two possible strategies can be adopted: undersampling followed by oversampling, or define class weights." }, { "code": null, "e": 7630, "s": 7540, "text": "If you are interested to data preprocessing, you can find other articles in my home page." }, { "code": null, "e": 7749, "s": 7630, "text": "If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and and Github." } ]
How to Migrate Your Oracle Database to PostgreSQL | by Shafiqa Iqbal | Towards Data Science
Using this walkthrough, you can learn how to migrate Oracle database to RDS PostgreSQL using AWS Data Migration Service and AWS Schema Conversion Tool (AWS SCT). In this post we will cover the following: Migrate Schema using AWS SCT Drop foreign keys and secondary indexes on the target database, and disable triggers. Perform full load and change data capture (CDC) using AWS DMS AWS DMS takes a minimalist approach and creates only those objects required to efficiently migrate the data. In other words, AWS DMS creates tables, primary keys, and in some cases unique indexes, but doesn’t create any other objects that are not required to efficiently migrate the data from the source. For example, it doesn’t create secondary indexes, nonprimary key constraints, or data defaults. So, to generate a complete target schema, use AWS Schema Conversion Tool (SCT). After setting up AWS SCT: Step 1: Start a new project and connect the source (oracle) and target (RDS PostgrSQL) Step 2: Right click on your schema which you want to migrate and choose convert schema Step 3: Select Assessment Report View from View to check the report. Go through hints to fix any schema conversion issues. Step 4: To fix issues, modify objects on your source database, modify the script generated by SCT manually and then apply them to the target database. Step 5: After you’re satisfied with your schema conversion, browse through your source and target data types and validate if your datatypes and objects are converted properly. During the full load phase, the tables are loaded out of order. Thus, we have some foreign key constraint violations if we keep constraints enabled on the target. Also, during the full load, secondary indexes should be disabled because they can slow down the table replication. They do so because the indexes need to be maintained as the records are loaded. Execute the following script to generate SQL for disabling foreign key constraints. --Use the below SQL to generate the scripts to drop foreign keysselect 'alter table '||con.conrelid::regclass||' drop constraint '||con.conname||';' as dropfrom pg_constraint conjoin pg_namespace ns on con.connamespace = ns.oidwhere ns.nspname = 'Schema_Name'and con.contype = 'f'; Save the output and execute it on your target PostgreSQL database. Execute the following script to generate SQL for disabling foreign key constraints. --Use the below SQL to generate the scripts to disable triggersselect 'alter table '||trigger_schema||'.'||event_object_table||' disable trigger '||trigger_name||';' as disablefrom information_schema.triggerswhere trigger_schema = 'hr'; Save the output and execute it on your target PostgreSQL database. In order to replicate your data using DMS with CDC, you need to first prepare your Oracle database: Setup logminer in Oracle database and configure the destination for Redo log files. Enable ArchiveLog Mode. Set up the supplemental logging that DMS needs to capture changes from the Oracle source database. Make sure the oracle login that you are using in your source endpoint has the necessary permissions. We’ll go through each point and prepare our source database for data replication. As sysdba, install the logminer package (if not installed by default installed) from the following path: @ORACLE_HOME/rdbms/admin/dbmslm.sql you can simply check if it’s already available using: desc dbms_logmnr To build the logminer dictionary, open the database and put the database in quiesce state. Then the dictionary can be created using the following statement: ALTER DATABASE OPEN;ALTER DATABASE QUIESCE RESTRICTED;EXEC DBMS_LOGSTDBY.BUILD; After building the LogMiner dictionary, find the latest archive log. This file should be the starting point for recovery. The following SQL query can be used to find the latest archived log: select name, to_char(completion_time,'yyyy/mm/dd hh24:mi') completion_timefrom v$archived_logorder by completion_time; And the output will be similar to NAME COMPLETION_TIME ------------------------------------ ---------------- /oracle/appsdb/arch/appsdb_1_248.dbf 2003/09/30 14:55 /oracle/appsdb/arch/appsdb_1_564.dbf 2003/10/03 09:54 /oracle/appsdb/arch/appsdb_1_568.dbf 2003/10/03 12:08 Run the command following to set logs to ARCHIVELOG modeALTER database ARCHIVELOG; While enabling archive mode in the database, if you get below error, then you need to do the following resolution. SQL> alter database archivelog;alter database archivelog*ERROR at line 1:ORA-01126: database must be mounted in this instance and not open in any instance follow this link to resolve your error. dbaclass.com Enable supplemental logging for the database by running the command following. ALTER DATABASE ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS; This option specifies that when a row is updated, all columns of that row (except for LOBs, LONGS, and ADTs) are placed in the redo log file. To use an Oracle database as a source in AWS DMS, grant the privileges following to the Oracle user specified in the Oracle endpoint connection settings. SELECT ANY TRANSACTIONSELECT on V_$ARCHIVED_LOGSELECT on V_$LOGSELECT on V_$LOGFILESELECT on V_$DATABASESELECT on V_$THREADSELECT on V_$PARAMETERSELECT on V_$NLS_PARAMETERSSELECT on V_$TIMEZONE_NAMESSELECT on V_$TRANSACTIONSELECT on ALL_INDEXESSELECT on ALL_OBJECTSSELECT on DBA_OBJECTS – Required if the Oracle version is earlier than 11.2.0.3. To access logminer redo logs, grant the following privileges to oracle user. CREATE SESSIONEXECUTE on DBMS_LOGMNRSELECT on V_$LOGMNR_LOGSSELECT on V_$LOGMNR_CONTENTSGRANT LOGMINING – Required only if the Oracle version is 12c or later. Step 1: First, create your replication instance. A replication instance runs the DMS task. Step 2: Create your source and target endpoints. Make sure that you select the Refresh schemas option after a successful connection test and Run test before you finish creating each endpoint. Step 3: Create your task. For Migration type, choose Migrate existing data and replicate ongoing changes. Because we are using AWS SCT to pre-create the schema, select Do nothing or Truncate for Target table preparation mode. Select Stop After Applying Cached Changes for the option Stop task after the full load completes. We want the task to stop temporarily after the full load completes and the cached changes are applied. Cached changes are changes that have occurred and accumulated while the full table load process was run. This is the step just before CDC is applied. Under Table’s Mappings section, add a new selection rule and select your desired schema that you want to migrate. Add New Transformation Rule and transform the schema name to lower case for target PostgreSQL. Do the same with table and column names by adding two more transformation rules. Start your task and full load will begin. While your task is running, you can check under table’s statistics to monitor its progress After your full load is finishes and cache changes have been applied, you need to reapply the triggers and foreign key constraints that you disabled before full load. Execute the following script to generate SQL for enabling foreign key constraints --Use the below SQL to generate the script to create foreign keysselect 'alter table '||con.conrelid::regclass||' add constraint '||con.conname||' '||pg_get_constraintdef(con.oid)||';' as createfrom pg_constraint conjoin pg_namespace ns on con.connamespace = ns.oidwhere ns.nspname = 'schema_name'and con.contype = 'f'; Execute the following script to generate SQL for enabling triggers --Use the below SQL to generate the scripts enable triggersselect 'alter table '||trigger_schema||'.'||event_object_table||' enable trigger '||trigger_name||';' as enablefrom information_schema.triggerswhere trigger_schema = 'schema_name'; Run the generated SQL on target PostgreSQL. Now that we have the foreign keys and secondary indexes back, we can enable the DMS task. Simply go to the DMS console and choose Tasks. Select the task in the list and choose Start/Resume. Select the Start option and choose Start task. Once it’s started, you can see the status of your task as “ongoing replication”. You can test the replication by updating some records in source oracle and checking under table’s statistics tab and running queries in your target PostgreSQL Database. In this tutorial, we migrated Oracle database to PostgreSQL database using AWS Data migration service with full load and CDC. We migrated the schema using Schema Conversion Tool (SCT) and replicated data using DMS. For upcoming stories, you should follow my profile Shafiqa Iqbal. That’s it, guys! Have fun, keep learning & always coding!
[ { "code": null, "e": 375, "s": 171, "text": "Using this walkthrough, you can learn how to migrate Oracle database to RDS PostgreSQL using AWS Data Migration Service and AWS Schema Conversion Tool (AWS SCT). In this post we will cover the following:" }, { "code": null, "e": 404, "s": 375, "text": "Migrate Schema using AWS SCT" }, { "code": null, "e": 490, "s": 404, "text": "Drop foreign keys and secondary indexes on the target database, and disable triggers." }, { "code": null, "e": 552, "s": 490, "text": "Perform full load and change data capture (CDC) using AWS DMS" }, { "code": null, "e": 1059, "s": 552, "text": "AWS DMS takes a minimalist approach and creates only those objects required to efficiently migrate the data. In other words, AWS DMS creates tables, primary keys, and in some cases unique indexes, but doesn’t create any other objects that are not required to efficiently migrate the data from the source. For example, it doesn’t create secondary indexes, nonprimary key constraints, or data defaults. So, to generate a complete target schema, use AWS Schema Conversion Tool (SCT). After setting up AWS SCT:" }, { "code": null, "e": 1146, "s": 1059, "text": "Step 1: Start a new project and connect the source (oracle) and target (RDS PostgrSQL)" }, { "code": null, "e": 1233, "s": 1146, "text": "Step 2: Right click on your schema which you want to migrate and choose convert schema" }, { "code": null, "e": 1356, "s": 1233, "text": "Step 3: Select Assessment Report View from View to check the report. Go through hints to fix any schema conversion issues." }, { "code": null, "e": 1507, "s": 1356, "text": "Step 4: To fix issues, modify objects on your source database, modify the script generated by SCT manually and then apply them to the target database." }, { "code": null, "e": 1683, "s": 1507, "text": "Step 5: After you’re satisfied with your schema conversion, browse through your source and target data types and validate if your datatypes and objects are converted properly." }, { "code": null, "e": 2041, "s": 1683, "text": "During the full load phase, the tables are loaded out of order. Thus, we have some foreign key constraint violations if we keep constraints enabled on the target. Also, during the full load, secondary indexes should be disabled because they can slow down the table replication. They do so because the indexes need to be maintained as the records are loaded." }, { "code": null, "e": 2125, "s": 2041, "text": "Execute the following script to generate SQL for disabling foreign key constraints." }, { "code": null, "e": 2407, "s": 2125, "text": "--Use the below SQL to generate the scripts to drop foreign keysselect 'alter table '||con.conrelid::regclass||' drop constraint '||con.conname||';' as dropfrom pg_constraint conjoin pg_namespace ns on con.connamespace = ns.oidwhere ns.nspname = 'Schema_Name'and con.contype = 'f';" }, { "code": null, "e": 2474, "s": 2407, "text": "Save the output and execute it on your target PostgreSQL database." }, { "code": null, "e": 2558, "s": 2474, "text": "Execute the following script to generate SQL for disabling foreign key constraints." }, { "code": null, "e": 2795, "s": 2558, "text": "--Use the below SQL to generate the scripts to disable triggersselect 'alter table '||trigger_schema||'.'||event_object_table||' disable trigger '||trigger_name||';' as disablefrom information_schema.triggerswhere trigger_schema = 'hr';" }, { "code": null, "e": 2862, "s": 2795, "text": "Save the output and execute it on your target PostgreSQL database." }, { "code": null, "e": 2962, "s": 2862, "text": "In order to replicate your data using DMS with CDC, you need to first prepare your Oracle database:" }, { "code": null, "e": 3046, "s": 2962, "text": "Setup logminer in Oracle database and configure the destination for Redo log files." }, { "code": null, "e": 3070, "s": 3046, "text": "Enable ArchiveLog Mode." }, { "code": null, "e": 3169, "s": 3070, "text": "Set up the supplemental logging that DMS needs to capture changes from the Oracle source database." }, { "code": null, "e": 3270, "s": 3169, "text": "Make sure the oracle login that you are using in your source endpoint has the necessary permissions." }, { "code": null, "e": 3352, "s": 3270, "text": "We’ll go through each point and prepare our source database for data replication." }, { "code": null, "e": 3457, "s": 3352, "text": "As sysdba, install the logminer package (if not installed by default installed) from the following path:" }, { "code": null, "e": 3493, "s": 3457, "text": "@ORACLE_HOME/rdbms/admin/dbmslm.sql" }, { "code": null, "e": 3547, "s": 3493, "text": "you can simply check if it’s already available using:" }, { "code": null, "e": 3564, "s": 3547, "text": "desc dbms_logmnr" }, { "code": null, "e": 3721, "s": 3564, "text": "To build the logminer dictionary, open the database and put the database in quiesce state. Then the dictionary can be created using the following statement:" }, { "code": null, "e": 3801, "s": 3721, "text": "ALTER DATABASE OPEN;ALTER DATABASE QUIESCE RESTRICTED;EXEC DBMS_LOGSTDBY.BUILD;" }, { "code": null, "e": 3992, "s": 3801, "text": "After building the LogMiner dictionary, find the latest archive log. This file should be the starting point for recovery. The following SQL query can be used to find the latest archived log:" }, { "code": null, "e": 4119, "s": 3992, "text": "select name, to_char(completion_time,'yyyy/mm/dd hh24:mi') completion_timefrom v$archived_logorder by completion_time;" }, { "code": null, "e": 4153, "s": 4119, "text": "And the output will be similar to" }, { "code": null, "e": 4443, "s": 4153, "text": " NAME COMPLETION_TIME ------------------------------------ ---------------- /oracle/appsdb/arch/appsdb_1_248.dbf 2003/09/30 14:55 /oracle/appsdb/arch/appsdb_1_564.dbf 2003/10/03 09:54 /oracle/appsdb/arch/appsdb_1_568.dbf 2003/10/03 12:08" }, { "code": null, "e": 4526, "s": 4443, "text": "Run the command following to set logs to ARCHIVELOG modeALTER database ARCHIVELOG;" }, { "code": null, "e": 4641, "s": 4526, "text": "While enabling archive mode in the database, if you get below error, then you need to do the following resolution." }, { "code": null, "e": 4796, "s": 4641, "text": "SQL> alter database archivelog;alter database archivelog*ERROR at line 1:ORA-01126: database must be mounted in this instance and not open in any instance" }, { "code": null, "e": 4836, "s": 4796, "text": "follow this link to resolve your error." }, { "code": null, "e": 4849, "s": 4836, "text": "dbaclass.com" }, { "code": null, "e": 4928, "s": 4849, "text": "Enable supplemental logging for the database by running the command following." }, { "code": null, "e": 4984, "s": 4928, "text": "ALTER DATABASE ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS;" }, { "code": null, "e": 5126, "s": 4984, "text": "This option specifies that when a row is updated, all columns of that row (except for LOBs, LONGS, and ADTs) are placed in the redo log file." }, { "code": null, "e": 5280, "s": 5126, "text": "To use an Oracle database as a source in AWS DMS, grant the privileges following to the Oracle user specified in the Oracle endpoint connection settings." }, { "code": null, "e": 5626, "s": 5280, "text": "SELECT ANY TRANSACTIONSELECT on V_$ARCHIVED_LOGSELECT on V_$LOGSELECT on V_$LOGFILESELECT on V_$DATABASESELECT on V_$THREADSELECT on V_$PARAMETERSELECT on V_$NLS_PARAMETERSSELECT on V_$TIMEZONE_NAMESSELECT on V_$TRANSACTIONSELECT on ALL_INDEXESSELECT on ALL_OBJECTSSELECT on DBA_OBJECTS – Required if the Oracle version is earlier than 11.2.0.3." }, { "code": null, "e": 5703, "s": 5626, "text": "To access logminer redo logs, grant the following privileges to oracle user." }, { "code": null, "e": 5862, "s": 5703, "text": "CREATE SESSIONEXECUTE on DBMS_LOGMNRSELECT on V_$LOGMNR_LOGSSELECT on V_$LOGMNR_CONTENTSGRANT LOGMINING – Required only if the Oracle version is 12c or later." }, { "code": null, "e": 5953, "s": 5862, "text": "Step 1: First, create your replication instance. A replication instance runs the DMS task." }, { "code": null, "e": 6145, "s": 5953, "text": "Step 2: Create your source and target endpoints. Make sure that you select the Refresh schemas option after a successful connection test and Run test before you finish creating each endpoint." }, { "code": null, "e": 6171, "s": 6145, "text": "Step 3: Create your task." }, { "code": null, "e": 6251, "s": 6171, "text": "For Migration type, choose Migrate existing data and replicate ongoing changes." }, { "code": null, "e": 6371, "s": 6251, "text": "Because we are using AWS SCT to pre-create the schema, select Do nothing or Truncate for Target table preparation mode." }, { "code": null, "e": 6722, "s": 6371, "text": "Select Stop After Applying Cached Changes for the option Stop task after the full load completes. We want the task to stop temporarily after the full load completes and the cached changes are applied. Cached changes are changes that have occurred and accumulated while the full table load process was run. This is the step just before CDC is applied." }, { "code": null, "e": 6931, "s": 6722, "text": "Under Table’s Mappings section, add a new selection rule and select your desired schema that you want to migrate. Add New Transformation Rule and transform the schema name to lower case for target PostgreSQL." }, { "code": null, "e": 7012, "s": 6931, "text": "Do the same with table and column names by adding two more transformation rules." }, { "code": null, "e": 7054, "s": 7012, "text": "Start your task and full load will begin." }, { "code": null, "e": 7145, "s": 7054, "text": "While your task is running, you can check under table’s statistics to monitor its progress" }, { "code": null, "e": 7312, "s": 7145, "text": "After your full load is finishes and cache changes have been applied, you need to reapply the triggers and foreign key constraints that you disabled before full load." }, { "code": null, "e": 7394, "s": 7312, "text": "Execute the following script to generate SQL for enabling foreign key constraints" }, { "code": null, "e": 7714, "s": 7394, "text": "--Use the below SQL to generate the script to create foreign keysselect 'alter table '||con.conrelid::regclass||' add constraint '||con.conname||' '||pg_get_constraintdef(con.oid)||';' as createfrom pg_constraint conjoin pg_namespace ns on con.connamespace = ns.oidwhere ns.nspname = 'schema_name'and con.contype = 'f';" }, { "code": null, "e": 7781, "s": 7714, "text": "Execute the following script to generate SQL for enabling triggers" }, { "code": null, "e": 8021, "s": 7781, "text": "--Use the below SQL to generate the scripts enable triggersselect 'alter table '||trigger_schema||'.'||event_object_table||' enable trigger '||trigger_name||';' as enablefrom information_schema.triggerswhere trigger_schema = 'schema_name';" }, { "code": null, "e": 8065, "s": 8021, "text": "Run the generated SQL on target PostgreSQL." }, { "code": null, "e": 8302, "s": 8065, "text": "Now that we have the foreign keys and secondary indexes back, we can enable the DMS task. Simply go to the DMS console and choose Tasks. Select the task in the list and choose Start/Resume. Select the Start option and choose Start task." }, { "code": null, "e": 8552, "s": 8302, "text": "Once it’s started, you can see the status of your task as “ongoing replication”. You can test the replication by updating some records in source oracle and checking under table’s statistics tab and running queries in your target PostgreSQL Database." }, { "code": null, "e": 8767, "s": 8552, "text": "In this tutorial, we migrated Oracle database to PostgreSQL database using AWS Data migration service with full load and CDC. We migrated the schema using Schema Conversion Tool (SCT) and replicated data using DMS." }, { "code": null, "e": 8833, "s": 8767, "text": "For upcoming stories, you should follow my profile Shafiqa Iqbal." } ]
FileChannel Class tryLock() Method in Java with Examples
13 Apr, 2021 In the case of a multi-threaded program, where multiple threads are in execution concurrently, we require locks to be acquired and released to maintain synchronization among the processes. FileChannel Class of java also provides a method known as trylock() which is used to acquire a lock on the File specified. This method is used to acquire a lock on any region of the file, specified in the parameters of the method. A lock may be a more flexible and complicated thread synchronization mechanism than the standard synchronized block. A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, like the read lock of a ReadWriteLock. Here the output is the object of FileLock class which mentions the lock applied, if no lock is applied (maybe due to the reason that some other processes are holding or writing the file) then this method will return null. The Position variable specifies the mark of the file from where the lock is to be acquired and the extent (up to which the lock is to be acquired) is given by the ‘size’ variable. If nothing is mentioned in the place of the second parameter then the size of Long.MAX_VALUE is taken by default. The “shared” boolean variable tells that whether the lock is shared or not. If it is false then the lock is an exclusive one otherwise shared among other processes. These are some basics of the method of synchronization. Its default value is taken to be false. The main advantage of this method is that it will never be blocked. After the invocation, it either returns the acquired lock or returns null if the file is handled by another process or raises an exception. This method is generally different from the lock() method of the same class in the sense that in synchronization process had to wait long to get access to file or resources and acquire locks, but this method will never wait in turn it will return the null or exception. Syntax: Method declaration public abstract FileLock tryLock(long position, long size, boolean shared) throws IOException Example Java // Java Program to illustrate FileChannel Class// tryLock() method // Importing librariesimport java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import java.nio.channels.FileLock;import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.StandardOpenOption; // save the file named as GFG.javapublic class GFG extends Thread { // content to be written in the file. String input = "geeks for geeks is a learning portal for computer sciences."; ByteBuffer buf = ByteBuffer.wrap(input.getBytes()); // path of the file String fp = "gfg.txt"; // file channel class object Path pt = Paths.get(fp); public void run() { try { // the thread says if file is opened. FileChannel fc = FileChannel.open( pt, StandardOpenOption.WRITE, StandardOpenOption.APPEND); System.out.println( Thread.currentThread().getId() + "says:File channel is opened for writing"); // trying lock fc.tryLock(0L, Long.MAX_VALUE, false); System.out.println( Thread.currentThread().getId() + "says:acquiring lock"); // writing fc.write(buf); // release the Lock after writing System.out.print(Thread.currentThread().getId() + "says:"); System.out.println( "writing is done, closing the file"); // Closing the file connections fc.close(); } // Catch block to handle the exception catch (Exception e) { // Getting and printing current threads System.out.println( Thread.currentThread().getId() + "says: Exception" + e); } // Here, one file raises exception since the file // is being written by another thread. } // Main driver method public static void main(String[] args) throws Exception { // Creating an object in the main() method GFG g1 = new GFG(); GFG g2 = new GFG(); // Calling start() methods over the objects g1.start(); g2.start(); // Here Two thread in concurrency // are trying to access the file }} Output: Output Explanation: We are creating two threads that will try to access the file and perform a write operation on it. since to maintain synchronization we are using the trylock() method. When one of the threads acquires a lock and is doing an operation on the file and then if a second thread calls the lock to be acquired then an exception is raised by the method as the file is not free to be acquired. In the above code, we had acquired lock explicitly on the whole file. If desired we can change the size of the portion of the file on which the lock has to be acquired. simmytarika5 Java-Files Picked Technical Scripter 2020 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2021" }, { "code": null, "e": 449, "s": 28, "text": "In the case of a multi-threaded program, where multiple threads are in execution concurrently, we require locks to be acquired and released to maintain synchronization among the processes. FileChannel Class of java also provides a method known as trylock() which is used to acquire a lock on the File specified. This method is used to acquire a lock on any region of the file, specified in the parameters of the method. " }, { "code": null, "e": 960, "s": 449, "text": "A lock may be a more flexible and complicated thread synchronization mechanism than the standard synchronized block. A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, like the read lock of a ReadWriteLock." }, { "code": null, "e": 1737, "s": 960, "text": "Here the output is the object of FileLock class which mentions the lock applied, if no lock is applied (maybe due to the reason that some other processes are holding or writing the file) then this method will return null. The Position variable specifies the mark of the file from where the lock is to be acquired and the extent (up to which the lock is to be acquired) is given by the ‘size’ variable. If nothing is mentioned in the place of the second parameter then the size of Long.MAX_VALUE is taken by default. The “shared” boolean variable tells that whether the lock is shared or not. If it is false then the lock is an exclusive one otherwise shared among other processes. These are some basics of the method of synchronization. Its default value is taken to be false." }, { "code": null, "e": 2215, "s": 1737, "text": "The main advantage of this method is that it will never be blocked. After the invocation, it either returns the acquired lock or returns null if the file is handled by another process or raises an exception. This method is generally different from the lock() method of the same class in the sense that in synchronization process had to wait long to get access to file or resources and acquire locks, but this method will never wait in turn it will return the null or exception." }, { "code": null, "e": 2242, "s": 2215, "text": "Syntax: Method declaration" }, { "code": null, "e": 2337, "s": 2242, "text": "public abstract FileLock tryLock(long position, long size, boolean shared) throws IOException " }, { "code": null, "e": 2345, "s": 2337, "text": "Example" }, { "code": null, "e": 2350, "s": 2345, "text": "Java" }, { "code": "// Java Program to illustrate FileChannel Class// tryLock() method // Importing librariesimport java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import java.nio.channels.FileLock;import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.StandardOpenOption; // save the file named as GFG.javapublic class GFG extends Thread { // content to be written in the file. String input = \"geeks for geeks is a learning portal for computer sciences.\"; ByteBuffer buf = ByteBuffer.wrap(input.getBytes()); // path of the file String fp = \"gfg.txt\"; // file channel class object Path pt = Paths.get(fp); public void run() { try { // the thread says if file is opened. FileChannel fc = FileChannel.open( pt, StandardOpenOption.WRITE, StandardOpenOption.APPEND); System.out.println( Thread.currentThread().getId() + \"says:File channel is opened for writing\"); // trying lock fc.tryLock(0L, Long.MAX_VALUE, false); System.out.println( Thread.currentThread().getId() + \"says:acquiring lock\"); // writing fc.write(buf); // release the Lock after writing System.out.print(Thread.currentThread().getId() + \"says:\"); System.out.println( \"writing is done, closing the file\"); // Closing the file connections fc.close(); } // Catch block to handle the exception catch (Exception e) { // Getting and printing current threads System.out.println( Thread.currentThread().getId() + \"says: Exception\" + e); } // Here, one file raises exception since the file // is being written by another thread. } // Main driver method public static void main(String[] args) throws Exception { // Creating an object in the main() method GFG g1 = new GFG(); GFG g2 = new GFG(); // Calling start() methods over the objects g1.start(); g2.start(); // Here Two thread in concurrency // are trying to access the file }}", "e": 4699, "s": 2350, "text": null }, { "code": null, "e": 4711, "s": 4703, "text": "Output:" }, { "code": null, "e": 4735, "s": 4715, "text": "Output Explanation:" }, { "code": null, "e": 5291, "s": 4737, "text": "We are creating two threads that will try to access the file and perform a write operation on it. since to maintain synchronization we are using the trylock() method. When one of the threads acquires a lock and is doing an operation on the file and then if a second thread calls the lock to be acquired then an exception is raised by the method as the file is not free to be acquired. In the above code, we had acquired lock explicitly on the whole file. If desired we can change the size of the portion of the file on which the lock has to be acquired." }, { "code": null, "e": 5306, "s": 5293, "text": "simmytarika5" }, { "code": null, "e": 5317, "s": 5306, "text": "Java-Files" }, { "code": null, "e": 5324, "s": 5317, "text": "Picked" }, { "code": null, "e": 5348, "s": 5324, "text": "Technical Scripter 2020" }, { "code": null, "e": 5353, "s": 5348, "text": "Java" }, { "code": null, "e": 5372, "s": 5353, "text": "Technical Scripter" }, { "code": null, "e": 5377, "s": 5372, "text": "Java" } ]
Maximize number of elements from Array with sum at most K
12 May, 2021 Given an array A[] of N integers and an integer K, the task is to select the maximum number of elements from the array whose sum is at most K. Examples: Input: A[] = {1, 12, 5, 111, 200, 1000, 10}, K = 50 Output: 4 Explanation: Maximum number of selections will be 1, 12, 5, 10 that is 1 + 12 + 5 + 10 = 28 < 50. Input: A[] = {3, 7, 2, 9, 4}, K = 15 Output: 3 Explanation: Maximum number of selections will be 3, 2, 4 that is 3 + 2 + 4 =9 < 15. Naive Approach: The idea is to generate all possible subsequences of the array and find the sum of elements of all the subsequences generated. Find the subsequence with maximum length and with the sum less than or equal to K. Time Complexity: O(2N) Auxiliary Space: (1) Efficient Approach: The efficient approach can be solved using the Greedy Technique. Below are the steps: Sort the given array.Iterate in the array and keep the track of the sum of elements until the sum is less than or equal to K.If the sum while iterating in the above steps exceeds K then break the loop and print the value of count till that index. Sort the given array. Iterate in the array and keep the track of the sum of elements until the sum is less than or equal to K. If the sum while iterating in the above steps exceeds K then break the loop and print the value of count till that index. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to select a maximum number of// elements in array whose sum is at most Kint maxSelections(int A[], int n, int k){ // Sort the array sort(A, A + n); // Calculate the sum and count while // iterating the sorted array int sum = 0; int count = 0; // Iterate for all the // elements in the array for (int i = 0; i < n; i++) { // Add the current element to sum sum = sum + A[i]; if (sum > k) { break; } // Increment the count count++; } // Return the answer return count;} // Driver Codeint main(){ // Given array int A[] = { 3, 7, 2, 9, 4 }; // Given sum k int k = 15; int n = sizeof(A) / sizeof(A[0]); // Function Call cout << maxSelections(A, n, k); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to select a maximum number of// elements in array whose sum is at most Kstatic int maxSelections(int A[], int n, int k){ // Sort the array Arrays.sort(A); // Calculate the sum and count while // iterating the sorted array int sum = 0; int count = 0; // Iterate for all the // elements in the array for(int i = 0; i < n; i++) { // Add the current element to sum sum = sum + A[i]; if (sum > k) { break; } // Increment the count count++; } // Return the answer return count;} // Driver Codepublic static void main(String[] args){ // Given array int A[] = { 3, 7, 2, 9, 4 }; // Given sum k int k = 15; int n = A.length; // Function call System.out.print(maxSelections(A, n, k));}} // This code is contributed by Rajput-Ji # Python3 program for# the above approach # Function to select a maximum# number of elements in array# whose sum is at most Kdef maxSelections(A, n, k): # Sort the array A.sort(); # Calculate the sum and # count while iterating # the sorted array sum = 0; count = 0; # Iterate for all the # elements in the array for i in range(n): # Add the current element to sum sum = sum + A[i]; if (sum > k): break; # Increment the count count += 1; # Return the answer return count; # Driver Codeif __name__ == '__main__': # Given array A = [3, 7, 2, 9, 4]; # Given sum k k = 15; n = len(A); # Function call print(maxSelections(A, n, k)); # This code is contributed by gauravrajput1 // C# program for the above approachusing System; class GFG{ // Function to select a maximum number of// elements in array whose sum is at most Kstatic int maxSelections(int[] A, int n, int k){ // Sort the array Array.Sort(A); // Calculate the sum and count while // iterating the sorted array int sum = 0; int count = 0; // Iterate for all the // elements in the array for(int i = 0; i < n; i++) { // Add the current element to sum sum = sum + A[i]; if (sum > k) { break; } // Increment the count count++; } // Return the answer return count;} // Driver Codepublic static void Main(String[] args){ // Given array int[] A = { 3, 7, 2, 9, 4 }; // Given sum k int k = 15; int n = A.Length; // Function call Console.Write(maxSelections(A, n, k));}} // This code is contributed by gauravrajput1 <script> // Javascript program for the above approach // Function to select a maximum number of// elements in array whose sum is at most Kfunction maxSelections( A, n, k){ // Sort the array A.sort(); // Calculate the sum and count while // iterating the sorted array let sum = 0; let count = 0; // Iterate for all the // elements in the array for (let i = 0; i < n; i++) { // Add the current element to sum sum = sum + A[i]; if (sum > k) { break; } // Increment the count count++; } // Return the answer return count;} // Driver Code // Given arraylet A = [ 3, 7, 2, 9, 4 ]; // Given sum klet k = 15;let n = A.length; // Function Calldocument.write(maxSelections(A, n, k)); </script> 3 Time Complexity: O(N*log N) Auxiliary Space: O(1) Rajput-Ji GauravRajput1 nitin_sharma Algorithms-Greedy Algorithms subsequence Arrays Greedy Mathematical Arrays Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 May, 2021" }, { "code": null, "e": 172, "s": 28, "text": "Given an array A[] of N integers and an integer K, the task is to select the maximum number of elements from the array whose sum is at most K. " }, { "code": null, "e": 182, "s": 172, "text": "Examples:" }, { "code": null, "e": 342, "s": 182, "text": "Input: A[] = {1, 12, 5, 111, 200, 1000, 10}, K = 50 Output: 4 Explanation: Maximum number of selections will be 1, 12, 5, 10 that is 1 + 12 + 5 + 10 = 28 < 50." }, { "code": null, "e": 474, "s": 342, "text": "Input: A[] = {3, 7, 2, 9, 4}, K = 15 Output: 3 Explanation: Maximum number of selections will be 3, 2, 4 that is 3 + 2 + 4 =9 < 15." }, { "code": null, "e": 745, "s": 474, "text": "Naive Approach: The idea is to generate all possible subsequences of the array and find the sum of elements of all the subsequences generated. Find the subsequence with maximum length and with the sum less than or equal to K. Time Complexity: O(2N) Auxiliary Space: (1) " }, { "code": null, "e": 853, "s": 745, "text": "Efficient Approach: The efficient approach can be solved using the Greedy Technique. Below are the steps: " }, { "code": null, "e": 1100, "s": 853, "text": "Sort the given array.Iterate in the array and keep the track of the sum of elements until the sum is less than or equal to K.If the sum while iterating in the above steps exceeds K then break the loop and print the value of count till that index." }, { "code": null, "e": 1122, "s": 1100, "text": "Sort the given array." }, { "code": null, "e": 1227, "s": 1122, "text": "Iterate in the array and keep the track of the sum of elements until the sum is less than or equal to K." }, { "code": null, "e": 1349, "s": 1227, "text": "If the sum while iterating in the above steps exceeds K then break the loop and print the value of count till that index." }, { "code": null, "e": 1401, "s": 1349, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1407, "s": 1401, "text": "C++14" }, { "code": null, "e": 1412, "s": 1407, "text": "Java" }, { "code": null, "e": 1420, "s": 1412, "text": "Python3" }, { "code": null, "e": 1423, "s": 1420, "text": "C#" }, { "code": null, "e": 1434, "s": 1423, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to select a maximum number of// elements in array whose sum is at most Kint maxSelections(int A[], int n, int k){ // Sort the array sort(A, A + n); // Calculate the sum and count while // iterating the sorted array int sum = 0; int count = 0; // Iterate for all the // elements in the array for (int i = 0; i < n; i++) { // Add the current element to sum sum = sum + A[i]; if (sum > k) { break; } // Increment the count count++; } // Return the answer return count;} // Driver Codeint main(){ // Given array int A[] = { 3, 7, 2, 9, 4 }; // Given sum k int k = 15; int n = sizeof(A) / sizeof(A[0]); // Function Call cout << maxSelections(A, n, k); return 0;}", "e": 2306, "s": 1434, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to select a maximum number of// elements in array whose sum is at most Kstatic int maxSelections(int A[], int n, int k){ // Sort the array Arrays.sort(A); // Calculate the sum and count while // iterating the sorted array int sum = 0; int count = 0; // Iterate for all the // elements in the array for(int i = 0; i < n; i++) { // Add the current element to sum sum = sum + A[i]; if (sum > k) { break; } // Increment the count count++; } // Return the answer return count;} // Driver Codepublic static void main(String[] args){ // Given array int A[] = { 3, 7, 2, 9, 4 }; // Given sum k int k = 15; int n = A.length; // Function call System.out.print(maxSelections(A, n, k));}} // This code is contributed by Rajput-Ji", "e": 3255, "s": 2306, "text": null }, { "code": "# Python3 program for# the above approach # Function to select a maximum# number of elements in array# whose sum is at most Kdef maxSelections(A, n, k): # Sort the array A.sort(); # Calculate the sum and # count while iterating # the sorted array sum = 0; count = 0; # Iterate for all the # elements in the array for i in range(n): # Add the current element to sum sum = sum + A[i]; if (sum > k): break; # Increment the count count += 1; # Return the answer return count; # Driver Codeif __name__ == '__main__': # Given array A = [3, 7, 2, 9, 4]; # Given sum k k = 15; n = len(A); # Function call print(maxSelections(A, n, k)); # This code is contributed by gauravrajput1", "e": 3994, "s": 3255, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to select a maximum number of// elements in array whose sum is at most Kstatic int maxSelections(int[] A, int n, int k){ // Sort the array Array.Sort(A); // Calculate the sum and count while // iterating the sorted array int sum = 0; int count = 0; // Iterate for all the // elements in the array for(int i = 0; i < n; i++) { // Add the current element to sum sum = sum + A[i]; if (sum > k) { break; } // Increment the count count++; } // Return the answer return count;} // Driver Codepublic static void Main(String[] args){ // Given array int[] A = { 3, 7, 2, 9, 4 }; // Given sum k int k = 15; int n = A.Length; // Function call Console.Write(maxSelections(A, n, k));}} // This code is contributed by gauravrajput1", "e": 4923, "s": 3994, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to select a maximum number of// elements in array whose sum is at most Kfunction maxSelections( A, n, k){ // Sort the array A.sort(); // Calculate the sum and count while // iterating the sorted array let sum = 0; let count = 0; // Iterate for all the // elements in the array for (let i = 0; i < n; i++) { // Add the current element to sum sum = sum + A[i]; if (sum > k) { break; } // Increment the count count++; } // Return the answer return count;} // Driver Code // Given arraylet A = [ 3, 7, 2, 9, 4 ]; // Given sum klet k = 15;let n = A.length; // Function Calldocument.write(maxSelections(A, n, k)); </script>", "e": 5702, "s": 4923, "text": null }, { "code": null, "e": 5704, "s": 5702, "text": "3" }, { "code": null, "e": 5758, "s": 5706, "text": "Time Complexity: O(N*log N) Auxiliary Space: O(1) " }, { "code": null, "e": 5768, "s": 5758, "text": "Rajput-Ji" }, { "code": null, "e": 5782, "s": 5768, "text": "GauravRajput1" }, { "code": null, "e": 5795, "s": 5782, "text": "nitin_sharma" }, { "code": null, "e": 5824, "s": 5795, "text": "Algorithms-Greedy Algorithms" }, { "code": null, "e": 5836, "s": 5824, "text": "subsequence" }, { "code": null, "e": 5843, "s": 5836, "text": "Arrays" }, { "code": null, "e": 5850, "s": 5843, "text": "Greedy" }, { "code": null, "e": 5863, "s": 5850, "text": "Mathematical" }, { "code": null, "e": 5870, "s": 5863, "text": "Arrays" }, { "code": null, "e": 5877, "s": 5870, "text": "Greedy" }, { "code": null, "e": 5890, "s": 5877, "text": "Mathematical" } ]
Class and Instance Attributes in Python
20 Apr, 2020 Class attributes Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. # Write Python code hereclass sampleclass: count = 0 # class attribute def increase(self): sampleclass.count += 1 # Calling increase() on an objects1 = sampleclass()s1.increase() print(s1.count) # Calling increase on one more# objects2 = sampleclass()s2.increase()print(s2.count) print(sampleclass.count) Output: 1 2 2 Instance Attributes Unlike class attributes, instance attributes are not shared by objects. Every object has its own copy of the instance attribute (In case of class attributes all object refer to single copy). To list the attributes of an instance/object, we have two functions:-1. vars()– This function displays the attribute of an instance in the form of an dictionary.2. dir()– This function displays more attributes than vars function,as it is not limited to instance. It displays the class attributes as well. It also displays the attributes of its ancestor classes. # Python program to demonstrate# instance attributes.class emp: def __init__(self): self.name = 'xyz' self.salary = 4000 def show(self): print(self.name) print(self.salary) e1 = emp()print("Dictionary form :", vars(e1))print(dir(e1)) Output : Dictionary form :{'salary': 4000, 'name': 'xyz'} ['__doc__', '__init__', '__module__', 'name', 'salary', 'show'] This article is contributed by Harsh Valecha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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. Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Apr, 2020" }, { "code": null, "e": 69, "s": 52, "text": "Class attributes" }, { "code": null, "e": 243, "s": 69, "text": "Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility." }, { "code": "# Write Python code hereclass sampleclass: count = 0 # class attribute def increase(self): sampleclass.count += 1 # Calling increase() on an objects1 = sampleclass()s1.increase() print(s1.count) # Calling increase on one more# objects2 = sampleclass()s2.increase()print(s2.count) print(sampleclass.count)", "e": 577, "s": 243, "text": null }, { "code": null, "e": 585, "s": 577, "text": "Output:" }, { "code": null, "e": 632, "s": 585, "text": "1 \n2 \n2" }, { "code": null, "e": 652, "s": 632, "text": "Instance Attributes" }, { "code": null, "e": 843, "s": 652, "text": "Unlike class attributes, instance attributes are not shared by objects. Every object has its own copy of the instance attribute (In case of class attributes all object refer to single copy)." }, { "code": null, "e": 1205, "s": 843, "text": "To list the attributes of an instance/object, we have two functions:-1. vars()– This function displays the attribute of an instance in the form of an dictionary.2. dir()– This function displays more attributes than vars function,as it is not limited to instance. It displays the class attributes as well. It also displays the attributes of its ancestor classes." }, { "code": "# Python program to demonstrate# instance attributes.class emp: def __init__(self): self.name = 'xyz' self.salary = 4000 def show(self): print(self.name) print(self.salary) e1 = emp()print(\"Dictionary form :\", vars(e1))print(dir(e1))", "e": 1476, "s": 1205, "text": null }, { "code": null, "e": 1485, "s": 1476, "text": "Output :" }, { "code": null, "e": 1598, "s": 1485, "text": "Dictionary form :{'salary': 4000, 'name': 'xyz'}\n['__doc__', '__init__', '__module__', 'name', 'salary', 'show']" }, { "code": null, "e": 1899, "s": 1598, "text": "This article is contributed by Harsh Valecha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2024, "s": 1899, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2031, "s": 2024, "text": "Python" }, { "code": null, "e": 2050, "s": 2031, "text": "Technical Scripter" } ]
Opening and Reading a File in Julia
20 Jul, 2021 File handling in Julia is achieved using functions such as open(), read(), close(). There are many ways to read the contents of a file like readline(), readlines() and just read(). open(): To open a file existing in an absolute path, provided as the parameter. read(): Read the contents of the file into a single string. close(): Close the file object or the variable holding the instance of an opened file. Consider a file “text.txt” placed in the same working directory along with Julia’s implementation file.test.txt one two three four five six Now we will use open() function to open a file in readable mode Syntax : f = open("absolute path of the file", "r") # few file operations close(f) There are two methods to Open a file using open() function: Method 1 Open a file using open() and assign it to a variable which is the instance of the opened file, then make use of that variable for further operations to be performed on the opened file.Then close the file using close(). Python3 # Opening a file in read_mode, method 1# r is the default mode f = open("test.txt", "r") # do some file operations # close the file instanceclose(f) Method 2 Open a file in union with a ‘do’ control flow. The opened file will automatically be closed once the end of do loop is attained. Perform the desired operations within the do control flow. This is the most common and handy way of opening and accessing a file. Python3 # opening a file in read_mode, method 2open("test.txt") do f # do stuff with the open file instance 'f' end # opened file is automatically closed after the do control ends. Reading a File can be done in multiple ways with the use of pre-defined functions in Julia. Files can be read line by line, in the form of strings or the whole file at once. Read the file contents line by line using readline() Function Suppose a file has n lines within. We can use the readline() function to read the contents of the file in a line by line manner(one line at a time) until the EOF (End of file) is attained. Python3 # read file contents, one line at a time open("test.txt") do f # line_number line = 0 # read till end of file while ! eof(f) # read a new / next line for every iteration s = readline(f) line += 1 println("$line . $s") end end Output: Reading the lines of a file into a String array using readlines() readlines() method is used to read all the lines of the file into a String array. Where every element is a line of the file. Using this we can read multiple lines at once. Python3 # opening a file in read_mode# r is the default mode f = open("test.txt", "r") # to count total lines in the fileline_count = 0 for lines in readlines(f) # increment line_count global line_count += 1 # print the line println(lines) end # total lines in fileprintln("line count is $line_count") close(f) Output: Read all contents of a file into a String at once using read() The file contents are entirely read into a single string using the read() method.Syntax: s = read(f, String) # f can be a file object or an absolute path Python # opening a file in read_mode f = open("test.txt", "r") # read entire file into a strings = read(f, String) print(s)close(f) Output: Till now we have assumed the case where our file exists in the specified path. What if a file doesn’t exist in the specified path? Python3 # opening a file in read_mode # dummy.txt doesn't exist# in the working directoryf = open("dummy.txt", "r") close(f) Output: We will handle this using the Try-Catch block in Julia.Open the file in try block using open(), if the file exists, then perform the desired operation. Else the try block will throw an exception and the control reaches the catch block. The user can be warned in the try block using a println() message or @warn. Python3 # since the presence of file is uncertain we'll use try catchtry open("dummy.txt", "r") do s # perform desired operations if file exists endcatch # either warn or print that the file doesn't exist println("file doesn't exist")end Output: adnanirshad158 julia-FileHandling Picked Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jul, 2021" }, { "code": null, "e": 234, "s": 52, "text": "File handling in Julia is achieved using functions such as open(), read(), close(). There are many ways to read the contents of a file like readline(), readlines() and just read(). " }, { "code": null, "e": 316, "s": 234, "text": "open(): To open a file existing in an absolute path, provided as the parameter. " }, { "code": null, "e": 378, "s": 316, "text": "read(): Read the contents of the file into a single string. " }, { "code": null, "e": 467, "s": 378, "text": "close(): Close the file object or the variable holding the instance of an opened file. " }, { "code": null, "e": 581, "s": 467, "text": "Consider a file “text.txt” placed in the same working directory along with Julia’s implementation file.test.txt " }, { "code": null, "e": 609, "s": 581, "text": "one\ntwo\nthree\nfour\nfive\nsix" }, { "code": null, "e": 684, "s": 609, "text": "Now we will use open() function to open a file in readable mode Syntax : " }, { "code": null, "e": 760, "s": 684, "text": "f = open(\"absolute path of the file\", \"r\")\n\n# few file operations \nclose(f)" }, { "code": null, "e": 822, "s": 760, "text": "There are two methods to Open a file using open() function: " }, { "code": null, "e": 831, "s": 822, "text": "Method 1" }, { "code": null, "e": 1051, "s": 831, "text": "Open a file using open() and assign it to a variable which is the instance of the opened file, then make use of that variable for further operations to be performed on the opened file.Then close the file using close(). " }, { "code": null, "e": 1059, "s": 1051, "text": "Python3" }, { "code": "# Opening a file in read_mode, method 1# r is the default mode f = open(\"test.txt\", \"r\") # do some file operations # close the file instanceclose(f)", "e": 1208, "s": 1059, "text": null }, { "code": null, "e": 1217, "s": 1208, "text": "Method 2" }, { "code": null, "e": 1477, "s": 1217, "text": "Open a file in union with a ‘do’ control flow. The opened file will automatically be closed once the end of do loop is attained. Perform the desired operations within the do control flow. This is the most common and handy way of opening and accessing a file. " }, { "code": null, "e": 1485, "s": 1477, "text": "Python3" }, { "code": "# opening a file in read_mode, method 2open(\"test.txt\") do f # do stuff with the open file instance 'f' end # opened file is automatically closed after the do control ends.", "e": 1662, "s": 1485, "text": null }, { "code": null, "e": 1837, "s": 1662, "text": "Reading a File can be done in multiple ways with the use of pre-defined functions in Julia. Files can be read line by line, in the form of strings or the whole file at once. " }, { "code": null, "e": 1899, "s": 1837, "text": "Read the file contents line by line using readline() Function" }, { "code": null, "e": 2089, "s": 1899, "text": "Suppose a file has n lines within. We can use the readline() function to read the contents of the file in a line by line manner(one line at a time) until the EOF (End of file) is attained. " }, { "code": null, "e": 2097, "s": 2089, "text": "Python3" }, { "code": "# read file contents, one line at a time open(\"test.txt\") do f # line_number line = 0 # read till end of file while ! eof(f) # read a new / next line for every iteration s = readline(f) line += 1 println(\"$line . $s\") end end", "e": 2369, "s": 2097, "text": null }, { "code": null, "e": 2379, "s": 2369, "text": "Output: " }, { "code": null, "e": 2447, "s": 2381, "text": "Reading the lines of a file into a String array using readlines()" }, { "code": null, "e": 2620, "s": 2447, "text": "readlines() method is used to read all the lines of the file into a String array. Where every element is a line of the file. Using this we can read multiple lines at once. " }, { "code": null, "e": 2628, "s": 2620, "text": "Python3" }, { "code": "# opening a file in read_mode# r is the default mode f = open(\"test.txt\", \"r\") # to count total lines in the fileline_count = 0 for lines in readlines(f) # increment line_count global line_count += 1 # print the line println(lines) end # total lines in fileprintln(\"line count is $line_count\") close(f)", "e": 2966, "s": 2628, "text": null }, { "code": null, "e": 2975, "s": 2966, "text": "Output: " }, { "code": null, "e": 3040, "s": 2977, "text": "Read all contents of a file into a String at once using read()" }, { "code": null, "e": 3131, "s": 3040, "text": "The file contents are entirely read into a single string using the read() method.Syntax: " }, { "code": null, "e": 3197, "s": 3131, "text": "s = read(f, String)\n\n# f can be a file object or an absolute path" }, { "code": null, "e": 3206, "s": 3199, "text": "Python" }, { "code": "# opening a file in read_mode f = open(\"test.txt\", \"r\") # read entire file into a strings = read(f, String) print(s)close(f)", "e": 3337, "s": 3206, "text": null }, { "code": null, "e": 3347, "s": 3337, "text": "Output: " }, { "code": null, "e": 3481, "s": 3349, "text": "Till now we have assumed the case where our file exists in the specified path. What if a file doesn’t exist in the specified path? " }, { "code": null, "e": 3489, "s": 3481, "text": "Python3" }, { "code": "# opening a file in read_mode # dummy.txt doesn't exist# in the working directoryf = open(\"dummy.txt\", \"r\") close(f)", "e": 3613, "s": 3489, "text": null }, { "code": null, "e": 3623, "s": 3613, "text": "Output: " }, { "code": null, "e": 3938, "s": 3625, "text": "We will handle this using the Try-Catch block in Julia.Open the file in try block using open(), if the file exists, then perform the desired operation. Else the try block will throw an exception and the control reaches the catch block. The user can be warned in the try block using a println() message or @warn. " }, { "code": null, "e": 3946, "s": 3938, "text": "Python3" }, { "code": "# since the presence of file is uncertain we'll use try catchtry open(\"dummy.txt\", \"r\") do s # perform desired operations if file exists endcatch # either warn or print that the file doesn't exist println(\"file doesn't exist\")end", "e": 4196, "s": 3946, "text": null }, { "code": null, "e": 4206, "s": 4196, "text": "Output: " }, { "code": null, "e": 4223, "s": 4208, "text": "adnanirshad158" }, { "code": null, "e": 4242, "s": 4223, "text": "julia-FileHandling" }, { "code": null, "e": 4249, "s": 4242, "text": "Picked" }, { "code": null, "e": 4255, "s": 4249, "text": "Julia" } ]
turtle.setworldcoordinates() function in Python
25 Aug, 2021 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This function is used to set up a user-defined coordinate system. This performs a reset. If mode ‘world’ is already active, all drawings are redrawn according to the new coordinates. Note: In user-defined coordinate systems angles may appear distorted. Syntax : turtle.setworldcoordinates(llx, lly, urx, ury) Parameters: llx: a number, x-coordinate of lower left corner of canvas lly: a number, y-coordinate of lower left corner of canvas urx: a number, x-coordinate of upper right corner of canvas ury: a number, y-coordinate of upper right corner of canvas Below is the implementation of the above method with some examples : Example 1 : Python3 # importing packageimport turtle # make screen object and# set screen mode to worldsc = turtle.Screen()sc.mode('world') # set world coordinatesturtle.setworldcoordinates(-20, -20, 20, 20) # loop for some motionfor i in range(20): turtle.forward(1+1*i) turtle.right(90) Output: Part A Example 2: Python3 # importing packageimport turtle # make screen object and# set screen mode to worldsc = turtle.Screen()sc.mode('world') # set world coordinatesturtle.setworldcoordinates(-40, -40, 40, 40) # loop for some motionfor i in range(20): turtle.forward(1+1*i) turtle.right(90) Output : In the above two examples, the code are the same and only the difference of world coordinates differ the output as shown below : Example 3 : Python3 # importing packageimport turtle # make screen object and# set mode to worldsc = turtle.Screen()sc.mode('world') # set world coordinatesturtle.setworldcoordinates(-50, -50, 50, 50) # do some motionfor i in range(16): turtle.forward(1+1*i) turtle.right(90) # set world coordinatesturtle.setworldcoordinates(-40, -40, 40, 40) # do some motionfor i in range(16): turtle.forward(1+1*(i+16)) turtle.right(90) # set world coordinatesturtle.setworldcoordinates(-30, -30, 30, 30) # do some motionfor i in range(16): turtle.forward(1+1*(i+32)) turtle.right(90) Output : Here, we can see that the all previous drawing is set to new world coordinates ( drawing enlarges ). sumitgumber28 Python-turtle 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 Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Aug, 2021" }, { "code": null, "e": 245, "s": 28, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 429, "s": 245, "text": "This function is used to set up a user-defined coordinate system. This performs a reset. If mode ‘world’ is already active, all drawings are redrawn according to the new coordinates. " }, { "code": null, "e": 499, "s": 429, "text": "Note: In user-defined coordinate systems angles may appear distorted." }, { "code": null, "e": 556, "s": 499, "text": "Syntax : turtle.setworldcoordinates(llx, lly, urx, ury) " }, { "code": null, "e": 568, "s": 556, "text": "Parameters:" }, { "code": null, "e": 627, "s": 568, "text": "llx: a number, x-coordinate of lower left corner of canvas" }, { "code": null, "e": 686, "s": 627, "text": "lly: a number, y-coordinate of lower left corner of canvas" }, { "code": null, "e": 746, "s": 686, "text": "urx: a number, x-coordinate of upper right corner of canvas" }, { "code": null, "e": 806, "s": 746, "text": "ury: a number, y-coordinate of upper right corner of canvas" }, { "code": null, "e": 875, "s": 806, "text": "Below is the implementation of the above method with some examples :" }, { "code": null, "e": 887, "s": 875, "text": "Example 1 :" }, { "code": null, "e": 895, "s": 887, "text": "Python3" }, { "code": "# importing packageimport turtle # make screen object and# set screen mode to worldsc = turtle.Screen()sc.mode('world') # set world coordinatesturtle.setworldcoordinates(-20, -20, 20, 20) # loop for some motionfor i in range(20): turtle.forward(1+1*i) turtle.right(90)", "e": 1170, "s": 895, "text": null }, { "code": null, "e": 1178, "s": 1170, "text": "Output:" }, { "code": null, "e": 1185, "s": 1178, "text": "Part A" }, { "code": null, "e": 1197, "s": 1185, "text": " Example 2:" }, { "code": null, "e": 1205, "s": 1197, "text": "Python3" }, { "code": "# importing packageimport turtle # make screen object and# set screen mode to worldsc = turtle.Screen()sc.mode('world') # set world coordinatesturtle.setworldcoordinates(-40, -40, 40, 40) # loop for some motionfor i in range(20): turtle.forward(1+1*i) turtle.right(90)", "e": 1480, "s": 1205, "text": null }, { "code": null, "e": 1489, "s": 1480, "text": "Output :" }, { "code": null, "e": 1619, "s": 1489, "text": "In the above two examples, the code are the same and only the difference of world coordinates differ the output as shown below :" }, { "code": null, "e": 1632, "s": 1619, "text": "Example 3 :" }, { "code": null, "e": 1640, "s": 1632, "text": "Python3" }, { "code": "# importing packageimport turtle # make screen object and# set mode to worldsc = turtle.Screen()sc.mode('world') # set world coordinatesturtle.setworldcoordinates(-50, -50, 50, 50) # do some motionfor i in range(16): turtle.forward(1+1*i) turtle.right(90) # set world coordinatesturtle.setworldcoordinates(-40, -40, 40, 40) # do some motionfor i in range(16): turtle.forward(1+1*(i+16)) turtle.right(90) # set world coordinatesturtle.setworldcoordinates(-30, -30, 30, 30) # do some motionfor i in range(16): turtle.forward(1+1*(i+32)) turtle.right(90)", "e": 2210, "s": 1640, "text": null }, { "code": null, "e": 2219, "s": 2210, "text": "Output :" }, { "code": null, "e": 2320, "s": 2219, "text": "Here, we can see that the all previous drawing is set to new world coordinates ( drawing enlarges )." }, { "code": null, "e": 2334, "s": 2320, "text": "sumitgumber28" }, { "code": null, "e": 2348, "s": 2334, "text": "Python-turtle" }, { "code": null, "e": 2355, "s": 2348, "text": "Python" }, { "code": null, "e": 2453, "s": 2355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2471, "s": 2453, "text": "Python Dictionary" }, { "code": null, "e": 2513, "s": 2471, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2535, "s": 2513, "text": "Enumerate() in Python" }, { "code": null, "e": 2570, "s": 2535, "text": "Read a file line by line in Python" }, { "code": null, "e": 2596, "s": 2570, "text": "Python String | replace()" }, { "code": null, "e": 2628, "s": 2596, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2657, "s": 2628, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2684, "s": 2657, "text": "Python Classes and Objects" }, { "code": null, "e": 2714, "s": 2684, "text": "Iterate over a list in Python" } ]
Program to calculate product of digits of a number
24 Nov, 2021 Given a number, the task is to find the product of the digits of a number. Examples: Input: n = 4513 Output: 60 Input: n = 5249 Output: 360 General Algorithm for product of digits in a given number: Get the numberDeclare a variable to store the product and set it to 1Repeat the next two steps till the number is not 0Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and multiply it with product.Divide the number by 10 with help of ‘/’ operatorPrint or return the product. Get the number Declare a variable to store the product and set it to 1 Repeat the next two steps till the number is not 0 Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and multiply it with product. Divide the number by 10 with help of ‘/’ operator Print or return the product. Below is the solution to get the product of the digits: C++ Java Python3 C# PHP Javascript // C++ program to compute// product of digits in the number.#include<bits/stdc++.h>using namespace std; /* Function to get product of digits */int getProduct(int n){ int product = 1; while (n != 0) { product = product * (n % 10); n = n / 10; } return product;} // Driver programint main(){ int n = 4513; cout << (getProduct(n));} // This code is contributed by// Surendra_Gangwar // Java program to compute// product of digits in the number. import java.io.*; class GFG { /* Function to get product of digits */ static int getProduct(int n) { int product = 1; while (n != 0) { product = product * (n % 10); n = n / 10; } return product; } // Driver program public static void main(String[] args) { int n = 4513; System.out.println(getProduct(n)); }} # Python3 program to compute# product of digits in the number. # Function to get product of digitsdef getProduct(n): product = 1 while (n != 0): product = product * (n % 10) n = n // 10 return product # Driver Coden = 4513print(getProduct(n)) # This code is contributed# by mohit kumar // C# program to compute// product of digits in the number.using System; class GFG{ /* Function to get product of digits */ static int getProduct(int n) { int product = 1; while (n != 0) { product = product * (n % 10); n = n / 10; } return product; } // Driver program public static void Main() { int n = 4513; Console.WriteLine(getProduct(n)); }} // This code is contributed by Ryuga <?php <?php // PHP program to compute// $product of digits in the number. /* Function to get $product of digits */ function getProduct($n){ $product = 1; while ($n != 0) { $product = $product * ( $n % 10); $n = intdiv($n , 10); } return $product;} // Driver code $n = 4513;echo getProduct($n); // This code is contributed by// ihritik ?> <script> // JavaScript program to compute// product of digits in the number. // Function to get product of digitsfunction getProduct(n){ let product = 1; while (n != 0) { product = product * (n % 10); n = Math.floor(n / 10); } return product;} // Driver codelet n = 4513; document.write(getProduct(n)); // This code is contributed by Manoj. </script> 60 Convert the integer to string Traverse the string and multiply the characters by converting them to integer When this method can be used?: When the number of digits of a number exceeds , we can’t take that number as an integer since the range of long long int doesn’t satisfy the given number. So take input as a string, run a loop from start to the length of the string and increase the sum with that character(in this case it is numeric) Below is the implementation: C++ Java Python3 C# Javascript #include <iostream>using namespace std;int getProduct(string str){ int product = 1; // Traversing through the string for (int i = 0; i < str.length(); i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum product = product * (str[i] - 48); } return product;} // Driver Codeint main(){ string st = "4513"; cout << getProduct(st); return 0;} import java.io.*; class GFG { static int getProduct(String str){ int product = 1; // Traversing through the string for (int i = 0; i < str.length(); i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum product *= str.charAt(i) - '0'; } return product;} // Driver Codepublic static void main(String[] args){ String st = "4513"; System.out.println(getProduct(st)); }}//this code is contributed by shivanisinghss2110 # Python3 program to compute# product of digits in the number. # Function to get product of digitsdef getProduct(n): product = 1 # Converting integer to string num = str(n) # Traversing the string for i in num: product = product * int(i) return product # Driver Coden = 4513print(getProduct(n)) # This code is contributed by vikkycirus using System;using System.Collections; class GFG{ static int getProduct(String str){ int product = 1; // Traversing through the string for (int i = 0; i < str.Length; i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum product = product * (str[i] - 48); } return product;} // Driver Codepublic static void Main(String[] args){ String st = "4513"; Console.Write(getProduct(st)); }} //This code is contributed by shivanisinghss2110 <script> function getProduct(str){ let product = 1; // Traversing through the string for (let i = 0; i < str.length; i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum product = product * (parseInt(str[i])); } return product;} // Driver Codelet st = "4513";document.write(getProduct(st)); // This code is contributed by unknown2108</script> Output: 60 Method #3: Recursion Get the number Get the remainder and pass the next remaining digitsGet the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and multiply it to the product. Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit Check the base case with n = 0Print or return the product Get the number Get the remainder and pass the next remaining digits Get the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and multiply it to the product. Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit Check the base case with n = 0 Print or return the product C++ //Recursive function to get product of the digits #include <iostream>using namespace std; int getProduct(int n){ // Base Case if(n == 0){ return 1 ; } // get the last digit and multiply it with remaining digits return (n%10) * getProduct(n/10) ;} int main() { // call the function cout<<getProduct(125) ; return 0;} mohit kumar 29 ankthon SURENDRA_GANGWAR ihritik vikkycirus mank1083 swarnalii unknown2108 shivanisinghss2110 prasanna1995 number-digits School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2021" }, { "code": null, "e": 103, "s": 28, "text": "Given a number, the task is to find the product of the digits of a number." }, { "code": null, "e": 114, "s": 103, "text": "Examples: " }, { "code": null, "e": 170, "s": 114, "text": "Input: n = 4513\nOutput: 60\n\nInput: n = 5249\nOutput: 360" }, { "code": null, "e": 231, "s": 170, "text": "General Algorithm for product of digits in a given number: " }, { "code": null, "e": 554, "s": 231, "text": "Get the numberDeclare a variable to store the product and set it to 1Repeat the next two steps till the number is not 0Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and multiply it with product.Divide the number by 10 with help of ‘/’ operatorPrint or return the product." }, { "code": null, "e": 569, "s": 554, "text": "Get the number" }, { "code": null, "e": 625, "s": 569, "text": "Declare a variable to store the product and set it to 1" }, { "code": null, "e": 676, "s": 625, "text": "Repeat the next two steps till the number is not 0" }, { "code": null, "e": 803, "s": 676, "text": "Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and multiply it with product." }, { "code": null, "e": 853, "s": 803, "text": "Divide the number by 10 with help of ‘/’ operator" }, { "code": null, "e": 882, "s": 853, "text": "Print or return the product." }, { "code": null, "e": 939, "s": 882, "text": "Below is the solution to get the product of the digits: " }, { "code": null, "e": 943, "s": 939, "text": "C++" }, { "code": null, "e": 948, "s": 943, "text": "Java" }, { "code": null, "e": 956, "s": 948, "text": "Python3" }, { "code": null, "e": 959, "s": 956, "text": "C#" }, { "code": null, "e": 963, "s": 959, "text": "PHP" }, { "code": null, "e": 974, "s": 963, "text": "Javascript" }, { "code": "// C++ program to compute// product of digits in the number.#include<bits/stdc++.h>using namespace std; /* Function to get product of digits */int getProduct(int n){ int product = 1; while (n != 0) { product = product * (n % 10); n = n / 10; } return product;} // Driver programint main(){ int n = 4513; cout << (getProduct(n));} // This code is contributed by// Surendra_Gangwar", "e": 1391, "s": 974, "text": null }, { "code": "// Java program to compute// product of digits in the number. import java.io.*; class GFG { /* Function to get product of digits */ static int getProduct(int n) { int product = 1; while (n != 0) { product = product * (n % 10); n = n / 10; } return product; } // Driver program public static void main(String[] args) { int n = 4513; System.out.println(getProduct(n)); }}", "e": 1854, "s": 1391, "text": null }, { "code": "# Python3 program to compute# product of digits in the number. # Function to get product of digitsdef getProduct(n): product = 1 while (n != 0): product = product * (n % 10) n = n // 10 return product # Driver Coden = 4513print(getProduct(n)) # This code is contributed# by mohit kumar", "e": 2166, "s": 1854, "text": null }, { "code": "// C# program to compute// product of digits in the number.using System; class GFG{ /* Function to get product of digits */ static int getProduct(int n) { int product = 1; while (n != 0) { product = product * (n % 10); n = n / 10; } return product; } // Driver program public static void Main() { int n = 4513; Console.WriteLine(getProduct(n)); }} // This code is contributed by Ryuga", "e": 2651, "s": 2166, "text": null }, { "code": "<?php <?php // PHP program to compute// $product of digits in the number. /* Function to get $product of digits */ function getProduct($n){ $product = 1; while ($n != 0) { $product = $product * ( $n % 10); $n = intdiv($n , 10); } return $product;} // Driver code $n = 4513;echo getProduct($n); // This code is contributed by// ihritik ?>", "e": 3021, "s": 2651, "text": null }, { "code": "<script> // JavaScript program to compute// product of digits in the number. // Function to get product of digitsfunction getProduct(n){ let product = 1; while (n != 0) { product = product * (n % 10); n = Math.floor(n / 10); } return product;} // Driver codelet n = 4513; document.write(getProduct(n)); // This code is contributed by Manoj. </script>", "e": 3402, "s": 3021, "text": null }, { "code": null, "e": 3405, "s": 3402, "text": "60" }, { "code": null, "e": 3437, "s": 3407, "text": "Convert the integer to string" }, { "code": null, "e": 3515, "s": 3437, "text": "Traverse the string and multiply the characters by converting them to integer" }, { "code": null, "e": 3848, "s": 3515, "text": "When this method can be used?: When the number of digits of a number exceeds , we can’t take that number as an integer since the range of long long int doesn’t satisfy the given number. So take input as a string, run a loop from start to the length of the string and increase the sum with that character(in this case it is numeric)" }, { "code": null, "e": 3877, "s": 3848, "text": "Below is the implementation:" }, { "code": null, "e": 3881, "s": 3877, "text": "C++" }, { "code": null, "e": 3886, "s": 3881, "text": "Java" }, { "code": null, "e": 3894, "s": 3886, "text": "Python3" }, { "code": null, "e": 3897, "s": 3894, "text": "C#" }, { "code": null, "e": 3908, "s": 3897, "text": "Javascript" }, { "code": "#include <iostream>using namespace std;int getProduct(string str){ int product = 1; // Traversing through the string for (int i = 0; i < str.length(); i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum product = product * (str[i] - 48); } return product;} // Driver Codeint main(){ string st = \"4513\"; cout << getProduct(st); return 0;}", "e": 4336, "s": 3908, "text": null }, { "code": "import java.io.*; class GFG { static int getProduct(String str){ int product = 1; // Traversing through the string for (int i = 0; i < str.length(); i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum product *= str.charAt(i) - '0'; } return product;} // Driver Codepublic static void main(String[] args){ String st = \"4513\"; System.out.println(getProduct(st)); }}//this code is contributed by shivanisinghss2110", "e": 4855, "s": 4336, "text": null }, { "code": "# Python3 program to compute# product of digits in the number. # Function to get product of digitsdef getProduct(n): product = 1 # Converting integer to string num = str(n) # Traversing the string for i in num: product = product * int(i) return product # Driver Coden = 4513print(getProduct(n)) # This code is contributed by vikkycirus", "e": 5225, "s": 4855, "text": null }, { "code": "using System;using System.Collections; class GFG{ static int getProduct(String str){ int product = 1; // Traversing through the string for (int i = 0; i < str.Length; i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum product = product * (str[i] - 48); } return product;} // Driver Codepublic static void Main(String[] args){ String st = \"4513\"; Console.Write(getProduct(st)); }} //This code is contributed by shivanisinghss2110", "e": 5760, "s": 5225, "text": null }, { "code": "<script> function getProduct(str){ let product = 1; // Traversing through the string for (let i = 0; i < str.length; i++) { // Since ascii value of // numbers starts from 48 // so we subtract it from sum product = product * (parseInt(str[i])); } return product;} // Driver Codelet st = \"4513\";document.write(getProduct(st)); // This code is contributed by unknown2108</script>", "e": 6191, "s": 5760, "text": null }, { "code": null, "e": 6199, "s": 6191, "text": "Output:" }, { "code": null, "e": 6202, "s": 6199, "text": "60" }, { "code": null, "e": 6223, "s": 6202, "text": "Method #3: Recursion" }, { "code": null, "e": 6560, "s": 6223, "text": "Get the number Get the remainder and pass the next remaining digitsGet the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and multiply it to the product. Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit Check the base case with n = 0Print or return the product" }, { "code": null, "e": 6575, "s": 6560, "text": "Get the number" }, { "code": null, "e": 6629, "s": 6575, "text": " Get the remainder and pass the next remaining digits" }, { "code": null, "e": 6760, "s": 6629, "text": "Get the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and multiply it to the product." }, { "code": null, "e": 6842, "s": 6760, "text": " Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit" }, { "code": null, "e": 6874, "s": 6842, "text": " Check the base case with n = 0" }, { "code": null, "e": 6902, "s": 6874, "text": "Print or return the product" }, { "code": null, "e": 6906, "s": 6902, "text": "C++" }, { "code": "//Recursive function to get product of the digits #include <iostream>using namespace std; int getProduct(int n){ // Base Case if(n == 0){ return 1 ; } // get the last digit and multiply it with remaining digits return (n%10) * getProduct(n/10) ;} int main() { // call the function cout<<getProduct(125) ; return 0;}", "e": 7258, "s": 6906, "text": null }, { "code": null, "e": 7273, "s": 7258, "text": "mohit kumar 29" }, { "code": null, "e": 7281, "s": 7273, "text": "ankthon" }, { "code": null, "e": 7298, "s": 7281, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 7306, "s": 7298, "text": "ihritik" }, { "code": null, "e": 7317, "s": 7306, "text": "vikkycirus" }, { "code": null, "e": 7326, "s": 7317, "text": "mank1083" }, { "code": null, "e": 7336, "s": 7326, "text": "swarnalii" }, { "code": null, "e": 7348, "s": 7336, "text": "unknown2108" }, { "code": null, "e": 7367, "s": 7348, "text": "shivanisinghss2110" }, { "code": null, "e": 7380, "s": 7367, "text": "prasanna1995" }, { "code": null, "e": 7394, "s": 7380, "text": "number-digits" }, { "code": null, "e": 7413, "s": 7394, "text": "School Programming" } ]
How to initialize multiple tables using jQuery DataTables plugin ?
15 Jan, 2021 DataTables are a modern jQuery plugin for adding interactive and advanced controls to HTML tables for our webpage. It is a very simple-to-use plug-in with a variety of options for the developer’s custom changes as per the application need. The plugin’s features include pagination, sorting, searching, and multiple-column ordering. In this article, we will learn to initialize multiple HTML tables using the jQuery DataTables plugin The pre-compiled files which are needed to implement are CSS: https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css JavaScript: https: //cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js Example: Initialization of multiple tables is handled with one line of code by using the table.display selector. Both the tables can be operated together, but they are executed independently. <!DOCTYPE html><html> <head> <meta content="initial-scale=1, maximum-scale=1, user-scalable=0" name="viewport" /> <meta name="viewport" content="width=device-width" /> <!--Datatable plugin CSS file --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css" /> <!--jQuery library file --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!--Datatable plugin JS library file --> <script type="text/javascript" src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"> </script></head> <body> <h2> Multiple tables operations using jQuery Datatables </h2> <!--HTML tables with student data--> <table id="" class="display" style="width:100%"> <thead> <tr> <th>StudentID</th> <th>StudentName</th> <th>Age</th> <th>Gender</th> <th>Marks Scored</th> </tr> </thead> <tbody> <tr> <td>ST1</td> <td>Prema</td> <td>35</td> <td>Female</td> <td>320</td> </tr> <tr> <td>ST2</td> <td>Wincy</td> <td>36</td> <td>Female</td> <td>170</td> </tr> <tr> <td>ST3</td> <td>Ashmita</td> <td>41</td> <td>Female</td> <td>860</td> </tr> <tr> <td>ST4</td> <td>Kelina</td> <td>32</td> <td>Female</td> <td>433</td> </tr> <tr> <td>ST5</td> <td>Satvik</td> <td>41</td> <td>male</td> <td>162</td> </tr> <tr> <td>ST6</td> <td>William</td> <td>37</td> <td>Female</td> <td>372</td> </tr> <tr> <td>ST7</td> <td>Chandan</td> <td>31</td> <td>male</td> <td>375</td> </tr> <tr> <td>ST8</td> <td>David</td> <td>45</td> <td>male</td> <td>327</td> </tr> <tr> <td>ST9</td> <td>Harry</td> <td>29</td> <td>male</td> <td>205</td> </tr> <tr> <td>ST10</td> <td>Frost</td> <td>29</td> <td>male</td> <td>300</td> </tr> <tr> <td>ST11</td> <td>Ginny</td> <td>31</td> <td>male</td> <td>560</td> </tr> <tr> <td>ST12</td> <td>Flod</td> <td>45</td> <td>Female</td> <td>342</td> </tr> <tr> <td>ST13</td> <td>Marshy</td> <td>23</td> <td>Female</td> <td>470</td> </tr> <tr> <td>ST13</td> <td>Kennedy</td> <td>43</td> <td>male</td> <td>313</td> </tr> <tr> <td>ST14</td> <td>Fiza</td> <td>31</td> <td>Female</td> <td>750</td> </tr> <tr> <td>ST15</td> <td>Silva</td> <td>34</td> <td>male</td> <td>985</td> </tr> </tbody> </table> <br /> <table id="" class="display" style="width:100%"> <thead> <tr> <th>StudentID</th> <th>StudentName</th> <th>Age</th> <th>Gender</th> <th>Marks Scored</th> </tr> </thead> <tbody> <tr> <td>ST15</td> <td>Varun</td> <td>41</td> <td>male</td> <td>262</td> </tr> <tr> <td>ST16</td> <td>Waheeda</td> <td>47</td> <td>Female</td> <td>373</td> </tr> <tr> <td>ST17</td> <td>Charu</td> <td>31</td> <td>female</td> <td>475</td> </tr> <tr> <td>ST18</td> <td>Dhriti</td> <td>45</td> <td>female</td> <td>227</td> </tr> <tr> <td>ST19</td> <td>Haritha</td> <td>39</td> <td>female</td> <td>295</td> </tr> <tr> <td>ST20</td> <td>Faran</td> <td>39</td> <td>male</td> <td>340</td> </tr> <tr> <td>ST21</td> <td>Gaurav</td> <td>31</td> <td>male</td> <td>562</td> </tr> <tr> <td>ST22</td> <td>Fenny</td> <td>41</td> <td>Female</td> <td>349</td> </tr> <tr> <td>ST23</td> <td>Mamta</td> <td>29</td> <td>Female</td> <td>471</td> </tr> <tr> <td>ST23</td> <td>Kamat</td> <td>44</td> <td>male</td> <td>319</td> </tr> </tbody> </table> <script> /* Initialization of datatables */ $(document).ready(function () { $('table.display').DataTable(); }); </script></body> </html> Output: The following output shows that data for both the tables are loaded after initialization. The following output shows that both the tables are executed independently showing the “searching” operation for “female” students. HTML-Misc jQuery-Plugin HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jan, 2021" }, { "code": null, "e": 360, "s": 28, "text": "DataTables are a modern jQuery plugin for adding interactive and advanced controls to HTML tables for our webpage. It is a very simple-to-use plug-in with a variety of options for the developer’s custom changes as per the application need. The plugin’s features include pagination, sorting, searching, and multiple-column ordering." }, { "code": null, "e": 461, "s": 360, "text": "In this article, we will learn to initialize multiple HTML tables using the jQuery DataTables plugin" }, { "code": null, "e": 518, "s": 461, "text": "The pre-compiled files which are needed to implement are" }, { "code": null, "e": 523, "s": 518, "text": "CSS:" }, { "code": null, "e": 588, "s": 523, "text": "https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css" }, { "code": null, "e": 600, "s": 588, "text": "JavaScript:" }, { "code": null, "e": 664, "s": 600, "text": "https: //cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js" }, { "code": null, "e": 856, "s": 664, "text": "Example: Initialization of multiple tables is handled with one line of code by using the table.display selector. Both the tables can be operated together, but they are executed independently." }, { "code": "<!DOCTYPE html><html> <head> <meta content=\"initial-scale=1, maximum-scale=1, user-scalable=0\" name=\"viewport\" /> <meta name=\"viewport\" content=\"width=device-width\" /> <!--Datatable plugin CSS file --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css\" /> <!--jQuery library file --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!--Datatable plugin JS library file --> <script type=\"text/javascript\" src=\"https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js\"> </script></head> <body> <h2> Multiple tables operations using jQuery Datatables </h2> <!--HTML tables with student data--> <table id=\"\" class=\"display\" style=\"width:100%\"> <thead> <tr> <th>StudentID</th> <th>StudentName</th> <th>Age</th> <th>Gender</th> <th>Marks Scored</th> </tr> </thead> <tbody> <tr> <td>ST1</td> <td>Prema</td> <td>35</td> <td>Female</td> <td>320</td> </tr> <tr> <td>ST2</td> <td>Wincy</td> <td>36</td> <td>Female</td> <td>170</td> </tr> <tr> <td>ST3</td> <td>Ashmita</td> <td>41</td> <td>Female</td> <td>860</td> </tr> <tr> <td>ST4</td> <td>Kelina</td> <td>32</td> <td>Female</td> <td>433</td> </tr> <tr> <td>ST5</td> <td>Satvik</td> <td>41</td> <td>male</td> <td>162</td> </tr> <tr> <td>ST6</td> <td>William</td> <td>37</td> <td>Female</td> <td>372</td> </tr> <tr> <td>ST7</td> <td>Chandan</td> <td>31</td> <td>male</td> <td>375</td> </tr> <tr> <td>ST8</td> <td>David</td> <td>45</td> <td>male</td> <td>327</td> </tr> <tr> <td>ST9</td> <td>Harry</td> <td>29</td> <td>male</td> <td>205</td> </tr> <tr> <td>ST10</td> <td>Frost</td> <td>29</td> <td>male</td> <td>300</td> </tr> <tr> <td>ST11</td> <td>Ginny</td> <td>31</td> <td>male</td> <td>560</td> </tr> <tr> <td>ST12</td> <td>Flod</td> <td>45</td> <td>Female</td> <td>342</td> </tr> <tr> <td>ST13</td> <td>Marshy</td> <td>23</td> <td>Female</td> <td>470</td> </tr> <tr> <td>ST13</td> <td>Kennedy</td> <td>43</td> <td>male</td> <td>313</td> </tr> <tr> <td>ST14</td> <td>Fiza</td> <td>31</td> <td>Female</td> <td>750</td> </tr> <tr> <td>ST15</td> <td>Silva</td> <td>34</td> <td>male</td> <td>985</td> </tr> </tbody> </table> <br /> <table id=\"\" class=\"display\" style=\"width:100%\"> <thead> <tr> <th>StudentID</th> <th>StudentName</th> <th>Age</th> <th>Gender</th> <th>Marks Scored</th> </tr> </thead> <tbody> <tr> <td>ST15</td> <td>Varun</td> <td>41</td> <td>male</td> <td>262</td> </tr> <tr> <td>ST16</td> <td>Waheeda</td> <td>47</td> <td>Female</td> <td>373</td> </tr> <tr> <td>ST17</td> <td>Charu</td> <td>31</td> <td>female</td> <td>475</td> </tr> <tr> <td>ST18</td> <td>Dhriti</td> <td>45</td> <td>female</td> <td>227</td> </tr> <tr> <td>ST19</td> <td>Haritha</td> <td>39</td> <td>female</td> <td>295</td> </tr> <tr> <td>ST20</td> <td>Faran</td> <td>39</td> <td>male</td> <td>340</td> </tr> <tr> <td>ST21</td> <td>Gaurav</td> <td>31</td> <td>male</td> <td>562</td> </tr> <tr> <td>ST22</td> <td>Fenny</td> <td>41</td> <td>Female</td> <td>349</td> </tr> <tr> <td>ST23</td> <td>Mamta</td> <td>29</td> <td>Female</td> <td>471</td> </tr> <tr> <td>ST23</td> <td>Kamat</td> <td>44</td> <td>male</td> <td>319</td> </tr> </tbody> </table> <script> /* Initialization of datatables */ $(document).ready(function () { $('table.display').DataTable(); }); </script></body> </html>", "e": 7087, "s": 856, "text": null }, { "code": null, "e": 7095, "s": 7087, "text": "Output:" }, { "code": null, "e": 7185, "s": 7095, "text": "The following output shows that data for both the tables are loaded after initialization." }, { "code": null, "e": 7317, "s": 7185, "text": "The following output shows that both the tables are executed independently showing the “searching” operation for “female” students." }, { "code": null, "e": 7327, "s": 7317, "text": "HTML-Misc" }, { "code": null, "e": 7341, "s": 7327, "text": "jQuery-Plugin" }, { "code": null, "e": 7346, "s": 7341, "text": "HTML" }, { "code": null, "e": 7353, "s": 7346, "text": "JQuery" }, { "code": null, "e": 7370, "s": 7353, "text": "Web Technologies" }, { "code": null, "e": 7375, "s": 7370, "text": "HTML" } ]
Bash program to check if the Number is a Palindrome
14 Jan, 2019 Given a number num, find whether the given number is palindrome or not using Bash Scripting. Examples: Input : 666 Output : Number is palindrome Input : 45667 Output : Number is NOT palindrome ApproachTo find the given number is palindrome just check if the number is same from beginning and the end. Reverse the number to check if the number reversed is equal to the original number or not, if yes than echo Number is palindrome otherwise echo Number is NOT palindrome . num=545 # Storing the remainders=0 # Store number in reverse # orderrev="" # Store original number # in another variabletemp=$num while [ $num -gt 0 ]do # Get Remainder s=$(( $num % 10 )) # Get next digit num=$(( $num / 10 )) # Store previous number and # current digit in reverse rev=$( echo ${rev}${s} ) done if [ $temp -eq $rev ];then echo "Number is palindrome"else echo "Number is NOT palindrome"fi Output: Number is palindrome AnmolAgarwal palindrome Shell Script Linux-Unix palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Jan, 2019" }, { "code": null, "e": 147, "s": 54, "text": "Given a number num, find whether the given number is palindrome or not using Bash Scripting." }, { "code": null, "e": 157, "s": 147, "text": "Examples:" }, { "code": null, "e": 250, "s": 157, "text": "Input : \n666\nOutput :\nNumber is palindrome\n\nInput :\n45667\nOutput :\nNumber is NOT palindrome\n" }, { "code": null, "e": 529, "s": 250, "text": "ApproachTo find the given number is palindrome just check if the number is same from beginning and the end. Reverse the number to check if the number reversed is equal to the original number or not, if yes than echo Number is palindrome otherwise echo Number is NOT palindrome ." }, { "code": "num=545 # Storing the remainders=0 # Store number in reverse # orderrev=\"\" # Store original number # in another variabletemp=$num while [ $num -gt 0 ]do # Get Remainder s=$(( $num % 10 )) # Get next digit num=$(( $num / 10 )) # Store previous number and # current digit in reverse rev=$( echo ${rev}${s} ) done if [ $temp -eq $rev ];then echo \"Number is palindrome\"else echo \"Number is NOT palindrome\"fi", "e": 986, "s": 529, "text": null }, { "code": null, "e": 994, "s": 986, "text": "Output:" }, { "code": null, "e": 1016, "s": 994, "text": "Number is palindrome\n" }, { "code": null, "e": 1029, "s": 1016, "text": "AnmolAgarwal" }, { "code": null, "e": 1040, "s": 1029, "text": "palindrome" }, { "code": null, "e": 1053, "s": 1040, "text": "Shell Script" }, { "code": null, "e": 1064, "s": 1053, "text": "Linux-Unix" }, { "code": null, "e": 1075, "s": 1064, "text": "palindrome" } ]
Puzzle 19 | (Poison and Rat)
12 Aug, 2021 There are 1000 wine bottles. One of the bottles contains poisoned wine. A rat dies after one hour of drinking the poisoned wine. How many minimum rats are needed to figure out which bottle contains poison in hour. Solution: We need to figure out in hour. We need 10 rats to figure out the poisoned bottle. The result is based on binary number system. We get 10 using ⌈ Log21000 ⌉. The idea is to number bottles from 1 to 1000 and write their corresponding binary numbers on the bottle. Each rat is assigned a position in the binary numbers written on bottles. Let us take an example. Rat 1 represents first bit in every bottle, rat 2 represents second bit and so on. If rat numbers 2, 4 and 6 die, then bottle number 42 (Binary 0000101010) is poisoned. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Xw5LR6WRTz4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> priyameena1408 Mathematical Puzzles Mathematical Puzzles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Aug, 2021" }, { "code": null, "e": 267, "s": 52, "text": "There are 1000 wine bottles. One of the bottles contains poisoned wine. A rat dies after one hour of drinking the poisoned wine. How many minimum rats are needed to figure out which bottle contains poison in hour. " }, { "code": null, "e": 435, "s": 267, "text": "Solution: We need to figure out in hour. We need 10 rats to figure out the poisoned bottle. The result is based on binary number system. We get 10 using ⌈ Log21000 ⌉. " }, { "code": null, "e": 808, "s": 435, "text": "The idea is to number bottles from 1 to 1000 and write their corresponding binary numbers on the bottle. Each rat is assigned a position in the binary numbers written on bottles. Let us take an example. Rat 1 represents first bit in every bottle, rat 2 represents second bit and so on. If rat numbers 2, 4 and 6 die, then bottle number 42 (Binary 0000101010) is poisoned. " }, { "code": null, "e": 934, "s": 808, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 1226, "s": 934, "text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Xw5LR6WRTz4\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 1243, "s": 1228, "text": "priyameena1408" }, { "code": null, "e": 1256, "s": 1243, "text": "Mathematical" }, { "code": null, "e": 1264, "s": 1256, "text": "Puzzles" }, { "code": null, "e": 1277, "s": 1264, "text": "Mathematical" }, { "code": null, "e": 1285, "s": 1277, "text": "Puzzles" } ]
Activity Lifecycle in Android with Demo App - GeeksforGeeks
30 Apr, 2021 In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any desktop application. An Android app consists of one or more screens or activities. Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when a new activity starts, the previous one always remains below it. There are four stages of an activity. If an activity is in the foreground of the screen i.e at the top of the stack, then it is said to be active or running. This is usually the activity that the user is currently interacting with.If an activity has lost focus and a non-full-sized or transparent activity has focused on top of your activity. In such a case either another activity has a higher position in multi-window mode or the activity itself is not focusable in the current window mode. Such activity is completely alive.If an activity is completely hidden by another activity, it is stopped or hidden. It still retains all the information, and as its window is hidden thus it will often be killed by the system when memory is needed elsewhere.The system can destroy the activity from memory by either asking it to finish or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state. If an activity is in the foreground of the screen i.e at the top of the stack, then it is said to be active or running. This is usually the activity that the user is currently interacting with. If an activity has lost focus and a non-full-sized or transparent activity has focused on top of your activity. In such a case either another activity has a higher position in multi-window mode or the activity itself is not focusable in the current window mode. Such activity is completely alive. If an activity is completely hidden by another activity, it is stopped or hidden. It still retains all the information, and as its window is hidden thus it will often be killed by the system when memory is needed elsewhere. The system can destroy the activity from memory by either asking it to finish or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state. For each stage, android provides us with a set of 7 methods that have their own significance for each stage in the life cycle. The image shows a path of migration whenever an app switches from one state to another. Detailed introduction on each of the method is stated as follows: It is called when the activity is first created. This is where all the static work is done like creating views, binding data to lists, etc. This method also provides a Bundle containing its previous frozen state, if there was one. Example: Java Kotlin import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Bundle containing previous frozen state setContentView(R.layout.activity_main); // The content view pointing to the id of layout // in the file activity_main.xml Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); }} import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Bundle containing previous frozen state setContentView(R.layout.activity_main) // The content view pointing to the id of layout // in the file activity_main.xml val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() }} It is invoked when the activity is visible to the user. It is followed by onResume() if the activity is invoked from the background. It is also invoked after onCreate() when the activity is first started. Example: Java Kotlin import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Bundle containing previous frozen state setContentView(R.layout.activity_main); // The content view pointing to the id of layout // in the file activity_main.xml Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onStart() { // It will show a message on the screen // then onStart is invoked Toast toast = Toast.makeText(getApplicationContext(), "onStart Called", Toast.LENGTH_LONG).show(); }} import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() } override fun onStart() { super.onStart() // It will show a message on the screen // then onStart is invoked val toast = Toast.makeText(applicationContext, "onStart Called", Toast.LENGTH_LONG).show() }} It is invoked after the activity has been stopped and prior to its starting stage and thus is always followed by onStart() when any activity is revived from background to on-screen. Example: Java Kotlin import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Bundle containing previous frozen state setContentView(R.layout.activity_main); // The content view pointing to the id of layout // in the file activity_main.xml Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onRestart() { // It will show a message on the screen // then onRestart is invoked Toast toast = Toast.makeText(getApplicationContext(), "onRestart Called", Toast.LENGTH_LONG).show(); }} import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() } override fun onRestart() { super.onRestart() // It will show a message on the screen // then onRestart is invoked val toast = Toast.makeText(applicationContext, "onRestart Called", Toast.LENGTH_LONG).show() }} It is invoked when the activity starts interacting with the user. At this point, the activity is at the top of the activity stack, with a user interacting with it. Always followed by onPause() when the activity goes into the background or is closed by the user. Example: Java Kotlin import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; import com.example.share.R; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onResume() { // It will show a message on the screen // then onResume is invoked Toast toast = Toast.makeText(getApplicationContext(), "onResume Called", Toast.LENGTH_LONG).show(); }} import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() } override fun onResume() { super.onResume() // It will show a message on the screen // then onResume is invoked val toast = Toast.makeText(applicationContext, "onResume Called", Toast.LENGTH_LONG).show() }} It is invoked when an activity is going into the background but has not yet been killed. It is a counterpart to onResume(). When an activity is launched in front of another activity, this callback will be invoked on the top activity (currently on screen). The activity, under the active activity, will not be created until the active activity’s onPause() returns, so it is recommended that heavy processing should not be done in this part. Example: Java Kotlin import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onPause() { // It will show a message on the screen // then onPause is invoked Toast toast = Toast.makeText(getApplicationContext(), "onPause Called", Toast.LENGTH_LONG).show(); }} import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() } override fun onPause() { super.onPause() // It will show a message on the screen // then onPause is invoked val toast = Toast.makeText(applicationContext, "onPause Called", Toast.LENGTH_LONG).show() }} It is invoked when the activity is not visible to the user. It is followed by onRestart() when the activity is revoked from the background, followed by onDestroy() when the activity is closed or finished, and nothing when the activity remains on the background only. Note that this method may never be called, in low memory situations where the system does not have enough memory to keep the activity’s process running after its onPause() method is called. Example: Java Kotlin import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onStop() { // It will show a message on the screen // then onStop is invoked Toast toast = Toast.makeText(getApplicationContext(), "onStop Called", Toast.LENGTH_LONG).show(); }} import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() } override fun onStop() { super.onStop() // It will show a message on the screen // then onStop is invoked val toast = Toast.makeText(applicationContext, "onStop Called", Toast.LENGTH_LONG).show() }} The final call received before the activity is destroyed. This can happen either because the activity is finishing (when finish() is invoked) or because the system is temporarily destroying this instance of the activity to save space. To distinguish between these scenarios, check it with isFinishing() method. Example: Java Kotlin import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onDestroy() { // It will show a message on the screen // then onDestroy is invoked Toast toast = Toast.makeText(getApplicationContext(), "onDestroy Called", Toast.LENGTH_LONG).show(); }} import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() } override fun onDestroy() { super.onDestroy() // It will show a message on the screen // then onDestroy is invoked val toast = Toast.makeText(applicationContext, "onDestroy Called", Toast.LENGTH_LONG).show() }} Java Kotlin import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onStart() { super.onStart(); Toast toast = Toast.makeText(getApplicationContext(), "onStart Called", Toast.LENGTH_LONG).show(); } @Override protected void onRestart() { super.onRestart(); Toast toast = Toast.makeText(getApplicationContext(), "onRestart Called", Toast.LENGTH_LONG).show(); } protected void onPause() { super.onPause(); Toast toast = Toast.makeText(getApplicationContext(), "onPause Called", Toast.LENGTH_LONG).show(); } protected void onResume() { super.onResume(); Toast toast = Toast.makeText(getApplicationContext(), "onResume Called", Toast.LENGTH_LONG).show(); } protected void onStop() { super.onStop(); Toast toast = Toast.makeText(getApplicationContext(), "onStop Called", Toast.LENGTH_LONG).show(); } protected void onDestroy() { super.onDestroy(); Toast toast = Toast.makeText(getApplicationContext(), "onDestroy Called", Toast.LENGTH_LONG).show(); }} import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() } override fun onStart() { super.onStart() val toast = Toast.makeText(applicationContext, "onStart Called", Toast.LENGTH_LONG).show() } override fun onRestart() { super.onRestart() val toast = Toast.makeText(applicationContext, "onRestart Called", Toast.LENGTH_LONG).show() } override fun onPause() { super.onPause() val toast = Toast.makeText(applicationContext, "onPause Called", Toast.LENGTH_LONG).show() } override fun onResume() { super.onResume() val toast = Toast.makeText(applicationContext, "onResume Called", Toast.LENGTH_LONG).show() } override fun onStop() { super.onStop() val toast = Toast.makeText(applicationContext, "onStop Called", Toast.LENGTH_LONG).show() } override fun onDestroy() { super.onDestroy() val toast = Toast.makeText(applicationContext, "onDestroy Called", Toast.LENGTH_LONG).show() }} Output: AmiyaRanjanRout aashaypawar Picked Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin 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": 24600, "s": 24572, "text": "\n30 Apr, 2021" }, { "code": null, "e": 25004, "s": 24600, "text": "In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any desktop application. An Android app consists of one or more screens or activities. Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when a new activity starts, the previous one always remains below it. There are four stages of an activity. " }, { "code": null, "e": 25933, "s": 25004, "text": "If an activity is in the foreground of the screen i.e at the top of the stack, then it is said to be active or running. This is usually the activity that the user is currently interacting with.If an activity has lost focus and a non-full-sized or transparent activity has focused on top of your activity. In such a case either another activity has a higher position in multi-window mode or the activity itself is not focusable in the current window mode. Such activity is completely alive.If an activity is completely hidden by another activity, it is stopped or hidden. It still retains all the information, and as its window is hidden thus it will often be killed by the system when memory is needed elsewhere.The system can destroy the activity from memory by either asking it to finish or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state." }, { "code": null, "e": 26127, "s": 25933, "text": "If an activity is in the foreground of the screen i.e at the top of the stack, then it is said to be active or running. This is usually the activity that the user is currently interacting with." }, { "code": null, "e": 26424, "s": 26127, "text": "If an activity has lost focus and a non-full-sized or transparent activity has focused on top of your activity. In such a case either another activity has a higher position in multi-window mode or the activity itself is not focusable in the current window mode. Such activity is completely alive." }, { "code": null, "e": 26648, "s": 26424, "text": "If an activity is completely hidden by another activity, it is stopped or hidden. It still retains all the information, and as its window is hidden thus it will often be killed by the system when memory is needed elsewhere." }, { "code": null, "e": 26865, "s": 26648, "text": "The system can destroy the activity from memory by either asking it to finish or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state." }, { "code": null, "e": 27080, "s": 26865, "text": "For each stage, android provides us with a set of 7 methods that have their own significance for each stage in the life cycle. The image shows a path of migration whenever an app switches from one state to another." }, { "code": null, "e": 27147, "s": 27080, "text": "Detailed introduction on each of the method is stated as follows: " }, { "code": null, "e": 27379, "s": 27147, "text": "It is called when the activity is first created. This is where all the static work is done like creating views, binding data to lists, etc. This method also provides a Bundle containing its previous frozen state, if there was one. " }, { "code": null, "e": 27389, "s": 27379, "text": "Example: " }, { "code": null, "e": 27394, "s": 27389, "text": "Java" }, { "code": null, "e": 27401, "s": 27394, "text": "Kotlin" }, { "code": "import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Bundle containing previous frozen state setContentView(R.layout.activity_main); // The content view pointing to the id of layout // in the file activity_main.xml Toast toast = Toast.makeText(getApplicationContext(), \"onCreate Called\", Toast.LENGTH_LONG).show(); }}", "e": 27993, "s": 27401, "text": null }, { "code": "import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Bundle containing previous frozen state setContentView(R.layout.activity_main) // The content view pointing to the id of layout // in the file activity_main.xml val toast = Toast.makeText(applicationContext, \"onCreate Called\", Toast.LENGTH_LONG).show() }}", "e": 28549, "s": 27993, "text": null }, { "code": null, "e": 28756, "s": 28549, "text": "It is invoked when the activity is visible to the user. It is followed by onResume() if the activity is invoked from the background. It is also invoked after onCreate() when the activity is first started. " }, { "code": null, "e": 28767, "s": 28756, "text": "Example: " }, { "code": null, "e": 28772, "s": 28767, "text": "Java" }, { "code": null, "e": 28779, "s": 28772, "text": "Kotlin" }, { "code": "import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Bundle containing previous frozen state setContentView(R.layout.activity_main); // The content view pointing to the id of layout // in the file activity_main.xml Toast toast = Toast.makeText(getApplicationContext(), \"onCreate Called\", Toast.LENGTH_LONG).show(); } protected void onStart() { // It will show a message on the screen // then onStart is invoked Toast toast = Toast.makeText(getApplicationContext(), \"onStart Called\", Toast.LENGTH_LONG).show(); }}", "e": 29597, "s": 28779, "text": null }, { "code": "import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, \"onCreate Called\", Toast.LENGTH_LONG).show() } override fun onStart() { super.onStart() // It will show a message on the screen // then onStart is invoked val toast = Toast.makeText(applicationContext, \"onStart Called\", Toast.LENGTH_LONG).show() }}", "e": 30231, "s": 29597, "text": null }, { "code": null, "e": 30415, "s": 30231, "text": "It is invoked after the activity has been stopped and prior to its starting stage and thus is always followed by onStart() when any activity is revived from background to on-screen. " }, { "code": null, "e": 30426, "s": 30415, "text": "Example: " }, { "code": null, "e": 30431, "s": 30426, "text": "Java" }, { "code": null, "e": 30438, "s": 30431, "text": "Kotlin" }, { "code": "import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Bundle containing previous frozen state setContentView(R.layout.activity_main); // The content view pointing to the id of layout // in the file activity_main.xml Toast toast = Toast.makeText(getApplicationContext(), \"onCreate Called\", Toast.LENGTH_LONG).show(); } protected void onRestart() { // It will show a message on the screen // then onRestart is invoked Toast toast = Toast.makeText(getApplicationContext(), \"onRestart Called\", Toast.LENGTH_LONG).show(); }}", "e": 31260, "s": 30438, "text": null }, { "code": "import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, \"onCreate Called\", Toast.LENGTH_LONG).show() } override fun onRestart() { super.onRestart() // It will show a message on the screen // then onRestart is invoked val toast = Toast.makeText(applicationContext, \"onRestart Called\", Toast.LENGTH_LONG).show() }}", "e": 31901, "s": 31260, "text": null }, { "code": null, "e": 32164, "s": 31901, "text": "It is invoked when the activity starts interacting with the user. At this point, the activity is at the top of the activity stack, with a user interacting with it. Always followed by onPause() when the activity goes into the background or is closed by the user. " }, { "code": null, "e": 32175, "s": 32164, "text": "Example: " }, { "code": null, "e": 32180, "s": 32175, "text": "Java" }, { "code": null, "e": 32187, "s": 32180, "text": "Kotlin" }, { "code": "import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; import com.example.share.R; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), \"onCreate Called\", Toast.LENGTH_LONG).show(); } protected void onResume() { // It will show a message on the screen // then onResume is invoked Toast toast = Toast.makeText(getApplicationContext(), \"onResume Called\", Toast.LENGTH_LONG).show(); }}", "e": 33027, "s": 32187, "text": null }, { "code": "import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, \"onCreate Called\", Toast.LENGTH_LONG).show() } override fun onResume() { super.onResume() // It will show a message on the screen // then onResume is invoked val toast = Toast.makeText(applicationContext, \"onResume Called\", Toast.LENGTH_LONG).show() }}", "e": 33664, "s": 33027, "text": null }, { "code": null, "e": 34105, "s": 33664, "text": "It is invoked when an activity is going into the background but has not yet been killed. It is a counterpart to onResume(). When an activity is launched in front of another activity, this callback will be invoked on the top activity (currently on screen). The activity, under the active activity, will not be created until the active activity’s onPause() returns, so it is recommended that heavy processing should not be done in this part. " }, { "code": null, "e": 34116, "s": 34105, "text": "Example: " }, { "code": null, "e": 34121, "s": 34116, "text": "Java" }, { "code": null, "e": 34128, "s": 34121, "text": "Kotlin" }, { "code": "import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), \"onCreate Called\", Toast.LENGTH_LONG).show(); } protected void onPause() { // It will show a message on the screen // then onPause is invoked Toast toast = Toast.makeText(getApplicationContext(), \"onPause Called\", Toast.LENGTH_LONG).show(); }}", "e": 34929, "s": 34128, "text": null }, { "code": "import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, \"onCreate Called\", Toast.LENGTH_LONG).show() } override fun onPause() { super.onPause() // It will show a message on the screen // then onPause is invoked val toast = Toast.makeText(applicationContext, \"onPause Called\", Toast.LENGTH_LONG).show() }}", "e": 35562, "s": 34929, "text": null }, { "code": null, "e": 36021, "s": 35562, "text": "It is invoked when the activity is not visible to the user. It is followed by onRestart() when the activity is revoked from the background, followed by onDestroy() when the activity is closed or finished, and nothing when the activity remains on the background only. Note that this method may never be called, in low memory situations where the system does not have enough memory to keep the activity’s process running after its onPause() method is called. " }, { "code": null, "e": 36032, "s": 36021, "text": "Example: " }, { "code": null, "e": 36037, "s": 36032, "text": "Java" }, { "code": null, "e": 36044, "s": 36037, "text": "Kotlin" }, { "code": "import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), \"onCreate Called\", Toast.LENGTH_LONG).show(); } protected void onStop() { // It will show a message on the screen // then onStop is invoked Toast toast = Toast.makeText(getApplicationContext(), \"onStop Called\", Toast.LENGTH_LONG).show(); }}", "e": 36842, "s": 36044, "text": null }, { "code": "import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, \"onCreate Called\", Toast.LENGTH_LONG).show() } override fun onStop() { super.onStop() // It will show a message on the screen // then onStop is invoked val toast = Toast.makeText(applicationContext, \"onStop Called\", Toast.LENGTH_LONG).show() }}", "e": 37471, "s": 36842, "text": null }, { "code": null, "e": 37784, "s": 37471, "text": "The final call received before the activity is destroyed. This can happen either because the activity is finishing (when finish() is invoked) or because the system is temporarily destroying this instance of the activity to save space. To distinguish between these scenarios, check it with isFinishing() method. " }, { "code": null, "e": 37793, "s": 37784, "text": "Example:" }, { "code": null, "e": 37798, "s": 37793, "text": "Java" }, { "code": null, "e": 37805, "s": 37798, "text": "Kotlin" }, { "code": "import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), \"onCreate Called\", Toast.LENGTH_LONG).show(); } protected void onDestroy() { // It will show a message on the screen // then onDestroy is invoked Toast toast = Toast.makeText(getApplicationContext(), \"onDestroy Called\", Toast.LENGTH_LONG).show(); }}", "e": 38620, "s": 37805, "text": null }, { "code": "import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, \"onCreate Called\", Toast.LENGTH_LONG).show() } override fun onDestroy() { super.onDestroy() // It will show a message on the screen // then onDestroy is invoked val toast = Toast.makeText(applicationContext, \"onDestroy Called\", Toast.LENGTH_LONG).show() }}", "e": 39261, "s": 38620, "text": null }, { "code": null, "e": 39266, "s": 39261, "text": "Java" }, { "code": null, "e": 39273, "s": 39266, "text": "Kotlin" }, { "code": "import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), \"onCreate Called\", Toast.LENGTH_LONG).show(); } protected void onStart() { super.onStart(); Toast toast = Toast.makeText(getApplicationContext(), \"onStart Called\", Toast.LENGTH_LONG).show(); } @Override protected void onRestart() { super.onRestart(); Toast toast = Toast.makeText(getApplicationContext(), \"onRestart Called\", Toast.LENGTH_LONG).show(); } protected void onPause() { super.onPause(); Toast toast = Toast.makeText(getApplicationContext(), \"onPause Called\", Toast.LENGTH_LONG).show(); } protected void onResume() { super.onResume(); Toast toast = Toast.makeText(getApplicationContext(), \"onResume Called\", Toast.LENGTH_LONG).show(); } protected void onStop() { super.onStop(); Toast toast = Toast.makeText(getApplicationContext(), \"onStop Called\", Toast.LENGTH_LONG).show(); } protected void onDestroy() { super.onDestroy(); Toast toast = Toast.makeText(getApplicationContext(), \"onDestroy Called\", Toast.LENGTH_LONG).show(); }}", "e": 40723, "s": 39273, "text": null }, { "code": "import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, \"onCreate Called\", Toast.LENGTH_LONG).show() } override fun onStart() { super.onStart() val toast = Toast.makeText(applicationContext, \"onStart Called\", Toast.LENGTH_LONG).show() } override fun onRestart() { super.onRestart() val toast = Toast.makeText(applicationContext, \"onRestart Called\", Toast.LENGTH_LONG).show() } override fun onPause() { super.onPause() val toast = Toast.makeText(applicationContext, \"onPause Called\", Toast.LENGTH_LONG).show() } override fun onResume() { super.onResume() val toast = Toast.makeText(applicationContext, \"onResume Called\", Toast.LENGTH_LONG).show() } override fun onStop() { super.onStop() val toast = Toast.makeText(applicationContext, \"onStop Called\", Toast.LENGTH_LONG).show() } override fun onDestroy() { super.onDestroy() val toast = Toast.makeText(applicationContext, \"onDestroy Called\", Toast.LENGTH_LONG).show() }}", "e": 42062, "s": 40723, "text": null }, { "code": null, "e": 42071, "s": 42062, "text": "Output: " }, { "code": null, "e": 42087, "s": 42071, "text": "AmiyaRanjanRout" }, { "code": null, "e": 42099, "s": 42087, "text": "aashaypawar" }, { "code": null, "e": 42106, "s": 42099, "text": "Picked" }, { "code": null, "e": 42114, "s": 42106, "text": "Android" }, { "code": null, "e": 42119, "s": 42114, "text": "Java" }, { "code": null, "e": 42124, "s": 42119, "text": "Java" }, { "code": null, "e": 42132, "s": 42124, "text": "Android" }, { "code": null, "e": 42230, "s": 42132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42288, "s": 42230, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 42331, "s": 42288, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 42364, "s": 42331, "text": "Services in Android with Example" }, { "code": null, "e": 42406, "s": 42364, "text": "Content Providers in Android with Example" }, { "code": null, "e": 42437, "s": 42406, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 42452, "s": 42437, "text": "Arrays in Java" }, { "code": null, "e": 42496, "s": 42452, "text": "Split() String method in Java with examples" }, { "code": null, "e": 42518, "s": 42496, "text": "For-each loop in Java" }, { "code": null, "e": 42554, "s": 42518, "text": "Arrays.sort() in Java with examples" } ]
QlikView - Dashboard
A Dashboard is a powerful feature to display values from many fields simultaneously. QlikeView's feature of data association in memory can display the dynamic values in all the sheet objects. Let us consider the following input data, which represents the sales figure of different product lines and product categories. Product_Line,Product_category,Value Sporting Goods,Outdoor Recreation,5642 Food, Beverages & Tobacco,2514 Apparel & Accessories,Clothing,2365 Apparel & Accessories,Costumes & Accessories,4487 Sporting Goods,Athletics,812 Health & Beauty,Personal Care,6912 Arts & Entertainment,Hobbies & Creative Arts,5201 Arts & Entertainment,Paintings,8451 Arts & Entertainment,Musical Instruments,1245 Hardware,Tool Accessories,456 Home & Garden,Bathroom Accessories,241 Food,Drinks,1247 Home & Garden,Lawn & Garden,5462 Office Supplies,Presentation Supplies,577 Hardware,Blocks,548 Baby & Toddler,Diapering,1247 Baby & Toddler,Toys,257 Home & Garden,Pipes,1241 Office Supplies,Display Board,2177 The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data. Edit the load script to add the following code. Click "OK" and press "Control+R" to load the data into the QlikView's memory. LOAD Product_Line, Product_category, Value FROM [C:\Qlikview\data\product_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); We choose the fields from the above input data as matrices to be displayed in the dashboard. For this, we follow the steps in the menu Layout → Select Fields. In the next screen, choose the available fields to be displayed in the dashboard. Click "OK". The following screen appears displaying all the fields NNow we add a chart to the dashboard by right-clicking anywhere in the sheet and choosing New Sheet Object → Chart. Let us choose the chart type as a bar chart to display the sales values for various product Lines. Let us select the Product Line as the Chart Dimension. The expression to display the sales value for the Product Line dimension is written in the expression editor. Given below is the dashboard displayed after finishing the above steps. The values in the above Dashboard can be selected for filtering specific products and the chart changes accordingly. In addition, the associated values are highlighted. 70 Lectures 5 hours Arthur Fong Print Add Notes Bookmark this page
[ { "code": null, "e": 3112, "s": 2920, "text": "A Dashboard is a powerful feature to display values from many fields simultaneously. QlikeView's feature of data association in memory can display the dynamic values in all the sheet objects." }, { "code": null, "e": 3239, "s": 3112, "text": "Let us consider the following input data, which represents the sales figure of different product lines and product categories." }, { "code": null, "e": 3923, "s": 3239, "text": "Product_Line,Product_category,Value\nSporting Goods,Outdoor Recreation,5642\nFood, Beverages & Tobacco,2514\nApparel & Accessories,Clothing,2365\nApparel & Accessories,Costumes & Accessories,4487\nSporting Goods,Athletics,812\nHealth & Beauty,Personal Care,6912\nArts & Entertainment,Hobbies & Creative Arts,5201\nArts & Entertainment,Paintings,8451\nArts & Entertainment,Musical Instruments,1245\nHardware,Tool Accessories,456\nHome & Garden,Bathroom Accessories,241\nFood,Drinks,1247\nHome & Garden,Lawn & Garden,5462\nOffice Supplies,Presentation Supplies,577\nHardware,Blocks,548\nBaby & Toddler,Diapering,1247\nBaby & Toddler,Toys,257\nHome & Garden,Pipes,1241\nOffice Supplies,Display Board,2177\n" }, { "code": null, "e": 4297, "s": 3923, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the \"Table Files\" option from the \"Data from Files\" tab and browse for the file containing the above data. Edit the load script to add the following code. Click \"OK\" and press \"Control+R\" to load the data into the QlikView's memory." }, { "code": null, "e": 4459, "s": 4297, "text": "LOAD Product_Line, \n Product_category, \n Value\nFROM\n[C:\\Qlikview\\data\\product_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 4618, "s": 4459, "text": "We choose the fields from the above input data as matrices to be displayed in the dashboard. For this, we follow the steps in the menu Layout → Select Fields." }, { "code": null, "e": 4712, "s": 4618, "text": "In the next screen, choose the available fields to be displayed in the dashboard. Click \"OK\"." }, { "code": null, "e": 4767, "s": 4712, "text": "The following screen appears displaying all the fields" }, { "code": null, "e": 4883, "s": 4767, "text": "NNow we add a chart to the dashboard by right-clicking anywhere in the sheet and choosing New Sheet Object → Chart." }, { "code": null, "e": 4982, "s": 4883, "text": "Let us choose the chart type as a bar chart to display the sales values for various product Lines." }, { "code": null, "e": 5037, "s": 4982, "text": "Let us select the Product Line as the Chart Dimension." }, { "code": null, "e": 5147, "s": 5037, "text": "The expression to display the sales value for the Product Line dimension is written in the expression editor." }, { "code": null, "e": 5219, "s": 5147, "text": "Given below is the dashboard displayed after finishing the above steps." }, { "code": null, "e": 5388, "s": 5219, "text": "The values in the above Dashboard can be selected for filtering specific products and the chart changes accordingly. In addition, the associated values are highlighted." }, { "code": null, "e": 5421, "s": 5388, "text": "\n 70 Lectures \n 5 hours \n" }, { "code": null, "e": 5434, "s": 5421, "text": " Arthur Fong" }, { "code": null, "e": 5441, "s": 5434, "text": " Print" }, { "code": null, "e": 5452, "s": 5441, "text": " Add Notes" } ]
Create Word Cloud using Python
In this problem, there is a file with some texts. We have to create Word Clouds from those texts and one masking image. The program will store the word cloud image as png format. To implement this problem, we need to use some libraries of python. The libraries are matplotlib, wordcloud, numpy, tkinter and PIL. To install these libraries, we need to follow these commands − $ sudo pip3 install matplotlib $ sudo pip3 install wordcloud $ sudo apt-get install python3-tk After adding these libraries, we can write the python code to perform the task. Step 1: Read the data from the file and store it into ‘dataset’. Step 2: Create pixel array from the mask image. Step 3: Create the word cloud from the dataset. Set the background color, mask, and stop-words. Step 4: Store the final image into the disk. Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages. Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages. Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL). Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress. Another input is the mask image (cloud.png). The final Result is on the right side. import matplotlib.pyplot as pPlot from wordcloud import WordCloud, STOPWORDS import numpy as npy from PIL import Image dataset = open("sampleWords.txt", "r").read() defcreate_word_cloud(string): maskArray = npy.array(Image.open("cloud.png")) cloud = WordCloud(background_color = "white", max_words = 200, mask = maskArray, stopwords = set(STOPWORDS)) cloud.generate(string) cloud.to_file("wordCloud.png") dataset = dataset.lower() create_word_cloud(dataset)
[ { "code": null, "e": 1241, "s": 1062, "text": "In this problem, there is a file with some texts. We have to create Word Clouds from those texts and one masking image. The program will store the word cloud image as png format." }, { "code": null, "e": 1374, "s": 1241, "text": "To implement this problem, we need to use some libraries of python. The libraries are matplotlib, wordcloud, numpy, tkinter and PIL." }, { "code": null, "e": 1437, "s": 1374, "text": "To install these libraries, we need to follow these commands −" }, { "code": null, "e": 1533, "s": 1437, "text": "$ sudo pip3 install matplotlib\n$ sudo pip3 install wordcloud\n$ sudo apt-get install python3-tk\n" }, { "code": null, "e": 1613, "s": 1533, "text": "After adding these libraries, we can write the python code to perform the task." }, { "code": null, "e": 1872, "s": 1613, "text": "Step 1: Read the data from the file and store it into ‘dataset’. \nStep 2: Create pixel array from the mask image. \nStep 3: Create the word cloud from the dataset. Set the background color, mask, and stop-words. \nStep 4: Store the final image into the disk. \n" }, { "code": null, "e": 2146, "s": 1872, "text": "Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages." }, { "code": null, "e": 2319, "s": 2146, "text": "Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands." }, { "code": null, "e": 2464, "s": 2319, "text": "Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages." }, { "code": null, "e": 2578, "s": 2464, "text": "Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL)." }, { "code": null, "e": 2726, "s": 2578, "text": "Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress." }, { "code": null, "e": 2810, "s": 2726, "text": "Another input is the mask image (cloud.png). The final Result is on the right side." }, { "code": null, "e": 3280, "s": 2810, "text": "import matplotlib.pyplot as pPlot\nfrom wordcloud import WordCloud, STOPWORDS\nimport numpy as npy\nfrom PIL import Image\ndataset = open(\"sampleWords.txt\", \"r\").read()\ndefcreate_word_cloud(string):\n maskArray = npy.array(Image.open(\"cloud.png\"))\n cloud = WordCloud(background_color = \"white\", max_words = 200, mask = maskArray, stopwords = set(STOPWORDS))\n cloud.generate(string)\n cloud.to_file(\"wordCloud.png\")\ndataset = dataset.lower()\ncreate_word_cloud(dataset)" } ]
Decode the string | Practice | GeeksforGeeks
An encoded string (s) is given, the task is to decode it. The pattern in which the strings were encoded were as follows original string: abbbababbbababbbab encoded string : 3[a3[b]1[ab]] Example 1: Input: s = 1[b] Output: b Explaination: 'b' is present only one time. Example 2: Input: s = 3[b2[ca]] Output: bcacabcacabcaca Explaination: 2[ca] means 'ca' is repeated twice which is 'caca' which concatenated with 'b' becomes 'bcaca'. This string repeated thrice becomes the output. Your Task: You do not need to read input or print annything. Your task is to complete the function decodedString() which takes s as input parameter and returns the decoded string. Expected Time Complexity: O(|s|) Expected Auxiliary Space: O(|s|) Constraints: 1 ≤ |s| ≤ 30 0 jainsakshi09014 days ago Not an easy one 0 danish_nitdgp1 week ago C++ O(n) Solution string decodedString(string s){ // code here stack<char> st; for(int i =0;i<s.length();i++){ if(s[i]!=']') st.push(s[i]); else { string temp; while(!st.empty() && st.top()!='['){ temp = st.top() + temp; st.pop(); } st.pop(); string num; while(!st.empty() && isdigit(st.top())){ num = st.top() + num; st.pop(); } int number = stoi(num); string repeat; while(number--){ repeat = repeat + temp; } for(char c : repeat) st.push(c); } } string res; while(!st.empty()){ res = st.top() + res; st.pop(); } return res; } 0 umeshkaushik6103 weeks ago RECURSIVE SIMPLE APPROACH | C++ class Solution{public: int i=0; string decodedString(string s){ int times=0; string res=""; // string s = s; while(i<s.size()){ if(isdigit(s[i])){ int ch = s[i]-'0'; while(i+1 < s.size() and isdigit(s[i+1])){ ch = (ch*10) + (s[++i]-'0'); } // cout<<ch<<" "; // cout<<endl; times = ch; } else if(s[i] == '['){ i++; auto tmp = decodedString(s); while(times--) res+=tmp; } else if(s[i] == ']') break; else{ res += s[i]; } i++; } return res; }}; 0 chauhangaurav97214 weeks ago class Solution{ public: string decodedString(string s){ stack<string>stk; for(int i = 0; i < s.size(); i++){ if(s[i]==']'){ string temp = ""; while(stk.top()!="["){ temp = temp + stk.top(); stk.pop(); } stk.pop(); string count = ""; while(stk.size() && isdigit(stk.top()[0])){ count = count + stk.top(); stk.pop(); } reverse(count.begin(), count.end()); int cnt = stoi(count); string cur = ""; while(cnt--) cur += temp; stk.push(cur); }else{ stk.push(string(1, s[i])); } } string ans = stk.top(); reverse(ans.begin(), ans.end()); return ans; } }; +11 geminicode2 months ago THIS IS NOT EASY !!!!!!!! 0 sachinkartik1663 months ago class Solution{ String decodedString(String s){ Stack<String> st=new Stack<>(); String ans=""; for(int i=0;i<s.length();i++){ if(s.charAt(i)==']'){ String pele=st.pop(); String maker=""; while(!pele.equals("[")){ maker=pele+maker; pele=st.pop(); } pele=st.pop(); String up=""; for(int j=0;j<Integer.parseInt(pele);j++){ up=maker+up; } st.push(up); }else{ try{ String pp=st.peek(); if(isNumeric(String.valueOf(s.charAt(i)))){ if(isNumeric(pp)){ while(isNumeric(pp)){ st.pop(); pp=pp+String.valueOf(s.charAt(i)); if(!st.isEmpty()){ pp=st.peek(); }else{ break; } } st.push(pp); }else{ st.push(String.valueOf(s.charAt(i))); } }else{ st.push(String.valueOf(s.charAt(i))); } }catch(Exception e){ st.push(String.valueOf(s.charAt(i))); } } } return st.pop(); } public boolean isNumeric(String str) { try { Integer.parseInt(str); return true; } catch(NumberFormatException e){ return false; } } } +1 suchigiri134 months ago class Solution{ static String decodedString(String s){ Stack<Character> stack = new Stack<>(); int i = s.length() - 1; String ans = ""; while(i >= 0){ String temp = ""; while(s.charAt(i) != '['){ stack.push(s.charAt(i)); i--; }if(s.charAt(i--) == '[') { while (stack.peek() != ']') { temp += stack.pop(); // System.out.println(temp); } } stack.pop(); if(!stack.isEmpty() && i >= 0){ temp = temp.repeat(Character.getNumericValue(s.charAt(i))); ans = temp + ans; i--; } else if(stack.isEmpty() && i >= 0) { if (Character.isDigit(s.charAt(i))) { ans = temp + ans; ans = ans.repeat(Character.getNumericValue(s.charAt(i))); i--; } } } return ans; } } Can anyone explain to me why it is giving run time error!! +5 lovilakheraa024 months ago EASY TO UNDERSTAND SOLUTION class Solution{ public: string decodedString(string s){ // code here int currNo=0; string currString=""; int prevNo; string prevString; stack<string>stringstack; stack<int>numstack; for(int i=0;i<s.size();i++) { if(isdigit(s[i])) currNo = currNo*10 + (s[i]-'0'); if(isalpha(s[i])) currString += s[i]; if(s[i] == '[') { stringstack.push(currString); numstack.push(currNo); currNo=0; currString=""; } if(s[i] == ']') { prevNo = numstack.top(); numstack.pop(); prevString = stringstack.top(); stringstack.pop(); while(prevNo--) { prevString += currString; } currString = prevString; } } return currString; } +1 ankitkumar734ac4 months ago class Solution{ static String decodedString(String s){ if(s == "")return ""; String sol = new String(); int repeat = 1; for(int i =0;i<s.length();++i) { if(Character.isDigit(s.charAt(i))) { String temp = ""; int k = i; while(Character.isDigit(s.charAt(k))) { temp+=s.charAt(k); k++; } repeat = Integer.parseInt(temp); i = k-1; } else if(s.charAt(i) =='[') { Stack<Character> st = new Stack<>(); st.push('['); int k = i+1; while(!st.isEmpty()) { if(s.charAt(k) == ']') { st.pop(); k++; } else if(s.charAt(k) =='[') { st.push('['); k++; } else k++; } String inside_bracket = decodedString(s.substring(i+1,k-1)); i = k-1; for(int j =0;j<repeat;++j) { sol+=inside_bracket; } } else { sol+=s.charAt(i); } } return sol; } } +1 mmodi01014 months ago string decodedString(string s){ // code here string num = ""; string ans=""; int n; string temp=""; string temp2=""; stack<char> st; int p = 0; while(p<s.size()) { if(s[p]==']') { while(st.top() != '[') { temp=st.top()+temp; st.pop(); } st.pop(); while(isdigit(st.top())) { num=st.top()+num; st.pop(); if(st.empty()){ break; } } n=stoi(num); for(int i=1;i<=n;i++) { temp2=temp2+temp; } if(st.empty()) { ans=temp2; break; } for(int i=0;i<temp2.size();i++) { st.push(temp2[i]); } temp=""; temp2=""; num=""; } else { st.push(s[p]); } p++; } return ans; } Time : 0.0s 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": 426, "s": 238, "text": "An encoded string (s) is given, the task is to decode it. The pattern in which the strings were encoded were as follows\noriginal string: abbbababbbababbbab \nencoded string : 3[a3[b]1[ab]]" }, { "code": null, "e": 437, "s": 426, "text": "Example 1:" }, { "code": null, "e": 507, "s": 437, "text": "Input: s = 1[b]\nOutput: b\nExplaination: 'b' is present only one time." }, { "code": null, "e": 518, "s": 507, "text": "Example 2:" }, { "code": null, "e": 724, "s": 518, "text": "Input: s = 3[b2[ca]]\nOutput: bcacabcacabcaca\nExplaination: 2[ca] means 'ca' is repeated \ntwice which is 'caca' which concatenated with \n'b' becomes 'bcaca'. This string repeated \nthrice becomes the output." }, { "code": null, "e": 904, "s": 724, "text": "Your Task:\nYou do not need to read input or print annything. Your task is to complete the function decodedString() which takes s as input parameter and returns the decoded string." }, { "code": null, "e": 970, "s": 904, "text": "Expected Time Complexity: O(|s|)\nExpected Auxiliary Space: O(|s|)" }, { "code": null, "e": 997, "s": 970, "text": "Constraints:\n1 ≤ |s| ≤ 30 " }, { "code": null, "e": 999, "s": 997, "text": "0" }, { "code": null, "e": 1024, "s": 999, "text": "jainsakshi09014 days ago" }, { "code": null, "e": 1041, "s": 1024, "text": "Not an easy one " }, { "code": null, "e": 1043, "s": 1041, "text": "0" }, { "code": null, "e": 1067, "s": 1043, "text": "danish_nitdgp1 week ago" }, { "code": null, "e": 1961, "s": 1067, "text": "C++ O(n) Solution string decodedString(string s){ // code here stack<char> st; for(int i =0;i<s.length();i++){ if(s[i]!=']') st.push(s[i]); else { string temp; while(!st.empty() && st.top()!='['){ temp = st.top() + temp; st.pop(); } st.pop(); string num; while(!st.empty() && isdigit(st.top())){ num = st.top() + num; st.pop(); } int number = stoi(num); string repeat; while(number--){ repeat = repeat + temp; } for(char c : repeat) st.push(c); } } string res; while(!st.empty()){ res = st.top() + res; st.pop(); } return res; }" }, { "code": null, "e": 1963, "s": 1961, "text": "0" }, { "code": null, "e": 1990, "s": 1963, "text": "umeshkaushik6103 weeks ago" }, { "code": null, "e": 2022, "s": 1990, "text": "RECURSIVE SIMPLE APPROACH | C++" }, { "code": null, "e": 2735, "s": 2022, "text": "class Solution{public: int i=0; string decodedString(string s){ int times=0; string res=\"\"; // string s = s; while(i<s.size()){ if(isdigit(s[i])){ int ch = s[i]-'0'; while(i+1 < s.size() and isdigit(s[i+1])){ ch = (ch*10) + (s[++i]-'0'); } // cout<<ch<<\" \"; // cout<<endl; times = ch; } else if(s[i] == '['){ i++; auto tmp = decodedString(s); while(times--) res+=tmp; } else if(s[i] == ']') break; else{ res += s[i]; } i++; } return res; }};" }, { "code": null, "e": 2737, "s": 2735, "text": "0" }, { "code": null, "e": 2766, "s": 2737, "text": "chauhangaurav97214 weeks ago" }, { "code": null, "e": 3693, "s": 2766, "text": "class Solution{\npublic:\n string decodedString(string s){\n stack<string>stk;\n for(int i = 0; i < s.size(); i++){\n if(s[i]==']'){\n string temp = \"\";\n while(stk.top()!=\"[\"){\n temp = temp + stk.top();\n stk.pop();\n }\n stk.pop();\n string count = \"\";\n while(stk.size() && isdigit(stk.top()[0])){\n count = count + stk.top();\n stk.pop();\n }\n reverse(count.begin(), count.end());\n int cnt = stoi(count);\n string cur = \"\";\n while(cnt--) cur += temp;\n stk.push(cur);\n }else{\n stk.push(string(1, s[i]));\n }\n }\n string ans = stk.top();\n reverse(ans.begin(), ans.end());\n return ans;\n }\n};" }, { "code": null, "e": 3697, "s": 3693, "text": "+11" }, { "code": null, "e": 3720, "s": 3697, "text": "geminicode2 months ago" }, { "code": null, "e": 3747, "s": 3720, "text": "THIS IS NOT EASY !!!!!!!! " }, { "code": null, "e": 3749, "s": 3747, "text": "0" }, { "code": null, "e": 3777, "s": 3749, "text": "sachinkartik1663 months ago" }, { "code": null, "e": 5817, "s": 3777, "text": "class Solution{\n String decodedString(String s){\n Stack<String> st=new Stack<>();\n String ans=\"\";\n \n for(int i=0;i<s.length();i++){\n if(s.charAt(i)==']'){\n String pele=st.pop();\n String maker=\"\";\n while(!pele.equals(\"[\")){\n maker=pele+maker;\n \n pele=st.pop();\n \n \n }\n \n pele=st.pop();\n String up=\"\";\n for(int j=0;j<Integer.parseInt(pele);j++){\n up=maker+up;\n }\n \n st.push(up);\n \n \n \n }else{\n \n \n try{\n String pp=st.peek();\n \n if(isNumeric(String.valueOf(s.charAt(i)))){\n \n \n if(isNumeric(pp)){\n while(isNumeric(pp)){\n st.pop();\n pp=pp+String.valueOf(s.charAt(i));\n if(!st.isEmpty()){\n pp=st.peek();\n }else{\n break;\n }\n \n }\n \n st.push(pp);\n }else{\n st.push(String.valueOf(s.charAt(i)));\n }\n }else{\n st.push(String.valueOf(s.charAt(i)));\n }\n \n }catch(Exception e){\n st.push(String.valueOf(s.charAt(i)));\n }\n \n \n \n }\n \n }\n \n return st.pop();\n \n }\n \n public boolean isNumeric(String str) { \n try { \n Integer.parseInt(str); \n return true;\n } catch(NumberFormatException e){ \n return false; \n } \n}\n \n}" }, { "code": null, "e": 5820, "s": 5817, "text": "+1" }, { "code": null, "e": 5844, "s": 5820, "text": "suchigiri134 months ago" }, { "code": null, "e": 6953, "s": 5844, "text": "class Solution{\n static String decodedString(String s){\n Stack<Character> stack = new Stack<>();\n int i = s.length() - 1;\n\n String ans = \"\";\n while(i >= 0){\n String temp = \"\";\n while(s.charAt(i) != '['){\n stack.push(s.charAt(i));\n i--;\n }if(s.charAt(i--) == '[') {\n while (stack.peek() != ']') {\n temp += stack.pop();\n // System.out.println(temp);\n }\n }\n stack.pop();\n if(!stack.isEmpty() && i >= 0){\n temp = temp.repeat(Character.getNumericValue(s.charAt(i)));\n ans = temp + ans;\n i--;\n }\n\n else if(stack.isEmpty() && i >= 0) {\n if (Character.isDigit(s.charAt(i))) {\n ans = temp + ans;\n ans = ans.repeat(Character.getNumericValue(s.charAt(i)));\n i--;\n }\n }\n }\n\n return ans;\n }\n}" }, { "code": null, "e": 7012, "s": 6953, "text": "Can anyone explain to me why it is giving run time error!!" }, { "code": null, "e": 7017, "s": 7014, "text": "+5" }, { "code": null, "e": 7044, "s": 7017, "text": "lovilakheraa024 months ago" }, { "code": null, "e": 8079, "s": 7044, "text": "EASY TO UNDERSTAND SOLUTION\n\nclass Solution{\npublic:\n string decodedString(string s){\n // code here\n int currNo=0;\n string currString=\"\";\n int prevNo;\n string prevString;\n stack<string>stringstack;\n stack<int>numstack;\n for(int i=0;i<s.size();i++)\n {\n if(isdigit(s[i])) currNo = currNo*10 + (s[i]-'0');\n if(isalpha(s[i])) currString += s[i];\n if(s[i] == '[')\n {\n stringstack.push(currString);\n numstack.push(currNo);\n currNo=0;\n currString=\"\";\n }\n if(s[i] == ']')\n {\n prevNo = numstack.top();\n numstack.pop();\n prevString = stringstack.top();\n stringstack.pop();\n \n while(prevNo--)\n {\n prevString += currString;\n }\n currString = prevString;\n }\n }\n return currString;\n \n \n }" }, { "code": null, "e": 8082, "s": 8079, "text": "+1" }, { "code": null, "e": 8110, "s": 8082, "text": "ankitkumar734ac4 months ago" }, { "code": null, "e": 9605, "s": 8110, "text": "class Solution{\n static String decodedString(String s){\nif(s == \"\")return \"\";\n String sol = new String();\n int repeat = 1;\n for(int i =0;i<s.length();++i)\n {\n if(Character.isDigit(s.charAt(i)))\n {\n String temp = \"\";\n int k = i;\n while(Character.isDigit(s.charAt(k)))\n {\n temp+=s.charAt(k);\n k++;\n }\n repeat = Integer.parseInt(temp);\n i = k-1;\n }\n else if(s.charAt(i) =='[')\n {\n Stack<Character> st = new Stack<>();\n st.push('[');\n int k = i+1;\n while(!st.isEmpty())\n {\n if(s.charAt(k) == ']')\n {\n st.pop();\n k++;\n }\n else if(s.charAt(k) =='[')\n {\n st.push('[');\n k++;\n }\n else k++;\n }\n String inside_bracket = decodedString(s.substring(i+1,k-1));\n i = k-1;\n for(int j =0;j<repeat;++j)\n {\n sol+=inside_bracket;\n }\n }\n \n else\n {\n sol+=s.charAt(i);\n }\n }\n return sol;\n }\n}" }, { "code": null, "e": 9608, "s": 9605, "text": "+1" }, { "code": null, "e": 9630, "s": 9608, "text": "mmodi01014 months ago" }, { "code": null, "e": 10849, "s": 9630, "text": "string decodedString(string s){\n // code here\n string num = \"\";\n string ans=\"\";\n int n;\n string temp=\"\";\n string temp2=\"\";\n stack<char> st;\n int p = 0;\n \n while(p<s.size())\n { if(s[p]==']')\n { while(st.top() != '[')\n {\n temp=st.top()+temp;\n st.pop();\n }\n st.pop();\n while(isdigit(st.top()))\n { num=st.top()+num;\n st.pop();\n if(st.empty()){\n break;\n }\n }\n n=stoi(num);\n for(int i=1;i<=n;i++)\n { temp2=temp2+temp;\n }\n if(st.empty())\n { ans=temp2;\n break;\n }\n for(int i=0;i<temp2.size();i++)\n { st.push(temp2[i]);\n }\n \n temp=\"\";\n temp2=\"\";\n num=\"\";\n }\n else\n { st.push(s[p]);\n }\n p++;\n }\n return ans;\n }" }, { "code": null, "e": 10863, "s": 10851, "text": "Time : 0.0s" }, { "code": null, "e": 11009, "s": 10863, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 11045, "s": 11009, "text": " Login to access your submissions. " }, { "code": null, "e": 11055, "s": 11045, "text": "\nProblem\n" }, { "code": null, "e": 11065, "s": 11055, "text": "\nContest\n" }, { "code": null, "e": 11128, "s": 11065, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 11276, "s": 11128, "text": "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." }, { "code": null, "e": 11484, "s": 11276, "text": "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." }, { "code": null, "e": 11590, "s": 11484, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How can Tensorflow be used to add dense layers on top using Python?
A dense layer can be added to the sequential model using the ‘add’ method, and specifying the type of layer as ‘Dense’. The layers are first flattened, and then a layer is added. This new layer will be applied to the entire training dataset. Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks? We will use the Keras Sequential API, which is helpful in building a sequential model that is used to work with a plain stack of layers, where every layer has exactly one input tensor and one output tensor. We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook. print("Adding dense layer on top") model.add(layers.Flatten()) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(10)) print("Complete architecture of the model") model.summary() Code credit: https://www.tensorflow.org/tutorials/images/cnn Adding dense layer on top Complete architecture of the model Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_3 (Conv2D) (None, 30, 30, 32) 896 _________________________________________________________________ max_pooling2d_2 (MaxPooling2 (None, 15, 15, 32) 0 _________________________________________________________________ conv2d_4 (Conv2D) (None, 13, 13, 64) 18496 _________________________________________________________________ max_pooling2d_3 (MaxPooling2 (None, 6, 6, 64) 0 _________________________________________________________________ conv2d_5 (Conv2D) (None, 4, 4, 64) 36928 _________________________________________________________________ flatten (Flatten) (None, 1024) 0 _________________________________________________________________ dense (Dense) (None, 64) 65600 _________________________________________________________________ dense_1 (Dense) (None, 10) 650 ================================================================= Total params: 122,570 Trainable params: 122,570 Non-trainable params: 0 _________________________________________________________________ To complete the model, the last output tensor from the convolutional base (of shape (4, 4, 64)) is fed to one or more Dense layers to perform classification. Dense layers will take vectors as input (which are 1D), and the current output is a 3D tensor. Next, the 3D output is flattened to 1D, and one or more Dense layers are added on top. CIFAR has 10 output classes, so a final Dense layer with 10 outputs is added. The (4, 4, 64) outputs are flattened into vectors of shape (1024) before going through two Dense layers.
[ { "code": null, "e": 1304, "s": 1062, "text": "A dense layer can be added to the sequential model using the ‘add’ method, and specifying the type of layer as ‘Dense’. The layers are first flattened, and then a layer is added. This new layer will be applied to the entire training dataset." }, { "code": null, "e": 1396, "s": 1304, "text": "Read More:\nWhat is TensorFlow and how Keras work with TensorFlow to create Neural Networks?" }, { "code": null, "e": 1603, "s": 1396, "text": "We will use the Keras Sequential API, which is helpful in building a sequential model that is used to work with a plain stack of layers, where every layer has exactly one input tensor and one output tensor." }, { "code": null, "e": 1873, "s": 1603, "text": "We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook." }, { "code": null, "e": 2071, "s": 1873, "text": "print(\"Adding dense layer on top\")\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(64, activation='relu'))\nmodel.add(layers.Dense(10))\nprint(\"Complete architecture of the model\")\nmodel.summary()" }, { "code": null, "e": 2132, "s": 2071, "text": "Code credit: https://www.tensorflow.org/tutorials/images/cnn" }, { "code": null, "e": 3665, "s": 2132, "text": "Adding dense layer on top\nComplete architecture of the model\nModel: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d_3 (Conv2D) (None, 30, 30, 32) 896 \n_________________________________________________________________\nmax_pooling2d_2 (MaxPooling2 (None, 15, 15, 32) 0 \n_________________________________________________________________\nconv2d_4 (Conv2D) (None, 13, 13, 64) 18496 \n_________________________________________________________________\nmax_pooling2d_3 (MaxPooling2 (None, 6, 6, 64) 0 \n_________________________________________________________________\nconv2d_5 (Conv2D) (None, 4, 4, 64) 36928 \n_________________________________________________________________\nflatten (Flatten) (None, 1024) 0 \n_________________________________________________________________\ndense (Dense) (None, 64) 65600 \n_________________________________________________________________\ndense_1 (Dense) (None, 10) 650 \n=================================================================\nTotal params: 122,570\nTrainable params: 122,570\nNon-trainable params: 0\n_________________________________________________________________" }, { "code": null, "e": 3823, "s": 3665, "text": "To complete the model, the last output tensor from the convolutional base (of shape (4, 4, 64)) is fed to one or more Dense layers to perform classification." }, { "code": null, "e": 3918, "s": 3823, "text": "Dense layers will take vectors as input (which are 1D), and the current output is a 3D tensor." }, { "code": null, "e": 4005, "s": 3918, "text": "Next, the 3D output is flattened to 1D, and one or more Dense layers are added on top." }, { "code": null, "e": 4083, "s": 4005, "text": "CIFAR has 10 output classes, so a final Dense layer with 10 outputs is added." }, { "code": null, "e": 4188, "s": 4083, "text": "The (4, 4, 64) outputs are flattened into vectors of shape (1024) before going through two Dense layers." } ]
Getting Started with Git and GitHub: A Complete Tutorial for Beginner | by Audhi Aprilliant | Towards Data Science
Git is an open-source version control system commonly used by developers around the world. The version control system helps developers to contribute to the open-source projects and check the version of codes. The git is developed by Linus Torvald, the Linux founder as a tool to help Linux developers develop and maintain the codes. So, git is the second project of Linus Torvald to support the main project, Linux. The above illustration clearly explains to us the functionality of git as a versioning tool. It lets us work with a single file instead of many files with their own version. Working with basic versioning (many files) tends to be untrackable and unstructured. We can not track our revision as well. But, using git, any revision or changes will be recorded on the git system and as users, we can move back to a certain version of files as we want to. From git logs, we can track the revision in our works, from the beginning. As the collaboration tool, git moves basic collaboration ways like using email, SMS, chat, etc to the collaborated system. Basic collaboration tends to be not integrated, misunderstanding, bad logs, and Inefficient for a big project with a lot of people working in it. Git is designed for text-based data, for instance codes, books, papers, article, etc Many companies and open-source projects are using version control systems to manage their project, like Google, Facebook, Microsoft, Twitter, LinkedIn, and others. So, this is why we need to learn the basic git commands for our future work and career in a tech company. It seems easy to install git on your computer. But it depends on your operating system as well. For Windows users, you might need to head over to git official site to download it. Luckily, for Linux user, just open our favorite terminal and run the script as follow: sudo apt-get updatesudo apt-get upgradesudo apt-get install git After the installation, everything would be okay. Check our git version with the following command. # Check our git versiongit --version For the first step, before talking deeper about git and its environment, we need to configure our git. We provide a username and email to it. # Setup the git configurationgit config --global user.name "your-username"git config --global user.email "your-email" For our first touch with git, let’s create a directory, for instance, git-stk in my case, and move into that directory. Then, begin our practice with git init. Important to note that git status will print the status on our works like are there any changes in the directory or files. As long as we didn't do any changes, the command git status will print no commits yet. So, what does git init means? Simply, this command will create a .git folder that contains several folders and files, like hooks, info, objects, refs, config, description, and HEAD in order to track our works. The logs of our changes will be recorded there. To interact with git commands, let’s create a new markdown file, namely README.md that filled with a sentence of “First line of README.md file”. Let’s check the current status with git status command. It prints with red marks indicating that we have done any changes to folders or files within the git-stk. It also means that our changes are not marked yet. We are in the modified state in the git lifecycle. To mark our change in file README.md, run git add command. To look up the differences of status between modified and staged state, just run git status again. The green mark indicates that our changes have been marked and now we are in the staged state. Our README.md file has been marked but has not been recorded yet. Record our changes like when we were working on Microsoft Word or other tools with git commit which is followed by the commit messages. So far, we have conducted experiments within a git environment and assigned git commands. But now, we will look deeper into the git lifecycle. What we did before is what we see in the git lifecycle. The git lifecycle is divided into four states namely: Modified: any changes didn’t been marked yet. We can do anything here, manipulate files, create or delete a new folder, and other things Staged: a condition when our changes have been marked but didn’t been recorded yet Committed: folders or files successfully are been recorded into our .git folder Can you imagine if we did some mistakes within our folders? Can we just move backward to our last commit or two last commits? The answer is of course we can. Git keeps our changes (commits) and we can go anywhere if it is necessary for our works. Okay, here is the new git command you must know: git log. We will record our entire commits, so we might easily track our works or commits. On the previous commit, we created a file namely README.md. Now, we will modify that file and inspect its logs using the git logs command. First, add our README.md file with the sentence “Second line of README.md file” and then commit it. Just follow and run the scripts based on the following figure. Check out the status until it prints “Nothing to commit”. It means that we have committed all of our changes. Okay, to track our works (commits), we just run git log and it will print the author (username and email), date-time of changes, messages, and SHA. git log --oneline : print logs just in one line git log --graph : show logs in a beautiful way with the author’s line git log --author=<username> : show logs for the certain author (if we work with many users in it) git log <filename> : show logs for certain file We must add commit messages as clear and simple as possible because it will help us to track our works One of the must-to-know command on git is git diff. It helps us to compare between commits on branches, specific files, or an entire directory. For instance, we will compare our two commits. The pattern is git diff <SHA-before> <SHA-after>. Input <SHA-before> and <SHA-after> with SHA of our commits. According to the output, we get information about the differences between our first commit and second commit on the README.md file. It is useful, right? As a human, we’re not perfect, right? Sometimes we get mistakes that impact other things. It applies to tech companies too, for instance as a data science team, we are developing new features to our machine learning flows. But found a bug. We must trace back from the beginning of works, looking into line per line of codes. Git simplifies our works with the move backward feature. Instead of looking from the beginning of works, we can track based on the previous commit before a bug was found. There are three commands to move back on git. It is used for our needs. git checkout: it is like a time machine, we can restore the condition of the project file to the designated time. However, this is temporary. These are not stored in the git database git reset: this command makes us unable to go back to the future. We will lose our commits. After the git logs were reset, we need to write a new commit git revert: will take the existing file condition in the past, then merge them with the last commit We can call the git checkout command to check the file condition at each commit. To return from the past use the command git checkout master When we decide to use git reset, there are three options we can select. It depends on our problem and which states we want to go to. Let’s check them out and try them on your computer! git reset --soft: will restore a file to the staged state git reset --mixed: will restore a file to the modified state git reset --hard: will restore a file to the committed state The git reflog is used to recover project history. We’re probably familiar with the git log command, which shows a list of commits. The git reflog is similar, but instead shows a list of times when HEAD changed. Let’s modify our README.md file again to show us the git checkout command. We just add a new line with “Third line of README.md file”. After that, like the previous step, add it into the committed state. Remember that we have restored our file with git reset and it removed our last commit. Then, using git checkout, we will check the file condition at each commit. Remember: Until this step, we just have three commits To check our first commit, we use the HEAD pointer. Follow the instruction to understand what does git checkout HEAD mean. It helps us track our content in the README.md file each commits, are there any changes? What kind of changes? To understand the functionality of tilde (~) and caret (^) on HEAD, please look at the following figure. It lets us go to every commits on every branch in our works. When talking about git as a versioning tool, we just talk about how git helps us keeping the version of our files. But, now we will talk git as a collaboration tool. The default branch name in Git is master When developing new features on our codes, it is recommended to create a new branch. Let the master branch as our main code. If our features are already done and there is no bug found, just merge with the master branch. In this case, we will create a new branch namely new_branch that adds two new lines on the README.md file. The git checkout command is also used to move and create branches Add a modification to the committed state on the new_branch branch and return to the master branch. Check the README.md file. Our modification on new_branch is not applied to the master because we worked on a different branch. It keeps our main codes clean and safe. Look at git logs and now you will find a new branch on the red mark. Yeah, this indicates there are any commits on another branch. We just created a new branch and commits to it. Now, we must merge that branch to the master and clean any conflicts. When we are working with a team, we must have many branches with its features. Our next task is to merge these branches and manage conflict within it. It is helped by git merge command. When files on the master are selected as the main file or code, we must merge another branch to the master. So we need to go to master! If our codes conflict, as the main developer or project leader, it is our task to choose whether codes are removed or added into the master. The two branch codes are separated by ====== After our merging is done properly, just check out the git logs. Voila! We have merged the new_branch to the master. Our master is clean now! This is the simple task of merging on git. Show what revision and author last modified each line of a file, we can use git blame command. git blame L <start><end> After talking a lot about git as versioning tools next, we talk git as collaboration tools via the remote repository. There are many platforms providing services to collaborate our scripts to people or our team, for instance, GitHub, GitLab, Bitbucket, and etc. For this tutorial, we use GitHub. So you might need to register your account and follow the instructions! Please log in to the GitHub page and create a new repository. Choose your own repo name and click create repository to create the new one. Our aim is to upload our local repository to the remote repository on GitHub. So, after the new repository is created, we can copy our remote repository link (via SSH or HTTPS) to the terminal and run git remote add command. It will create a new connection to a remote repository. Run git push to upload our local repository to a remote repository. This command takes two argument <remote-name> <branch-name> . <remote-name> : a remote name, for instance, origin <brach-name> : a branch name, for instance, master (default) We are here right now, coders! To summarize our tutorial, the friendly developer just creates a simple cheat sheet to help us understand the basic git commands we have already learned. Learn more about the git cheat sheet! You might be want to get the resume of this basic git tutorial, just visit my GitHub page https://audhiaprilliant.github.io/git-version-control-system/. It would be great to share and learn together with everyone across the world! Thanks! [1] Anonim, Git (2020), https://docs.github.com/.
[ { "code": null, "e": 588, "s": 172, "text": "Git is an open-source version control system commonly used by developers around the world. The version control system helps developers to contribute to the open-source projects and check the version of codes. The git is developed by Linus Torvald, the Linux founder as a tool to help Linux developers develop and maintain the codes. So, git is the second project of Linus Torvald to support the main project, Linux." }, { "code": null, "e": 1112, "s": 588, "text": "The above illustration clearly explains to us the functionality of git as a versioning tool. It lets us work with a single file instead of many files with their own version. Working with basic versioning (many files) tends to be untrackable and unstructured. We can not track our revision as well. But, using git, any revision or changes will be recorded on the git system and as users, we can move back to a certain version of files as we want to. From git logs, we can track the revision in our works, from the beginning." }, { "code": null, "e": 1381, "s": 1112, "text": "As the collaboration tool, git moves basic collaboration ways like using email, SMS, chat, etc to the collaborated system. Basic collaboration tends to be not integrated, misunderstanding, bad logs, and Inefficient for a big project with a lot of people working in it." }, { "code": null, "e": 1466, "s": 1381, "text": "Git is designed for text-based data, for instance codes, books, papers, article, etc" }, { "code": null, "e": 1736, "s": 1466, "text": "Many companies and open-source projects are using version control systems to manage their project, like Google, Facebook, Microsoft, Twitter, LinkedIn, and others. So, this is why we need to learn the basic git commands for our future work and career in a tech company." }, { "code": null, "e": 2003, "s": 1736, "text": "It seems easy to install git on your computer. But it depends on your operating system as well. For Windows users, you might need to head over to git official site to download it. Luckily, for Linux user, just open our favorite terminal and run the script as follow:" }, { "code": null, "e": 2067, "s": 2003, "text": "sudo apt-get updatesudo apt-get upgradesudo apt-get install git" }, { "code": null, "e": 2167, "s": 2067, "text": "After the installation, everything would be okay. Check our git version with the following command." }, { "code": null, "e": 2204, "s": 2167, "text": "# Check our git versiongit --version" }, { "code": null, "e": 2346, "s": 2204, "text": "For the first step, before talking deeper about git and its environment, we need to configure our git. We provide a username and email to it." }, { "code": null, "e": 2464, "s": 2346, "text": "# Setup the git configurationgit config --global user.name \"your-username\"git config --global user.email \"your-email\"" }, { "code": null, "e": 2834, "s": 2464, "text": "For our first touch with git, let’s create a directory, for instance, git-stk in my case, and move into that directory. Then, begin our practice with git init. Important to note that git status will print the status on our works like are there any changes in the directory or files. As long as we didn't do any changes, the command git status will print no commits yet." }, { "code": null, "e": 3092, "s": 2834, "text": "So, what does git init means? Simply, this command will create a .git folder that contains several folders and files, like hooks, info, objects, refs, config, description, and HEAD in order to track our works. The logs of our changes will be recorded there." }, { "code": null, "e": 3237, "s": 3092, "text": "To interact with git commands, let’s create a new markdown file, namely README.md that filled with a sentence of “First line of README.md file”." }, { "code": null, "e": 3501, "s": 3237, "text": "Let’s check the current status with git status command. It prints with red marks indicating that we have done any changes to folders or files within the git-stk. It also means that our changes are not marked yet. We are in the modified state in the git lifecycle." }, { "code": null, "e": 3754, "s": 3501, "text": "To mark our change in file README.md, run git add command. To look up the differences of status between modified and staged state, just run git status again. The green mark indicates that our changes have been marked and now we are in the staged state." }, { "code": null, "e": 3956, "s": 3754, "text": "Our README.md file has been marked but has not been recorded yet. Record our changes like when we were working on Microsoft Word or other tools with git commit which is followed by the commit messages." }, { "code": null, "e": 4209, "s": 3956, "text": "So far, we have conducted experiments within a git environment and assigned git commands. But now, we will look deeper into the git lifecycle. What we did before is what we see in the git lifecycle. The git lifecycle is divided into four states namely:" }, { "code": null, "e": 4346, "s": 4209, "text": "Modified: any changes didn’t been marked yet. We can do anything here, manipulate files, create or delete a new folder, and other things" }, { "code": null, "e": 4429, "s": 4346, "text": "Staged: a condition when our changes have been marked but didn’t been recorded yet" }, { "code": null, "e": 4509, "s": 4429, "text": "Committed: folders or files successfully are been recorded into our .git folder" }, { "code": null, "e": 4896, "s": 4509, "text": "Can you imagine if we did some mistakes within our folders? Can we just move backward to our last commit or two last commits? The answer is of course we can. Git keeps our changes (commits) and we can go anywhere if it is necessary for our works. Okay, here is the new git command you must know: git log. We will record our entire commits, so we might easily track our works or commits." }, { "code": null, "e": 5198, "s": 4896, "text": "On the previous commit, we created a file namely README.md. Now, we will modify that file and inspect its logs using the git logs command. First, add our README.md file with the sentence “Second line of README.md file” and then commit it. Just follow and run the scripts based on the following figure." }, { "code": null, "e": 5456, "s": 5198, "text": "Check out the status until it prints “Nothing to commit”. It means that we have committed all of our changes. Okay, to track our works (commits), we just run git log and it will print the author (username and email), date-time of changes, messages, and SHA." }, { "code": null, "e": 5504, "s": 5456, "text": "git log --oneline : print logs just in one line" }, { "code": null, "e": 5574, "s": 5504, "text": "git log --graph : show logs in a beautiful way with the author’s line" }, { "code": null, "e": 5672, "s": 5574, "text": "git log --author=<username> : show logs for the certain author (if we work with many users in it)" }, { "code": null, "e": 5720, "s": 5672, "text": "git log <filename> : show logs for certain file" }, { "code": null, "e": 5823, "s": 5720, "text": "We must add commit messages as clear and simple as possible because it will help us to track our works" }, { "code": null, "e": 6014, "s": 5823, "text": "One of the must-to-know command on git is git diff. It helps us to compare between commits on branches, specific files, or an entire directory. For instance, we will compare our two commits." }, { "code": null, "e": 6124, "s": 6014, "text": "The pattern is git diff <SHA-before> <SHA-after>. Input <SHA-before> and <SHA-after> with SHA of our commits." }, { "code": null, "e": 6277, "s": 6124, "text": "According to the output, we get information about the differences between our first commit and second commit on the README.md file. It is useful, right?" }, { "code": null, "e": 6773, "s": 6277, "text": "As a human, we’re not perfect, right? Sometimes we get mistakes that impact other things. It applies to tech companies too, for instance as a data science team, we are developing new features to our machine learning flows. But found a bug. We must trace back from the beginning of works, looking into line per line of codes. Git simplifies our works with the move backward feature. Instead of looking from the beginning of works, we can track based on the previous commit before a bug was found." }, { "code": null, "e": 6845, "s": 6773, "text": "There are three commands to move back on git. It is used for our needs." }, { "code": null, "e": 7028, "s": 6845, "text": "git checkout: it is like a time machine, we can restore the condition of the project file to the designated time. However, this is temporary. These are not stored in the git database" }, { "code": null, "e": 7181, "s": 7028, "text": "git reset: this command makes us unable to go back to the future. We will lose our commits. After the git logs were reset, we need to write a new commit" }, { "code": null, "e": 7281, "s": 7181, "text": "git revert: will take the existing file condition in the past, then merge them with the last commit" }, { "code": null, "e": 7422, "s": 7281, "text": "We can call the git checkout command to check the file condition at each commit. To return from the past use the command git checkout master" }, { "code": null, "e": 7607, "s": 7422, "text": "When we decide to use git reset, there are three options we can select. It depends on our problem and which states we want to go to. Let’s check them out and try them on your computer!" }, { "code": null, "e": 7665, "s": 7607, "text": "git reset --soft: will restore a file to the staged state" }, { "code": null, "e": 7726, "s": 7665, "text": "git reset --mixed: will restore a file to the modified state" }, { "code": null, "e": 7787, "s": 7726, "text": "git reset --hard: will restore a file to the committed state" }, { "code": null, "e": 7999, "s": 7787, "text": "The git reflog is used to recover project history. We’re probably familiar with the git log command, which shows a list of commits. The git reflog is similar, but instead shows a list of times when HEAD changed." }, { "code": null, "e": 8203, "s": 7999, "text": "Let’s modify our README.md file again to show us the git checkout command. We just add a new line with “Third line of README.md file”. After that, like the previous step, add it into the committed state." }, { "code": null, "e": 8365, "s": 8203, "text": "Remember that we have restored our file with git reset and it removed our last commit. Then, using git checkout, we will check the file condition at each commit." }, { "code": null, "e": 8419, "s": 8365, "text": "Remember: Until this step, we just have three commits" }, { "code": null, "e": 8653, "s": 8419, "text": "To check our first commit, we use the HEAD pointer. Follow the instruction to understand what does git checkout HEAD mean. It helps us track our content in the README.md file each commits, are there any changes? What kind of changes?" }, { "code": null, "e": 8819, "s": 8653, "text": "To understand the functionality of tilde (~) and caret (^) on HEAD, please look at the following figure. It lets us go to every commits on every branch in our works." }, { "code": null, "e": 8985, "s": 8819, "text": "When talking about git as a versioning tool, we just talk about how git helps us keeping the version of our files. But, now we will talk git as a collaboration tool." }, { "code": null, "e": 9026, "s": 8985, "text": "The default branch name in Git is master" }, { "code": null, "e": 9246, "s": 9026, "text": "When developing new features on our codes, it is recommended to create a new branch. Let the master branch as our main code. If our features are already done and there is no bug found, just merge with the master branch." }, { "code": null, "e": 9353, "s": 9246, "text": "In this case, we will create a new branch namely new_branch that adds two new lines on the README.md file." }, { "code": null, "e": 9419, "s": 9353, "text": "The git checkout command is also used to move and create branches" }, { "code": null, "e": 9686, "s": 9419, "text": "Add a modification to the committed state on the new_branch branch and return to the master branch. Check the README.md file. Our modification on new_branch is not applied to the master because we worked on a different branch. It keeps our main codes clean and safe." }, { "code": null, "e": 9817, "s": 9686, "text": "Look at git logs and now you will find a new branch on the red mark. Yeah, this indicates there are any commits on another branch." }, { "code": null, "e": 9935, "s": 9817, "text": "We just created a new branch and commits to it. Now, we must merge that branch to the master and clean any conflicts." }, { "code": null, "e": 10398, "s": 9935, "text": "When we are working with a team, we must have many branches with its features. Our next task is to merge these branches and manage conflict within it. It is helped by git merge command. When files on the master are selected as the main file or code, we must merge another branch to the master. So we need to go to master! If our codes conflict, as the main developer or project leader, it is our task to choose whether codes are removed or added into the master." }, { "code": null, "e": 10443, "s": 10398, "text": "The two branch codes are separated by ======" }, { "code": null, "e": 10628, "s": 10443, "text": "After our merging is done properly, just check out the git logs. Voila! We have merged the new_branch to the master. Our master is clean now! This is the simple task of merging on git." }, { "code": null, "e": 10723, "s": 10628, "text": "Show what revision and author last modified each line of a file, we can use git blame command." }, { "code": null, "e": 10748, "s": 10723, "text": "git blame L <start><end>" }, { "code": null, "e": 11116, "s": 10748, "text": "After talking a lot about git as versioning tools next, we talk git as collaboration tools via the remote repository. There are many platforms providing services to collaborate our scripts to people or our team, for instance, GitHub, GitLab, Bitbucket, and etc. For this tutorial, we use GitHub. So you might need to register your account and follow the instructions!" }, { "code": null, "e": 11255, "s": 11116, "text": "Please log in to the GitHub page and create a new repository. Choose your own repo name and click create repository to create the new one." }, { "code": null, "e": 11536, "s": 11255, "text": "Our aim is to upload our local repository to the remote repository on GitHub. So, after the new repository is created, we can copy our remote repository link (via SSH or HTTPS) to the terminal and run git remote add command. It will create a new connection to a remote repository." }, { "code": null, "e": 11666, "s": 11536, "text": "Run git push to upload our local repository to a remote repository. This command takes two argument <remote-name> <branch-name> ." }, { "code": null, "e": 11718, "s": 11666, "text": "<remote-name> : a remote name, for instance, origin" }, { "code": null, "e": 11779, "s": 11718, "text": "<brach-name> : a branch name, for instance, master (default)" }, { "code": null, "e": 12002, "s": 11779, "text": "We are here right now, coders! To summarize our tutorial, the friendly developer just creates a simple cheat sheet to help us understand the basic git commands we have already learned. Learn more about the git cheat sheet!" }, { "code": null, "e": 12241, "s": 12002, "text": "You might be want to get the resume of this basic git tutorial, just visit my GitHub page https://audhiaprilliant.github.io/git-version-control-system/. It would be great to share and learn together with everyone across the world! Thanks!" } ]
JupyterLab 2.0. Let’s take a glimpse into the future of... | by Roman Orac | Towards Data Science
A few days ago, I wrote a story Are you still using JupyterLab? and I got an amazing response. Readers pointed me to various new IDEs that are being developed for Data Science, but one of them stood out. Michal Krassowski left me a note about a project that he and other contributors have been working on. JupyterLab-LSP is a Language Server Protocol integration for JupyterLab. In short, it adds new superpowers to JupyterLab, like code navigation, hover suggestions, linters, autocomplete and rename. I am really excited about this one as it addresses most of the issues, where PyCharm is superior to JupyterLab. Let’s take it for a test drive Here are a few links that might interest you: - Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases. After installing JupyterLab-LSP you will notice “Fully initialized” icon in the status bar. This means that JupyterLab-LSP is working. Code linting works great. In the example below, It shows “imported by unused” warning. This one is one of the most anticipated features for me. Let’s test it. Code Completion (CC) didn’t work for pandas or numpy as can be seen in a video below. I also tried CC with columns in pandas DataFrame, but it wasn’t any different. CC did work great with system libraries and with classes I’ve defined. Some pandas functions take many arguments, some of which I rarely use. Each time I use such function, I have to google for documentation to refresh my mind about it. JupyterLab-LSP adds Function Signature Suggestions (FSS), which works great. You get a nice popup — not too intrusive, just right. FSS could be further improved by highlighting the current argument that you are editing, like deoplete-jedi plugin in NeoVim. Function Signature Suggestions works great, but there is a still room for improvement JupyterLab-LSP has also a nice diagnostic panel that lists all the warning and error. This is really useful as red underlinings may be overlooked from time to time. I was a bit disappointed with this one as I thought it will do refactoring, but it is a keyword replacement. I tried to refactor a variable name, but it also renamed a string as can be seen in a video below. JupyterLab-LSP is packed with useful features, like Go to Definition — would you like to see how pandas DataFrame works behind the scenes — just use Go to Definition. Code formatting will be a part of the LSP extension at some point too! Would you like to see how pandas DataFrame works behind the scenes — just use Go to Definition Make sure you have the latest JupyterLab installed — 2.1.0 at the time of writing. You also need to enable Extension Manager in JupyterLab. pip install -U jupyterlab Install LSP server extension: pip install jupyter-lsp Install node (command is for macOS): brew install nodejs Install frontend extension: jupyter labextension install @krassowski/jupyterlab-lsp Install LSP servers for programming languages: pip install 'python-language-server[all]' Start jupyterlab and you should see “Fully initialized” icon in the status bar. By the positive comments, I’ve made, you might be thinking that I will be using JuypterLab 2.0 with LSP daily. You would be surprised to know that I’ve actually installed the older version right after I finished this story. Why is that? While new features work great, other extensions that I use do not support JupyterLab 2.0 yet. Those are jupyterlab-vim for Vi keybindings and jupyterlab_code_formatter for code formating. These two extensions are at the moment more important to me than LSP support. Maybe we can have the best of both worlds as it seems that JupyterLab-LSP supports also JupyterLab 1.x, but I haven’t tried it yet. # for JupyterLab 1.xjupyter labextension install @krassowski/[email protected] In short, JupyterLab-LSP is a huge improvement and I can say I am going to be using it for sure in the future Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.
[ { "code": null, "e": 376, "s": 172, "text": "A few days ago, I wrote a story Are you still using JupyterLab? and I got an amazing response. Readers pointed me to various new IDEs that are being developed for Data Science, but one of them stood out." }, { "code": null, "e": 787, "s": 376, "text": "Michal Krassowski left me a note about a project that he and other contributors have been working on. JupyterLab-LSP is a Language Server Protocol integration for JupyterLab. In short, it adds new superpowers to JupyterLab, like code navigation, hover suggestions, linters, autocomplete and rename. I am really excited about this one as it addresses most of the issues, where PyCharm is superior to JupyterLab." }, { "code": null, "e": 818, "s": 787, "text": "Let’s take it for a test drive" }, { "code": null, "e": 864, "s": 818, "text": "Here are a few links that might interest you:" }, { "code": null, "e": 1194, "s": 864, "text": "- Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers" }, { "code": null, "e": 1431, "s": 1194, "text": "Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases." }, { "code": null, "e": 1566, "s": 1431, "text": "After installing JupyterLab-LSP you will notice “Fully initialized” icon in the status bar. This means that JupyterLab-LSP is working." }, { "code": null, "e": 1653, "s": 1566, "text": "Code linting works great. In the example below, It shows “imported by unused” warning." }, { "code": null, "e": 1725, "s": 1653, "text": "This one is one of the most anticipated features for me. Let’s test it." }, { "code": null, "e": 1961, "s": 1725, "text": "Code Completion (CC) didn’t work for pandas or numpy as can be seen in a video below. I also tried CC with columns in pandas DataFrame, but it wasn’t any different. CC did work great with system libraries and with classes I’ve defined." }, { "code": null, "e": 2127, "s": 1961, "text": "Some pandas functions take many arguments, some of which I rarely use. Each time I use such function, I have to google for documentation to refresh my mind about it." }, { "code": null, "e": 2258, "s": 2127, "text": "JupyterLab-LSP adds Function Signature Suggestions (FSS), which works great. You get a nice popup — not too intrusive, just right." }, { "code": null, "e": 2384, "s": 2258, "text": "FSS could be further improved by highlighting the current argument that you are editing, like deoplete-jedi plugin in NeoVim." }, { "code": null, "e": 2470, "s": 2384, "text": "Function Signature Suggestions works great, but there is a still room for improvement" }, { "code": null, "e": 2635, "s": 2470, "text": "JupyterLab-LSP has also a nice diagnostic panel that lists all the warning and error. This is really useful as red underlinings may be overlooked from time to time." }, { "code": null, "e": 2843, "s": 2635, "text": "I was a bit disappointed with this one as I thought it will do refactoring, but it is a keyword replacement. I tried to refactor a variable name, but it also renamed a string as can be seen in a video below." }, { "code": null, "e": 3010, "s": 2843, "text": "JupyterLab-LSP is packed with useful features, like Go to Definition — would you like to see how pandas DataFrame works behind the scenes — just use Go to Definition." }, { "code": null, "e": 3081, "s": 3010, "text": "Code formatting will be a part of the LSP extension at some point too!" }, { "code": null, "e": 3176, "s": 3081, "text": "Would you like to see how pandas DataFrame works behind the scenes — just use Go to Definition" }, { "code": null, "e": 3316, "s": 3176, "text": "Make sure you have the latest JupyterLab installed — 2.1.0 at the time of writing. You also need to enable Extension Manager in JupyterLab." }, { "code": null, "e": 3342, "s": 3316, "text": "pip install -U jupyterlab" }, { "code": null, "e": 3372, "s": 3342, "text": "Install LSP server extension:" }, { "code": null, "e": 3396, "s": 3372, "text": "pip install jupyter-lsp" }, { "code": null, "e": 3433, "s": 3396, "text": "Install node (command is for macOS):" }, { "code": null, "e": 3453, "s": 3433, "text": "brew install nodejs" }, { "code": null, "e": 3481, "s": 3453, "text": "Install frontend extension:" }, { "code": null, "e": 3537, "s": 3481, "text": "jupyter labextension install @krassowski/jupyterlab-lsp" }, { "code": null, "e": 3584, "s": 3537, "text": "Install LSP servers for programming languages:" }, { "code": null, "e": 3626, "s": 3584, "text": "pip install 'python-language-server[all]'" }, { "code": null, "e": 3706, "s": 3626, "text": "Start jupyterlab and you should see “Fully initialized” icon in the status bar." }, { "code": null, "e": 3943, "s": 3706, "text": "By the positive comments, I’ve made, you might be thinking that I will be using JuypterLab 2.0 with LSP daily. You would be surprised to know that I’ve actually installed the older version right after I finished this story. Why is that?" }, { "code": null, "e": 4341, "s": 3943, "text": "While new features work great, other extensions that I use do not support JupyterLab 2.0 yet. Those are jupyterlab-vim for Vi keybindings and jupyterlab_code_formatter for code formating. These two extensions are at the moment more important to me than LSP support. Maybe we can have the best of both worlds as it seems that JupyterLab-LSP supports also JupyterLab 1.x, but I haven’t tried it yet." }, { "code": null, "e": 4423, "s": 4341, "text": "# for JupyterLab 1.xjupyter labextension install @krassowski/[email protected]" }, { "code": null, "e": 4533, "s": 4423, "text": "In short, JupyterLab-LSP is a huge improvement and I can say I am going to be using it for sure in the future" } ]
Validate IPv4 address using ReGex patterns in C++
Given an IP Address, the task is to validate this IP address and check whether it is IPv4 or not with the help of ReGex(Regular Expression). If the IP Address is valid then print “IPv4 Address” otherwise print “Not”. A valid IPv4 address is an IP in the form "X1.X2.X3.X4" where 0 <= Xi <= 255 and Xi cannot contain leading zeros. For example, "192.168.1.1" and "192.168.1.0" are valid IPv4 addresses but "192.168.01.1", while "192.168.1.00" and "[email protected]" are invalid IPv4 addresses. For example, Input-1 − IP= “172.15.254.2” Output − “IPv4” Explanation − This is a valid IPv4 address, return “IPv4”. Input-2 − IP= “312.25.12.1” Output − “Not” Explanation − This is not a valid IPv4 Address, return “No”. To check whether the given IP address is IPv4 or not, we use ReGex. A ReGex is an expression that contains a sequence of characters that define a specific pattern. These patterns can be used in algorithms to match the pattern in a string. It is also widely used for Input Validation. Range Specification − We can specify the characters to make the patterns in the simplest way. To specify the range by using characters, we can use ‘[ ]’ brackets. Specifying Characters − The above expression indicates an opening bracket and a digit in the range a to z , ‘A’ to ‘Z’, and ‘0’ to ‘9’ as a regex. [a-z], [A-Z] and [0-9]. Repeated Patterns − An expression modifier can be “+” that suggests matching the occurrence of a pattern one or more times or it can be “*” that suggests matching the occurrence of a pattern zero or more times. The expression [a-z]* will match a blank string. If you want to specify a group of characters to match one or more times, then you can use the parentheses as follows − [Abc]+ Following is the approach to solving this problem, Take Input a string specifying an IP address. Take Input a string specifying an IP address. A string function validIPAddress(string IP) takes an IP address as input and checks whether the input string is valid or not. If it is valid then return “IPv4” otherwise return “Not an IP Address”. A string function validIPAddress(string IP) takes an IP address as input and checks whether the input string is valid or not. If it is valid then return “IPv4” otherwise return “Not an IP Address”. Creating a regex pattern for the IPv4 address. Since an IPv4 address contains 4 fields in which each field contains the value in the range of 0-255. An IPv4 address looks like XXX.XXX.XXX.XXX. Creating a regex pattern for the IPv4 address. Since an IPv4 address contains 4 fields in which each field contains the value in the range of 0-255. An IPv4 address looks like XXX.XXX.XXX.XXX. A valid IPv4 address might be in the range (([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0- 5])\\.){3} in which the first digit will be in the ranges from 0-9, second 1-9 and third digit in the range of 0-9. A valid IPv4 address might be in the range (([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0- 5])\\.){3} in which the first digit will be in the ranges from 0-9, second 1-9 and third digit in the range of 0-9. Similarly, for the second field first character would be in the range of 100-199, thus the regex pattern would be ‘1[0-9]-0-9]’ Similarly, for the second field first character would be in the range of 100-199, thus the regex pattern would be ‘1[0-9]-0-9]’ For the next field, the digit will be in the range 200-249. Thus the regex pattern will be ‘2[0-4][0-9]’ which ensures that the range doesn’t exceed a digit more than 255. For the next field, the digit will be in the range 200-249. Thus the regex pattern will be ‘2[0-4][0-9]’ which ensures that the range doesn’t exceed a digit more than 255. The last which is the next field contains digits in the range from 250-255 thus the regex pattern would be 25[0-5]. The last which is the next field contains digits in the range from 250-255 thus the regex pattern would be 25[0-5]. #include<bits/stdc++.h> using namespace std; string validIPAddress(string IP) { regex ipv4("(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0- 9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"); if(regex_match(IP, ipv4)) return "IPv4"; else return "Not"; } int main(){ string IP= “172.16.254.1”; string ans= validIPAddress(IP); cout<<ans<<endl; return 0; } Running the above code will generate the output as, IPv4 Since the input IP Address is a Valid IP address, we will return “IPv4”.
[ { "code": null, "e": 1279, "s": 1062, "text": "Given an IP Address, the task is to validate this IP address and check whether it is IPv4 or not with the help of ReGex(Regular Expression). If the IP Address is valid then print “IPv4 Address” otherwise print “Not”." }, { "code": null, "e": 1563, "s": 1279, "text": "A valid IPv4 address is an IP in the form \"X1.X2.X3.X4\" where 0 <= Xi <= 255 and Xi cannot contain leading zeros. For example, \"192.168.1.1\" and \"192.168.1.0\" are valid IPv4 addresses but \"192.168.01.1\", while \"192.168.1.00\" and \"[email protected]\" are invalid IPv4 addresses. For example," }, { "code": null, "e": 1573, "s": 1563, "text": "Input-1 −" }, { "code": null, "e": 1592, "s": 1573, "text": "IP= “172.15.254.2”" }, { "code": null, "e": 1601, "s": 1592, "text": "Output −" }, { "code": null, "e": 1608, "s": 1601, "text": "“IPv4”" }, { "code": null, "e": 1667, "s": 1608, "text": "Explanation − This is a valid IPv4 address, return “IPv4”." }, { "code": null, "e": 1677, "s": 1667, "text": "Input-2 −" }, { "code": null, "e": 1695, "s": 1677, "text": "IP= “312.25.12.1”" }, { "code": null, "e": 1704, "s": 1695, "text": "Output −" }, { "code": null, "e": 1710, "s": 1704, "text": "“Not”" }, { "code": null, "e": 1771, "s": 1710, "text": "Explanation − This is not a valid IPv4 Address, return “No”." }, { "code": null, "e": 2055, "s": 1771, "text": "To check whether the given IP address is IPv4 or not, we use ReGex. A ReGex is an expression that contains a sequence of characters that define a specific pattern. These patterns can be used in algorithms to match the pattern in a string. It is also widely used for Input Validation." }, { "code": null, "e": 2218, "s": 2055, "text": "Range Specification − We can specify the characters to make the patterns in the simplest way. To specify the range by using characters, we can use ‘[ ]’ brackets." }, { "code": null, "e": 2389, "s": 2218, "text": "Specifying Characters − The above expression indicates an opening bracket and a digit in the range a to z , ‘A’ to ‘Z’, and ‘0’ to ‘9’ as a regex. [a-z], [A-Z] and [0-9]." }, { "code": null, "e": 2600, "s": 2389, "text": "Repeated Patterns − An expression modifier can be “+” that suggests matching the occurrence of a pattern one or more times or it can be “*” that suggests matching the occurrence of a pattern zero or more times." }, { "code": null, "e": 2649, "s": 2600, "text": "The expression [a-z]* will match a blank string." }, { "code": null, "e": 2768, "s": 2649, "text": "If you want to specify a group of characters to match one or more times, then you can use the parentheses as follows −" }, { "code": null, "e": 2775, "s": 2768, "text": "[Abc]+" }, { "code": null, "e": 2826, "s": 2775, "text": "Following is the approach to solving this problem," }, { "code": null, "e": 2872, "s": 2826, "text": "Take Input a string specifying an IP address." }, { "code": null, "e": 2918, "s": 2872, "text": "Take Input a string specifying an IP address." }, { "code": null, "e": 3116, "s": 2918, "text": "A string function validIPAddress(string IP) takes an IP address as input and checks whether the input string is valid or not. If it is valid then return “IPv4” otherwise return “Not an IP Address”." }, { "code": null, "e": 3314, "s": 3116, "text": "A string function validIPAddress(string IP) takes an IP address as input and checks whether the input string is valid or not. If it is valid then return “IPv4” otherwise return “Not an IP Address”." }, { "code": null, "e": 3507, "s": 3314, "text": "Creating a regex pattern for the IPv4 address. Since an IPv4 address contains 4 fields in which each field contains the value in the range of 0-255. An IPv4 address looks like XXX.XXX.XXX.XXX." }, { "code": null, "e": 3700, "s": 3507, "text": "Creating a regex pattern for the IPv4 address. Since an IPv4 address contains 4 fields in which each field contains the value in the range of 0-255. An IPv4 address looks like XXX.XXX.XXX.XXX." }, { "code": null, "e": 3908, "s": 3700, "text": "A valid IPv4 address might be in the range (([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0- 5])\\\\.){3} in which the first digit will be in the ranges from 0-9, second 1-9 and third digit in the range of 0-9." }, { "code": null, "e": 4116, "s": 3908, "text": "A valid IPv4 address might be in the range (([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0- 5])\\\\.){3} in which the first digit will be in the ranges from 0-9, second 1-9 and third digit in the range of 0-9." }, { "code": null, "e": 4244, "s": 4116, "text": "Similarly, for the second field first character would be in the range of 100-199, thus the regex pattern would be ‘1[0-9]-0-9]’" }, { "code": null, "e": 4372, "s": 4244, "text": "Similarly, for the second field first character would be in the range of 100-199, thus the regex pattern would be ‘1[0-9]-0-9]’" }, { "code": null, "e": 4544, "s": 4372, "text": "For the next field, the digit will be in the range 200-249. Thus the regex pattern will be ‘2[0-4][0-9]’ which ensures that the range doesn’t exceed a digit more than 255." }, { "code": null, "e": 4716, "s": 4544, "text": "For the next field, the digit will be in the range 200-249. Thus the regex pattern will be ‘2[0-4][0-9]’ which ensures that the range doesn’t exceed a digit more than 255." }, { "code": null, "e": 4832, "s": 4716, "text": "The last which is the next field contains digits in the range from 250-255 thus the regex pattern would be 25[0-5]." }, { "code": null, "e": 4948, "s": 4832, "text": "The last which is the next field contains digits in the range from 250-255 thus the regex pattern would be 25[0-5]." }, { "code": null, "e": 5348, "s": 4948, "text": "#include<bits/stdc++.h>\nusing namespace std;\nstring validIPAddress(string IP) {\n regex ipv4(\"(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\\\.){3}([0- 9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\");\n if(regex_match(IP, ipv4))\n return \"IPv4\";\n else\n return \"Not\";\n}\nint main(){\n string IP= “172.16.254.1”;\n string ans= validIPAddress(IP);\n cout<<ans<<endl;\n return 0;\n}" }, { "code": null, "e": 5400, "s": 5348, "text": "Running the above code will generate the output as," }, { "code": null, "e": 5405, "s": 5400, "text": "IPv4" }, { "code": null, "e": 5478, "s": 5405, "text": "Since the input IP Address is a Valid IP address, we will return “IPv4”." } ]
Angular Material 7 - Chips
The <mat-chip-list>, an Angular Directive, is used to a list of values as chips. In this chapter, we will showcase the configuration required to draw a chip control using Angular Material. Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter − Following is the content of the modified module descriptor app.module.ts. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {MatChipsModule} from '@angular/material' import {FormsModule, ReactiveFormsModule} from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, MatChipsModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Following is the content of the modified HTML host file app.component.html. <mat-chip-list> <mat-chip>One</mat-chip> <mat-chip>Two</mat-chip> <mat-chip color = "primary" selected>Tree</mat-chip> <mat-chip color = "accent" selected>Four</mat-chip> </mat-chip-list> Verify the result. As first, we've created chip list using mat-chip-list. Then, we've added chips to each chip list using mat-chip. 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": 2836, "s": 2755, "text": "The <mat-chip-list>, an Angular Directive, is used to a list of values as chips." }, { "code": null, "e": 2944, "s": 2836, "text": "In this chapter, we will showcase the configuration required to draw a chip control using Angular Material." }, { "code": null, "e": 3055, "s": 2944, "text": "Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −" }, { "code": null, "e": 3129, "s": 3055, "text": "Following is the content of the modified module descriptor app.module.ts." }, { "code": null, "e": 3742, "s": 3129, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatChipsModule} from '@angular/material'\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatChipsModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 3818, "s": 3742, "text": "Following is the content of the modified HTML host file app.component.html." }, { "code": null, "e": 4018, "s": 3818, "text": "<mat-chip-list>\n <mat-chip>One</mat-chip>\n <mat-chip>Two</mat-chip>\n <mat-chip color = \"primary\" selected>Tree</mat-chip>\n <mat-chip color = \"accent\" selected>Four</mat-chip>\n</mat-chip-list>" }, { "code": null, "e": 4037, "s": 4018, "text": "Verify the result." }, { "code": null, "e": 4092, "s": 4037, "text": "As first, we've created chip list using mat-chip-list." }, { "code": null, "e": 4150, "s": 4092, "text": "Then, we've added chips to each chip list using mat-chip." }, { "code": null, "e": 4185, "s": 4150, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4199, "s": 4185, "text": " Anadi Sharma" }, { "code": null, "e": 4234, "s": 4199, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4248, "s": 4234, "text": " Anadi Sharma" }, { "code": null, "e": 4283, "s": 4248, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4303, "s": 4283, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 4338, "s": 4303, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4355, "s": 4338, "text": " Frahaan Hussain" }, { "code": null, "e": 4388, "s": 4355, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 4400, "s": 4388, "text": " Senol Atac" }, { "code": null, "e": 4435, "s": 4400, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4447, "s": 4435, "text": " Senol Atac" }, { "code": null, "e": 4454, "s": 4447, "text": " Print" }, { "code": null, "e": 4465, "s": 4454, "text": " Add Notes" } ]
Plotting the Learning Curve with a Single Line of Code | by Rukshan Pramoditha | Towards Data Science
The Learning Curve is another great tool to have in any data scientist’s toolbox. It is a visualization technique that can be to see how much our model benefits from adding more training data. It shows the relationship between the training score and the test score for a machine learning model with a varying number of training samples. Generally, the cross-validation procedure is taken into effect when plotting the learning curve. A good ML model fits the training data very well and is generalizable to new input data as well. Sometimes, an ML model may require more training instances in order to generalize to new input data. Adding more training data will sometimes benefit the model to generalize, but not always! We can decide whether to add more training data to build a more generalizable model by looking at its learning curve. Plotting the learning curve typically requires writing many lines of code and consumes more time. But, thanks to the Python Yellowbrick library, things are much easy now! By using it properly, we can plot the learning curve with just a single line of code! In this article, we will discuss how to plot the learning curve with Yellowbrick and learn how to interpret it. To get the most out of today’s content, it is recommended to read the “Using k-fold cross-validation for evaluating a model’s performance” section of my k-fold cross-validation explained in plain English article. In addition to that, having knowledge of Support Vector Machines and Random Forests algorithms is preferred. This is because, today, we plot the learning curve based on those algorithms. If you’re not familiar with them, just read the following contents written by me. Support Vector Machines with Scikit-learn Random forests — An ensemble of decision trees Yellowbrick doesn’t come with the default Anaconda installer. You need to manually install it. To install it, open your Anaconda prompt and just run the following command. pip install yellowbrick If that didn’t work for you, try the following with the user tag. pip install yellowbrick --user or you can also try it with the conda-forge channel. conda install -c conda-forge yellowbrick or try it with the DistrictDataLabs channel. conda install -c districtdatalabs yellowbrick Any of the above methods will install the latest version of Yellowbrick. Now, consider the following example codes where we plot the learning curve of an SVM and a Random Forest Classifier using the Scikit-learn built-in breast cancer dataset. That dataset has 30 features and 569 training samples. Let’s see adding more data will benefit the SVM and Random Forest models to generalize to new input data. In the above graphs, the accuracy score of the train set is marked as the “Training Score” and the accuracy score of the test set is marked as the “Cross-Validation Score”. Until about 175 training instances, the training score of the SVC (Support Vector Classifier) model (graph at left) is much greater than the test score. Therefore, if your current dataset has much less than 175 training instances (e.g. around 100), adding more training instances will increase generalization. But, after the 175 level, the model will probably not benefit much from adding more training data. For the Random Forest Classifier (graph at right), we can see that the training and test scores have not yet converged, so potentially this model would benefit from adding more training data (e.g. around 700–1000 training instances). When we execute the learning_curve() function, a lot of work happens behind the scenes. We only need to run a single line of code to plot the learning curve. That’s the power of Yellowbrick! The first argument of the learning_curve() function should be a Scikit-learn estimator (here it is an SVM or a Random Forest Classifier). The second and third ones should be X (feature matrix) and y (target vector). The “cv” defines the number of folds for the cross-validation. Standard values are 3, 5, and 10 (here it is 10). The scoring argument contains the method of scoring of the model. In classification, “accuracy” and “roc_auc” are most preferred. In regression, “r2” and “neg_mean_squared_error” are commonly used. In addition to those, there are many evaluation metrics. You can find all of them by visiting this link. When we execute the learning_curve() function, the cross-validation procedure happens behind the scenes. Because of this, we just input X and y. We don’t need to split the dataset as X_train, y_train, X_test, y_test. In cross-validation, the splitting is done internally based on the number of folds specified in cv. Using cross-validation here guarantees that the accuracy score of the model isn’t much affected by the random data splitting process. If you just use the train_test_split() function without cross-validation, the accuracy score will vary significantly based on the random_state you provide inside the train_test_split() function. Here in cross-validation, the accuracy is calculated using the average of 10 (cv=10) such iterations! The learning curve is a great tool that you should have in your machine learning toolkit. It can be used to see how much your model benefits from adding more training data. Sometimes, adding more data will benefit the model to generalize to new input data. Generally, the cross-validation procedure is taken into effect when plotting the learning curve to avoid the effect of the random data splitting process. The learning curve should not be confused with the validation curve which is used to plot the influence of a single hyperparameter. The functionalities of both curves are totally different. If you’re interested to learn more about the validation curve, you may read my “Validation Curve Explained — Plot the influence of a single hyperparameter” article. Thanks for reading! This tutorial was designed and created by Rukshan Pramoditha, the Author of Data Science 365 Blog. Read my other articles at https://rukshanpramoditha.medium.com
[ { "code": null, "e": 606, "s": 172, "text": "The Learning Curve is another great tool to have in any data scientist’s toolbox. It is a visualization technique that can be to see how much our model benefits from adding more training data. It shows the relationship between the training score and the test score for a machine learning model with a varying number of training samples. Generally, the cross-validation procedure is taken into effect when plotting the learning curve." }, { "code": null, "e": 1012, "s": 606, "text": "A good ML model fits the training data very well and is generalizable to new input data as well. Sometimes, an ML model may require more training instances in order to generalize to new input data. Adding more training data will sometimes benefit the model to generalize, but not always! We can decide whether to add more training data to build a more generalizable model by looking at its learning curve." }, { "code": null, "e": 1381, "s": 1012, "text": "Plotting the learning curve typically requires writing many lines of code and consumes more time. But, thanks to the Python Yellowbrick library, things are much easy now! By using it properly, we can plot the learning curve with just a single line of code! In this article, we will discuss how to plot the learning curve with Yellowbrick and learn how to interpret it." }, { "code": null, "e": 1594, "s": 1381, "text": "To get the most out of today’s content, it is recommended to read the “Using k-fold cross-validation for evaluating a model’s performance” section of my k-fold cross-validation explained in plain English article." }, { "code": null, "e": 1863, "s": 1594, "text": "In addition to that, having knowledge of Support Vector Machines and Random Forests algorithms is preferred. This is because, today, we plot the learning curve based on those algorithms. If you’re not familiar with them, just read the following contents written by me." }, { "code": null, "e": 1905, "s": 1863, "text": "Support Vector Machines with Scikit-learn" }, { "code": null, "e": 1952, "s": 1905, "text": "Random forests — An ensemble of decision trees" }, { "code": null, "e": 2124, "s": 1952, "text": "Yellowbrick doesn’t come with the default Anaconda installer. You need to manually install it. To install it, open your Anaconda prompt and just run the following command." }, { "code": null, "e": 2148, "s": 2124, "text": "pip install yellowbrick" }, { "code": null, "e": 2214, "s": 2148, "text": "If that didn’t work for you, try the following with the user tag." }, { "code": null, "e": 2245, "s": 2214, "text": "pip install yellowbrick --user" }, { "code": null, "e": 2298, "s": 2245, "text": "or you can also try it with the conda-forge channel." }, { "code": null, "e": 2339, "s": 2298, "text": "conda install -c conda-forge yellowbrick" }, { "code": null, "e": 2384, "s": 2339, "text": "or try it with the DistrictDataLabs channel." }, { "code": null, "e": 2430, "s": 2384, "text": "conda install -c districtdatalabs yellowbrick" }, { "code": null, "e": 2503, "s": 2430, "text": "Any of the above methods will install the latest version of Yellowbrick." }, { "code": null, "e": 2835, "s": 2503, "text": "Now, consider the following example codes where we plot the learning curve of an SVM and a Random Forest Classifier using the Scikit-learn built-in breast cancer dataset. That dataset has 30 features and 569 training samples. Let’s see adding more data will benefit the SVM and Random Forest models to generalize to new input data." }, { "code": null, "e": 3651, "s": 2835, "text": "In the above graphs, the accuracy score of the train set is marked as the “Training Score” and the accuracy score of the test set is marked as the “Cross-Validation Score”. Until about 175 training instances, the training score of the SVC (Support Vector Classifier) model (graph at left) is much greater than the test score. Therefore, if your current dataset has much less than 175 training instances (e.g. around 100), adding more training instances will increase generalization. But, after the 175 level, the model will probably not benefit much from adding more training data. For the Random Forest Classifier (graph at right), we can see that the training and test scores have not yet converged, so potentially this model would benefit from adding more training data (e.g. around 700–1000 training instances)." }, { "code": null, "e": 4474, "s": 3651, "text": "When we execute the learning_curve() function, a lot of work happens behind the scenes. We only need to run a single line of code to plot the learning curve. That’s the power of Yellowbrick! The first argument of the learning_curve() function should be a Scikit-learn estimator (here it is an SVM or a Random Forest Classifier). The second and third ones should be X (feature matrix) and y (target vector). The “cv” defines the number of folds for the cross-validation. Standard values are 3, 5, and 10 (here it is 10). The scoring argument contains the method of scoring of the model. In classification, “accuracy” and “roc_auc” are most preferred. In regression, “r2” and “neg_mean_squared_error” are commonly used. In addition to those, there are many evaluation metrics. You can find all of them by visiting this link." }, { "code": null, "e": 5222, "s": 4474, "text": "When we execute the learning_curve() function, the cross-validation procedure happens behind the scenes. Because of this, we just input X and y. We don’t need to split the dataset as X_train, y_train, X_test, y_test. In cross-validation, the splitting is done internally based on the number of folds specified in cv. Using cross-validation here guarantees that the accuracy score of the model isn’t much affected by the random data splitting process. If you just use the train_test_split() function without cross-validation, the accuracy score will vary significantly based on the random_state you provide inside the train_test_split() function. Here in cross-validation, the accuracy is calculated using the average of 10 (cv=10) such iterations!" }, { "code": null, "e": 5633, "s": 5222, "text": "The learning curve is a great tool that you should have in your machine learning toolkit. It can be used to see how much your model benefits from adding more training data. Sometimes, adding more data will benefit the model to generalize to new input data. Generally, the cross-validation procedure is taken into effect when plotting the learning curve to avoid the effect of the random data splitting process." }, { "code": null, "e": 5988, "s": 5633, "text": "The learning curve should not be confused with the validation curve which is used to plot the influence of a single hyperparameter. The functionalities of both curves are totally different. If you’re interested to learn more about the validation curve, you may read my “Validation Curve Explained — Plot the influence of a single hyperparameter” article." }, { "code": null, "e": 6008, "s": 5988, "text": "Thanks for reading!" }, { "code": null, "e": 6107, "s": 6008, "text": "This tutorial was designed and created by Rukshan Pramoditha, the Author of Data Science 365 Blog." } ]
What is Pass By Reference and Pass By Value in PHP?
In this article, we will learn about pass by value and pass by reference in PHP. Now, let’s understand these two concepts in detail. In PHP generally, we followed to pass the arguments to the function with passed by value approach. We are following this practice because if the value of the argument within the function is changed, it does not get changed outside of the function. In some cases we may need to modify function arguments, So to allow a function to modify its arguments, they must be passed by reference. Let's begin with passed by reference. As it is already mentioned we can pass a variable by reference to a function so the function can modify the variable. To begin the process of passing the parameters passed by reference, prepend an ampersand (&) to the argument name in the function definition. Let's test this with a simple example. <?php function calculate(&$a){ $a++; } $a=5; calculate($a); echo $a; ?> 6 Here we have declared variable aandpassingitaspassbyreferencetothefunctioncalculate().Soastheprinciplesaysifthevalueofthea gets changed inside the function then it will be also going to change outside the function. There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. This is deprecated in 5.4 version of PHP when you use to calculate(&$a); it throws an error. Let's test an example to understand pass by value. <?php function calculate($a){ $a++; echo $a."<br/>"; } $a=5; calculate($a); echo $a; ?> 6 5 Here we have passed the value to the function calculate() as pass by value. Its value gets changed inside the function but that is not reflected outside the function. The value of the variable remains the same outside the function.
[ { "code": null, "e": 1144, "s": 1062, "text": "In this article, we will learn about pass by value and pass by reference in PHP. " }, { "code": null, "e": 1196, "s": 1144, "text": "Now, let’s understand these two concepts in detail." }, { "code": null, "e": 1444, "s": 1196, "text": "In PHP generally, we followed to pass the arguments to the function with passed by value approach. We are following this practice because if the value of the argument within the function is changed, it does not get changed outside of the function." }, { "code": null, "e": 1582, "s": 1444, "text": "In some cases we may need to modify function arguments, So to allow a function to modify its arguments, they must be passed by reference." }, { "code": null, "e": 1880, "s": 1582, "text": "Let's begin with passed by reference. As it is already mentioned we can pass a variable by reference to a function so the function can modify the variable. To begin the process of passing the parameters passed by reference, prepend an ampersand (&) to the argument name in the function definition." }, { "code": null, "e": 1919, "s": 1880, "text": "Let's test this with a simple example." }, { "code": null, "e": 2012, "s": 1919, "text": "<?php\n function calculate(&$a){\n $a++;\n }\n $a=5;\n calculate($a);\n echo $a;\n?>" }, { "code": null, "e": 2014, "s": 2012, "text": "6" }, { "code": null, "e": 2229, "s": 2014, "text": "Here we have declared variable aandpassingitaspassbyreferencetothefunctioncalculate().Soastheprinciplesaysifthevalueofthea gets changed inside the function then it will be also going to change outside the function." }, { "code": null, "e": 2483, "s": 2229, "text": "There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. This is deprecated in 5.4 version of PHP when you use to calculate(&$a); it throws an error." }, { "code": null, "e": 2534, "s": 2483, "text": "Let's test an example to understand pass by value." }, { "code": null, "e": 2646, "s": 2534, "text": "<?php\n function calculate($a){\n $a++;\n echo $a.\"<br/>\";\n }\n $a=5;\n calculate($a);\n echo $a;\n?>" }, { "code": null, "e": 2650, "s": 2646, "text": "6\n5" }, { "code": null, "e": 2882, "s": 2650, "text": "Here we have passed the value to the function calculate() as pass by value. Its value gets changed inside the function but that is not reflected outside the function. The value of the variable remains the same outside the function." } ]
Evaluating Bayesian Mixed Models in R/Python | by Eduardo Coronado Sroka | Towards Data Science
What can I say, model checking and evaluation are just one of those things you can’t (and shouldn’t) avoid in your model development process (as if this isn’t obvious enough). Yet, I think in many cases we end up chasing performance metrics — say RMSE, misclassification, etc.— rather than understanding how well our model represents the data. This can lead to problems down the line. So, no matter what framework and metrics you’re using I’d always recommend you keep the following questions in mind: What aspects of our data and understanding of the problem aren’t being captured by my model?Which model performs best and how well might it generalize (i.e. work in the future)? What aspects of our data and understanding of the problem aren’t being captured by my model? Which model performs best and how well might it generalize (i.e. work in the future)? Avoid chasing performance metrics (e.g. RMSE, misclassification, etc.). Understanding how well our model represents the data and our knowledge is also crucial. In this article, my goal guide is you through some useful model checking and evaluation VISUAL METHODS for Bayesian models (not your typical RMSE) in both R and Python. I will build upon an example and set of models covered in my previous post so I recommend you take a quick look before moving forward. towardsdatascience.com Here’s what I’ll cover: How to check model fit via posterior predictive checks (PPCs)How to evaluate performance via cross-validation (LOOCV, in a Bayesian setting)An applied model selection example using these two concepts How to check model fit via posterior predictive checks (PPCs) How to evaluate performance via cross-validation (LOOCV, in a Bayesian setting) An applied model selection example using these two concepts Without further ado, let’s travel through the dunes of uncertainty and onto Bayesian lands. (Sorry not sorry for this cheesy metaphor. 😉) In my previous post our EDA suggested we explore three Bayesian models — a simple linear regression (base model), a random intercept model and a random intercept, random slope model — on simulated website bounce times with the overall goal of determining whether younger people spend more time on a website than older ones across locations. Similarly, we ran some MCMC visual diagnostics to check whether we could trust the samples generated from the sampling methods in brms and pymc3. Thus, the next step in our model development process should be to evaluate each model’s fit to the data given the context, as well as gauging their predictive performance with the end of goal selecting the best one. NOTE: The previous post contains only code snippets. All model fitting and MCMC diagnostics code is found on Github. Posterior predictive checks are just a fancy way of saying model checking in Bayesian jargon. The name originates from the methods used to assess goodness-of-fit (explained below). Once you’ve fit a model and the MCMC diagnostics show no red flags, you might want to visually explore how well the model fits the data. In a non-Bayesian setting you’d probably look at residual or Normal Q-Q plots (which you can still do for Bayesian models). However, be aware that Bayesian residual plots won’t capture the uncertainty around our inferences since they are based on single parameter draw. Bayesian models are generative thus we can simulate values under a model and check whether these resemble those in our original data. Bayesian models are generative in nature which allows us to simulate datasets under a model and compare these against observed ones. If the model fits well, we expect simulated values to look similar to those in our observed data. If instead our simulated data doesn’t resemble the observed data then we’ve misspecified the model and should be wary of our parameter inferences. If simulated values don’t resemble those in the observed then we can say we have a “lack of fit” or “model misspecification”. Thus, the most common technique to check model fit is to simulate datasets from the posterior predictive distribution — hence the term posterior predictive checks — which is defined as follows We are basically marginalizing (integrating) over our posterior inferences to obtain a predicted value ỹ given our observed data y. You can think about this procedure as first simulating some parameter values from your joint posterior (e.g. mean and variance) and then using those as inputs in a likelihood function (e.g. a Normal distribution) to generate predicted samples. Thus the quality of our posterior inferences will impact how well the posterior predicted samples will represent the observed data. Let’s dive to some coded examples. First, let’s explore how well the densities of simulated datasets compare to those of observed data. In R bayesplot provides nice built-in function ppc_dense_overlay to generate these visualizations. In Python, PyMC3 also has built-in function plot_ppc generated via arviz. Below we see that simulated data generated from the random intercept model fits the observed data well (i.e. has a similar pattern). Ok so our simulated data visually seems to resemble the observed density, however we might also want to know how comparable simulated summary statistics are to those of the observed data. From your good ‘ol Stat 101 days you might recall that the typical test statistics are the mean, variance, etc. and you might be tempted to use those. Let’s see what happens when we use the mean with the samples from our base linear regression. Great! The means of the posterior samples also seem to fit the data — so we should move on, right? Well, wait a second. Let’s look at another summary statistic: skewness. Uhm, what? What happened?! Well, this is a cautionary tale that illustrates the importance of checking more than just the mean and the variance of the posterior predicted samples. If we had only done this, we might have incorrectly concluded that our model has no lack of fit and that it correctly represents the data while it clearly doesn’t capture its skewness. In fact, it is recommended to look at summary statistics unrelated (also referred to as orthogonal) to any of the parameters you’re updating. Test statistics related to our model parameters might be unable to capture potential issues between the data and our models. In our case, our models assume a Gaussian distribution and we are updating mean and variance parameters. So unrelated metrics we could explore are skewness and median values — the former at a population level and the later at the group level. In R, we can use two bayesplot function to generate these diagrams: ppc_stat and ppc_stat_grouped. In Python, this isn’t as straightforward but can be achieved with some custom code using pandas, matplotlib, and plotly as follows. Now, we can see the random intercept model captures the behavior of the observed data. Firstly, based on skewness and secondly based on county-level median values. In the previous section we covered model checking using the joint posterior predictive density (i.e. considering all the data). However, what if we’re also interested in detecting unusual observations such as outliers and influential points, or checking how well our model is specified across observations? Using the joint distribution makes it really hard to do this. Instead, we can take our model checking to a more granular level based on marginal (i.e. univariate) posterior predictive distributions. One way to obtain these marginal samples is via the leave-one-out cross-validation (LOO CV) predictive density. “Wait, but that’s so inefficient!” I know, I know. Computing these requires us to refit the model n times (!!), but fret not dear reader, there are ways to approximate these densities without all the refitting. Smart people came up with an elegant approximation method called Pareto Smoothed Importance Sampling (PSIS) which I’ll refer to as LOO-PSIS. Marginal predictive checks can be particularly useful for detecting outliers and influential points, or for checking overall model calibration (i.e. how well the model is specified). In a Bayesian setting, we use some probability theory to test this — specifically, a concept called the probability integral transform (PIT), which basically uses CDF properties to convert continuous random variables into uniformly distributed ones. However, this only holds exactly if the distribution used to generate the continuous random variables is the true distribution. What does that mean for us? In our case, the fitted model is what’s generating the continuous random variables so if it is a good approximation of the true bounce time generative distribution, then the set of empirical CDF values we calculate for each LOO marginal density will be approximately uniform. That is, for each univariate density p( ỹ_i | y_-i ) of a left out point we will compute a CDF value [ p_i = Pr( ỹ_i ≤ y_i | y_-i ) ] and then plot these p_is to see if they look uniformly distributed. If our fitted model is a good approximation of the true data generating distribution, then the PIT converted values will approximately follow a uniform. This might sound like “voodoo magic” to some so I’ve written a nice side tutorial you can review to get more intuition on why this is true. Feel free to play around with the code and data. htmlpreview.github.io Yay! If you’re still here it means I either didn’t completely lose you with the PIT explanation or I’ve regained your trust (hopefully) with that tutorial. Ok, let’s dive into an example on how to use this diagnostic. As a heads up, I’ll refer to the empirical CDF values as LOO-PIT. In R, we can use the loo package to generate LOO-PSIS samples and the bayesplot ppc_loo_pit_overlay function to apply the PIT to these values and compare them against samples form a Uniform[0,1]. In Python, you can use a PyMC3 built-in function plot_loo_pit as follows Below we can see that the LOO-PIT values (thick curve) from our model plotted against random samples of a standard uniform (thin curves). Without going into details, here’s a general way to interpret these plots: LOO-PIT values concentrated near 0 or 1 hint at an under-dispersed model (i.e. our pointwise predictive densities are too narrow and expect less variation than found in the data)LOO-PIT values concentrated near 0.5 hint at an over-dispersed model (i.e. our pointwise predictive densities are too broad and expect greater variation than found in the data) LOO-PIT values concentrated near 0 or 1 hint at an under-dispersed model (i.e. our pointwise predictive densities are too narrow and expect less variation than found in the data) LOO-PIT values concentrated near 0.5 hint at an over-dispersed model (i.e. our pointwise predictive densities are too broad and expect greater variation than found in the data) Looking at our model there isn’t any apparent lack-of-fit since the LOO-PIT values follow plausible uniform samples. However, there seems to be a sticky point near 0.6 which hints a slight over-dispersion (i.e. some marginal densities are too broad compared to the data) and is discussed in the tutorial linked above. If instead the LOO-PIT lines were nowhere near the uniform samples then you should interpret this as lack-of-fit and explore further modeling. (To learn more I recommend you read pages 152–153 of Bayesian Data Analysis 3). As in any modeling scenario, we’re interested in the effect potential influential data points or outliers could have on our model — i.e. if we were to omit influential points, would they drastically change our posterior predictive density? Looking at observations associated with these points provides hints as to whether and how we might want to modify our modeling strategy. Traditionally we compare the full data posterior predictive density and with each LOO CV predictive density to identify these points but this can be computationally expensive. Luckily, the LOO-PSIS method already computes an empirical estimate of this comparison: the tail shape parameter ( k̂ ) of the generalized Pareto distribution used in the sampler. Intuitively, if a marginal predictive density of a left out point has a large k̂ then it suggests that this point is highly influential. In practice, observations with k̂ values: Less than 0.7 are considered non-influential points with reliable PSIS estimates of the LOO predictive density Between 0.7 and 1 are considered influential and less reliable Greater than 1 are considered highly influential and unreliably estimated by the model The Pareto-k diagnostic can be useful to identify problematic point(s) in your model (or even across models!). Let’s work through an example to get some intuition on how to use this k̂ to identify these unusual points. In R, you can use the loo function to compute and extract the Pareto shape estimates k̂ and visualize these with ggplot . In Python, you can use the PyMC3 built-in function loo to generate the pointwise samples and the plot_khat function to visualize these shape estimates. Since all observations have a k̂ <0.5 then none are considered influential in the posterior given our model is able to characterize them correctly. In other words, our model’s LOO-PSIS estimates are reliable. As always we would like to know the predictive accuracy of our models given some out-of-sample (unknown) data. A common approach to estimate this error is to use some type of cross-validation. Aside from your typical RMSE metric, linear Bayesian models’ performance can be assessed with some additional metrics. For example, the Expected Log Predictive Density (ELPD) or the Watanabe–Akaike information criterion (WAIC), which is faster and less computationally expensive the ELPD. Here I will focus on the ELPD criteria. Intuitively, ELPD refers to the model’s average predictive performance over the distribution of unseen data (which, as stated above, we can approximate with cross-validation). Regardless of the cross-validation flavor we choose — K-fold or LOO — we can obtain an expected log predicted density (ELPD) value for each out-of-sample datapoint (see here for an intuitive example). In general, higher ELPD values indicate better model performance. Although it might sound counterintuitive, in a Bayesian setting computing K-fold CV can be less efficient and more complex than LOO CV. Now, using K-fold might seem like a no-brainer compared to LOO given it generally leads to lower variance (especially when data is correlated), and can be less computationally expensive. However, in a Bayesian setting we have ways to approximate LOO values without having to refit the model multiple times (e.g. the PSIS method discussed above). Additionally, LOO ELPD estimates have a major advantage over K-fold ELDP values. They allow us to identify points that are hard to predict and can even be used in model comparison to identify which model best captures each out-of-sample observation. Let’s walk through an example of how to compare the predictive performance models using overall LOO ELPD and pointwise LOO ELPD values. In R, we can use loo and loo_compare functions to compare the overall performance of multiple models, as well as the pointwise differences between a pair of models. (Note: loo also provides a kfold function.) In Python, we can use the PyMC compare and loo functions to obtain the same overall and pointwise model comparisons. Below are the outputs from the code above. Models with best overall performance are commonly listed first and have the smallest ( d_loo ) and largest ( elpd_loo ). In our case, the random intercept model has the best overall performance. Now, as I mentioned above we can obtain pointwise ELPD estimates regardless of the CV method of our choosing which allows us to compare models more granularly. The values plotted below are the differences between the ELPD values from the random intercept model minus those of the linear regression. Here we see the random intercept model has better overall performance (i.e. most values > 0), however, notice there are certain points where the linear regression performs better. The ELPD pointwise plots paired with the above Pareto-k diagnostic plots can help identify unusual points. Now that we’ve covered all the ins and outs of the ways Bayesian models can be evaluated, let’s apply these techniques to the three models from my previous post. First, we compare at the posterior predictive densities of our models. Here we observe that the linear mixed models tend to better fit the observed data. Similarly, we’d want to look at some posterior test statistics, keeping in mind that statistics related to our model parameters might not be as useful for detecting model misspecification. Below, observe how the mean fails to capture the lack-of-fit of the linear regression while the skewness coefficient clearly shows a misspecification. We can also look at the county-specific test statistics to identify potential lack-of-fit. Below we observe that the mixed models also tend to capture the county medians (thick lines) better than the linear regression model. Next, looking at the LOO-PIT diagnostic we see no lack-of-fit for any of our models given all PIT values (thick lines) follow probable random uniform samples (thin lines). However, as discussed above, there seems to be some sticky points for all models. The linear regression seems to present under-dispersion (i.e. values concentrating towards 1) while the mixed models present some over-dispersion (i.e. values concentrating towards 0.5). This provides hints that further modeling effort could focus on narrowing the univariate posterior predictive distributions in the mixed models to better capture the uncertainty. Now, looking at the predictive performance between models using the ELPD information criteria we see that the random intercept model seems to be the best model (i.e. elpd_diff = 0.0 ). ## elpd_diff se_diff## bayes_rintercept 0.0 0.0 ## bayes_rslope -1.3 0.3 ## lin_reg -347.8 18.8 We can look at the pointwise differences between the random intercept model and the other two to see where it performs better (i.e. ELPD_rand_int_i — ELDP_other_model_i ). The top diagrams shows the random intercept model performs better than the linear regression for most points ( ELPD Pointwise Diff > 0 ) and thus the large difference in model performance above. A similar comparison between the mixed models demonstrates their similar performance but we can also use this analysis to identify observations that are harder to predict (e.g. those in Dorset county). Finally, looking at the indices of those hard-to-predict observations in the Pareto-k diagnostic we can see the random intercept model is able to better resolve these observations (i.e. smaller k̂ value). Congrats, you’ve reached the Bayesian lands! You should feel proud of yourself at this point. Having to tread through all that material can be daunting but hopefully you’ve gained a better understanding and some intuition about how to evaluate Bayesian models. From the analysis above we see that the best model for this data is the random intercept one. It not only shows good predictive performance but also shows a good fit for our data. So as a final step, let’s look at our inferences and answers our initial question: “How does age affect bounce time?” The table below provides a summary of some fixed effects and within-/between-group variance estimate with 95% credible intervals. Two important things to note here: Given the 95% intervals don’t contain 0, we’re confident that all these estimates are non-zero Related to our original question, the effect of age on bounce time is about 1.8. Since we center-scaled our variable, the effect will be positive or negative relative to whether we’re considering deviations above or below the average age. You can achieve summary tables like these using tidybayes in R or PyMC3’s pm.summary() function in Python. A very useful approach for understanding the estimated differences amongst groups is to visualize the random effects. Below we see that cheshire, cumbria, essex, and kent tend to have higher average bounce times while london and norfolk have lower ones. We can’t say that for dorset and devon since their 95% intervals contain zero and thus we can’t be certain the bounce rates in these counties deviate from the population average. One thing to note is how our Bayesian framework is able to capture uncertainty even in counties with smaller sample sizes (i.e. kent and essex ). Using tidybayes in R or PyMC3’s pm.foresplot() function in Python you can achieve these very nice visuals We observe that counties with larger sample sizes have narrower intervals around the fits (e.g. cheshire) while smaller ones have wider intervals (e.g. kent). Finally, we can check the fits against the data. Using tidybayes in R you can achieve these very nice visuals quite easily, in Python it can be more tedious but still possible with seaborn and pandas. Evaluating Bayesian models follows many of the same goodness-of-fit testing and performance comparison steps as for any other model you’d encounter. However, there are tools and concepts that are particularly useful for assessing Bayesian models. Some are quite complex and it can feel daunting to use them if you’re unfamiliar with what their outputs mean. (There’s nothing more distressing than not being able to understand a model’s output summary.) Luckily there are visual ways of diagnosing model fit, evaluating performance, and even interpreting results from Bayesian models. I hope this part 2 on Bayesian mixed models has continued to build your intuition about Bayesian modeling such that it becomes a powerful method in your toolset. towardsdatascience.com towardsdatascience.com Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., & Rubin, D. B. (2013). Bayesian data analysis. CRC press.Gabry, Jonah, et al. “Visualization in Bayesian workflow.” Journal of the Royal Statistical Society: Series A (Statistics in Society) 182.2 (2019): 389–402.Gelman, Andrew, Jessica Hwang, and Aki Vehtari. “Understanding predictive information criteria for Bayesian models.” Statistics and computing 24.6 (2014): 997–1016.Vehtari, Aki, Andrew Gelman, and Jonah Gabry. “Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC.” Statistics and computing 27.5 (2017): 1413–1432. Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., & Rubin, D. B. (2013). Bayesian data analysis. CRC press. Gabry, Jonah, et al. “Visualization in Bayesian workflow.” Journal of the Royal Statistical Society: Series A (Statistics in Society) 182.2 (2019): 389–402. Gelman, Andrew, Jessica Hwang, and Aki Vehtari. “Understanding predictive information criteria for Bayesian models.” Statistics and computing 24.6 (2014): 997–1016. Vehtari, Aki, Andrew Gelman, and Jonah Gabry. “Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC.” Statistics and computing 27.5 (2017): 1413–1432. If you liked the article feel free to share! Comment or tweet (@ecoronado92) if you have any questions, or you see anything incorrect/questionable. All R code can be found here All Python code can be found here
[ { "code": null, "e": 556, "s": 171, "text": "What can I say, model checking and evaluation are just one of those things you can’t (and shouldn’t) avoid in your model development process (as if this isn’t obvious enough). Yet, I think in many cases we end up chasing performance metrics — say RMSE, misclassification, etc.— rather than understanding how well our model represents the data. This can lead to problems down the line." }, { "code": null, "e": 673, "s": 556, "text": "So, no matter what framework and metrics you’re using I’d always recommend you keep the following questions in mind:" }, { "code": null, "e": 851, "s": 673, "text": "What aspects of our data and understanding of the problem aren’t being captured by my model?Which model performs best and how well might it generalize (i.e. work in the future)?" }, { "code": null, "e": 944, "s": 851, "text": "What aspects of our data and understanding of the problem aren’t being captured by my model?" }, { "code": null, "e": 1030, "s": 944, "text": "Which model performs best and how well might it generalize (i.e. work in the future)?" }, { "code": null, "e": 1190, "s": 1030, "text": "Avoid chasing performance metrics (e.g. RMSE, misclassification, etc.). Understanding how well our model represents the data and our knowledge is also crucial." }, { "code": null, "e": 1494, "s": 1190, "text": "In this article, my goal guide is you through some useful model checking and evaluation VISUAL METHODS for Bayesian models (not your typical RMSE) in both R and Python. I will build upon an example and set of models covered in my previous post so I recommend you take a quick look before moving forward." }, { "code": null, "e": 1517, "s": 1494, "text": "towardsdatascience.com" }, { "code": null, "e": 1541, "s": 1517, "text": "Here’s what I’ll cover:" }, { "code": null, "e": 1741, "s": 1541, "text": "How to check model fit via posterior predictive checks (PPCs)How to evaluate performance via cross-validation (LOOCV, in a Bayesian setting)An applied model selection example using these two concepts" }, { "code": null, "e": 1803, "s": 1741, "text": "How to check model fit via posterior predictive checks (PPCs)" }, { "code": null, "e": 1883, "s": 1803, "text": "How to evaluate performance via cross-validation (LOOCV, in a Bayesian setting)" }, { "code": null, "e": 1943, "s": 1883, "text": "An applied model selection example using these two concepts" }, { "code": null, "e": 2081, "s": 1943, "text": "Without further ado, let’s travel through the dunes of uncertainty and onto Bayesian lands. (Sorry not sorry for this cheesy metaphor. 😉)" }, { "code": null, "e": 2568, "s": 2081, "text": "In my previous post our EDA suggested we explore three Bayesian models — a simple linear regression (base model), a random intercept model and a random intercept, random slope model — on simulated website bounce times with the overall goal of determining whether younger people spend more time on a website than older ones across locations. Similarly, we ran some MCMC visual diagnostics to check whether we could trust the samples generated from the sampling methods in brms and pymc3." }, { "code": null, "e": 2784, "s": 2568, "text": "Thus, the next step in our model development process should be to evaluate each model’s fit to the data given the context, as well as gauging their predictive performance with the end of goal selecting the best one." }, { "code": null, "e": 2901, "s": 2784, "text": "NOTE: The previous post contains only code snippets. All model fitting and MCMC diagnostics code is found on Github." }, { "code": null, "e": 3489, "s": 2901, "text": "Posterior predictive checks are just a fancy way of saying model checking in Bayesian jargon. The name originates from the methods used to assess goodness-of-fit (explained below). Once you’ve fit a model and the MCMC diagnostics show no red flags, you might want to visually explore how well the model fits the data. In a non-Bayesian setting you’d probably look at residual or Normal Q-Q plots (which you can still do for Bayesian models). However, be aware that Bayesian residual plots won’t capture the uncertainty around our inferences since they are based on single parameter draw." }, { "code": null, "e": 3623, "s": 3489, "text": "Bayesian models are generative thus we can simulate values under a model and check whether these resemble those in our original data." }, { "code": null, "e": 4001, "s": 3623, "text": "Bayesian models are generative in nature which allows us to simulate datasets under a model and compare these against observed ones. If the model fits well, we expect simulated values to look similar to those in our observed data. If instead our simulated data doesn’t resemble the observed data then we’ve misspecified the model and should be wary of our parameter inferences." }, { "code": null, "e": 4127, "s": 4001, "text": "If simulated values don’t resemble those in the observed then we can say we have a “lack of fit” or “model misspecification”." }, { "code": null, "e": 4320, "s": 4127, "text": "Thus, the most common technique to check model fit is to simulate datasets from the posterior predictive distribution — hence the term posterior predictive checks — which is defined as follows" }, { "code": null, "e": 4697, "s": 4320, "text": "We are basically marginalizing (integrating) over our posterior inferences to obtain a predicted value ỹ given our observed data y. You can think about this procedure as first simulating some parameter values from your joint posterior (e.g. mean and variance) and then using those as inputs in a likelihood function (e.g. a Normal distribution) to generate predicted samples." }, { "code": null, "e": 4829, "s": 4697, "text": "Thus the quality of our posterior inferences will impact how well the posterior predicted samples will represent the observed data." }, { "code": null, "e": 4864, "s": 4829, "text": "Let’s dive to some coded examples." }, { "code": null, "e": 4965, "s": 4864, "text": "First, let’s explore how well the densities of simulated datasets compare to those of observed data." }, { "code": null, "e": 5064, "s": 4965, "text": "In R bayesplot provides nice built-in function ppc_dense_overlay to generate these visualizations." }, { "code": null, "e": 5138, "s": 5064, "text": "In Python, PyMC3 also has built-in function plot_ppc generated via arviz." }, { "code": null, "e": 5271, "s": 5138, "text": "Below we see that simulated data generated from the random intercept model fits the observed data well (i.e. has a similar pattern)." }, { "code": null, "e": 5704, "s": 5271, "text": "Ok so our simulated data visually seems to resemble the observed density, however we might also want to know how comparable simulated summary statistics are to those of the observed data. From your good ‘ol Stat 101 days you might recall that the typical test statistics are the mean, variance, etc. and you might be tempted to use those. Let’s see what happens when we use the mean with the samples from our base linear regression." }, { "code": null, "e": 5875, "s": 5704, "text": "Great! The means of the posterior samples also seem to fit the data — so we should move on, right? Well, wait a second. Let’s look at another summary statistic: skewness." }, { "code": null, "e": 6240, "s": 5875, "text": "Uhm, what? What happened?! Well, this is a cautionary tale that illustrates the importance of checking more than just the mean and the variance of the posterior predicted samples. If we had only done this, we might have incorrectly concluded that our model has no lack of fit and that it correctly represents the data while it clearly doesn’t capture its skewness." }, { "code": null, "e": 6382, "s": 6240, "text": "In fact, it is recommended to look at summary statistics unrelated (also referred to as orthogonal) to any of the parameters you’re updating." }, { "code": null, "e": 6507, "s": 6382, "text": "Test statistics related to our model parameters might be unable to capture potential issues between the data and our models." }, { "code": null, "e": 6750, "s": 6507, "text": "In our case, our models assume a Gaussian distribution and we are updating mean and variance parameters. So unrelated metrics we could explore are skewness and median values — the former at a population level and the later at the group level." }, { "code": null, "e": 6849, "s": 6750, "text": "In R, we can use two bayesplot function to generate these diagrams: ppc_stat and ppc_stat_grouped." }, { "code": null, "e": 6981, "s": 6849, "text": "In Python, this isn’t as straightforward but can be achieved with some custom code using pandas, matplotlib, and plotly as follows." }, { "code": null, "e": 7095, "s": 6981, "text": "Now, we can see the random intercept model captures the behavior of the observed data. Firstly, based on skewness" }, { "code": null, "e": 7145, "s": 7095, "text": "and secondly based on county-level median values." }, { "code": null, "e": 7763, "s": 7145, "text": "In the previous section we covered model checking using the joint posterior predictive density (i.e. considering all the data). However, what if we’re also interested in detecting unusual observations such as outliers and influential points, or checking how well our model is specified across observations? Using the joint distribution makes it really hard to do this. Instead, we can take our model checking to a more granular level based on marginal (i.e. univariate) posterior predictive distributions. One way to obtain these marginal samples is via the leave-one-out cross-validation (LOO CV) predictive density." }, { "code": null, "e": 8115, "s": 7763, "text": "“Wait, but that’s so inefficient!” I know, I know. Computing these requires us to refit the model n times (!!), but fret not dear reader, there are ways to approximate these densities without all the refitting. Smart people came up with an elegant approximation method called Pareto Smoothed Importance Sampling (PSIS) which I’ll refer to as LOO-PSIS." }, { "code": null, "e": 8298, "s": 8115, "text": "Marginal predictive checks can be particularly useful for detecting outliers and influential points, or for checking overall model calibration (i.e. how well the model is specified)." }, { "code": null, "e": 8676, "s": 8298, "text": "In a Bayesian setting, we use some probability theory to test this — specifically, a concept called the probability integral transform (PIT), which basically uses CDF properties to convert continuous random variables into uniformly distributed ones. However, this only holds exactly if the distribution used to generate the continuous random variables is the true distribution." }, { "code": null, "e": 9184, "s": 8676, "text": "What does that mean for us? In our case, the fitted model is what’s generating the continuous random variables so if it is a good approximation of the true bounce time generative distribution, then the set of empirical CDF values we calculate for each LOO marginal density will be approximately uniform. That is, for each univariate density p( ỹ_i | y_-i ) of a left out point we will compute a CDF value [ p_i = Pr( ỹ_i ≤ y_i | y_-i ) ] and then plot these p_is to see if they look uniformly distributed." }, { "code": null, "e": 9337, "s": 9184, "text": "If our fitted model is a good approximation of the true data generating distribution, then the PIT converted values will approximately follow a uniform." }, { "code": null, "e": 9526, "s": 9337, "text": "This might sound like “voodoo magic” to some so I’ve written a nice side tutorial you can review to get more intuition on why this is true. Feel free to play around with the code and data." }, { "code": null, "e": 9548, "s": 9526, "text": "htmlpreview.github.io" }, { "code": null, "e": 9832, "s": 9548, "text": "Yay! If you’re still here it means I either didn’t completely lose you with the PIT explanation or I’ve regained your trust (hopefully) with that tutorial. Ok, let’s dive into an example on how to use this diagnostic. As a heads up, I’ll refer to the empirical CDF values as LOO-PIT." }, { "code": null, "e": 10028, "s": 9832, "text": "In R, we can use the loo package to generate LOO-PSIS samples and the bayesplot ppc_loo_pit_overlay function to apply the PIT to these values and compare them against samples form a Uniform[0,1]." }, { "code": null, "e": 10101, "s": 10028, "text": "In Python, you can use a PyMC3 built-in function plot_loo_pit as follows" }, { "code": null, "e": 10314, "s": 10101, "text": "Below we can see that the LOO-PIT values (thick curve) from our model plotted against random samples of a standard uniform (thin curves). Without going into details, here’s a general way to interpret these plots:" }, { "code": null, "e": 10669, "s": 10314, "text": "LOO-PIT values concentrated near 0 or 1 hint at an under-dispersed model (i.e. our pointwise predictive densities are too narrow and expect less variation than found in the data)LOO-PIT values concentrated near 0.5 hint at an over-dispersed model (i.e. our pointwise predictive densities are too broad and expect greater variation than found in the data)" }, { "code": null, "e": 10848, "s": 10669, "text": "LOO-PIT values concentrated near 0 or 1 hint at an under-dispersed model (i.e. our pointwise predictive densities are too narrow and expect less variation than found in the data)" }, { "code": null, "e": 11025, "s": 10848, "text": "LOO-PIT values concentrated near 0.5 hint at an over-dispersed model (i.e. our pointwise predictive densities are too broad and expect greater variation than found in the data)" }, { "code": null, "e": 11486, "s": 11025, "text": "Looking at our model there isn’t any apparent lack-of-fit since the LOO-PIT values follow plausible uniform samples. However, there seems to be a sticky point near 0.6 which hints a slight over-dispersion (i.e. some marginal densities are too broad compared to the data) and is discussed in the tutorial linked above. If instead the LOO-PIT lines were nowhere near the uniform samples then you should interpret this as lack-of-fit and explore further modeling." }, { "code": null, "e": 11566, "s": 11486, "text": "(To learn more I recommend you read pages 152–153 of Bayesian Data Analysis 3)." }, { "code": null, "e": 12119, "s": 11566, "text": "As in any modeling scenario, we’re interested in the effect potential influential data points or outliers could have on our model — i.e. if we were to omit influential points, would they drastically change our posterior predictive density? Looking at observations associated with these points provides hints as to whether and how we might want to modify our modeling strategy. Traditionally we compare the full data posterior predictive density and with each LOO CV predictive density to identify these points but this can be computationally expensive." }, { "code": null, "e": 12478, "s": 12119, "text": "Luckily, the LOO-PSIS method already computes an empirical estimate of this comparison: the tail shape parameter ( k̂ ) of the generalized Pareto distribution used in the sampler. Intuitively, if a marginal predictive density of a left out point has a large k̂ then it suggests that this point is highly influential. In practice, observations with k̂ values:" }, { "code": null, "e": 12589, "s": 12478, "text": "Less than 0.7 are considered non-influential points with reliable PSIS estimates of the LOO predictive density" }, { "code": null, "e": 12652, "s": 12589, "text": "Between 0.7 and 1 are considered influential and less reliable" }, { "code": null, "e": 12739, "s": 12652, "text": "Greater than 1 are considered highly influential and unreliably estimated by the model" }, { "code": null, "e": 12850, "s": 12739, "text": "The Pareto-k diagnostic can be useful to identify problematic point(s) in your model (or even across models!)." }, { "code": null, "e": 12958, "s": 12850, "text": "Let’s work through an example to get some intuition on how to use this k̂ to identify these unusual points." }, { "code": null, "e": 13080, "s": 12958, "text": "In R, you can use the loo function to compute and extract the Pareto shape estimates k̂ and visualize these with ggplot ." }, { "code": null, "e": 13232, "s": 13080, "text": "In Python, you can use the PyMC3 built-in function loo to generate the pointwise samples and the plot_khat function to visualize these shape estimates." }, { "code": null, "e": 13441, "s": 13232, "text": "Since all observations have a k̂ <0.5 then none are considered influential in the posterior given our model is able to characterize them correctly. In other words, our model’s LOO-PSIS estimates are reliable." }, { "code": null, "e": 13963, "s": 13441, "text": "As always we would like to know the predictive accuracy of our models given some out-of-sample (unknown) data. A common approach to estimate this error is to use some type of cross-validation. Aside from your typical RMSE metric, linear Bayesian models’ performance can be assessed with some additional metrics. For example, the Expected Log Predictive Density (ELPD) or the Watanabe–Akaike information criterion (WAIC), which is faster and less computationally expensive the ELPD. Here I will focus on the ELPD criteria." }, { "code": null, "e": 14406, "s": 13963, "text": "Intuitively, ELPD refers to the model’s average predictive performance over the distribution of unseen data (which, as stated above, we can approximate with cross-validation). Regardless of the cross-validation flavor we choose — K-fold or LOO — we can obtain an expected log predicted density (ELPD) value for each out-of-sample datapoint (see here for an intuitive example). In general, higher ELPD values indicate better model performance." }, { "code": null, "e": 14542, "s": 14406, "text": "Although it might sound counterintuitive, in a Bayesian setting computing K-fold CV can be less efficient and more complex than LOO CV." }, { "code": null, "e": 14888, "s": 14542, "text": "Now, using K-fold might seem like a no-brainer compared to LOO given it generally leads to lower variance (especially when data is correlated), and can be less computationally expensive. However, in a Bayesian setting we have ways to approximate LOO values without having to refit the model multiple times (e.g. the PSIS method discussed above)." }, { "code": null, "e": 15138, "s": 14888, "text": "Additionally, LOO ELPD estimates have a major advantage over K-fold ELDP values. They allow us to identify points that are hard to predict and can even be used in model comparison to identify which model best captures each out-of-sample observation." }, { "code": null, "e": 15274, "s": 15138, "text": "Let’s walk through an example of how to compare the predictive performance models using overall LOO ELPD and pointwise LOO ELPD values." }, { "code": null, "e": 15483, "s": 15274, "text": "In R, we can use loo and loo_compare functions to compare the overall performance of multiple models, as well as the pointwise differences between a pair of models. (Note: loo also provides a kfold function.)" }, { "code": null, "e": 15600, "s": 15483, "text": "In Python, we can use the PyMC compare and loo functions to obtain the same overall and pointwise model comparisons." }, { "code": null, "e": 15838, "s": 15600, "text": "Below are the outputs from the code above. Models with best overall performance are commonly listed first and have the smallest ( d_loo ) and largest ( elpd_loo ). In our case, the random intercept model has the best overall performance." }, { "code": null, "e": 16317, "s": 15838, "text": "Now, as I mentioned above we can obtain pointwise ELPD estimates regardless of the CV method of our choosing which allows us to compare models more granularly. The values plotted below are the differences between the ELPD values from the random intercept model minus those of the linear regression. Here we see the random intercept model has better overall performance (i.e. most values > 0), however, notice there are certain points where the linear regression performs better." }, { "code": null, "e": 16424, "s": 16317, "text": "The ELPD pointwise plots paired with the above Pareto-k diagnostic plots can help identify unusual points." }, { "code": null, "e": 16586, "s": 16424, "text": "Now that we’ve covered all the ins and outs of the ways Bayesian models can be evaluated, let’s apply these techniques to the three models from my previous post." }, { "code": null, "e": 16740, "s": 16586, "text": "First, we compare at the posterior predictive densities of our models. Here we observe that the linear mixed models tend to better fit the observed data." }, { "code": null, "e": 17080, "s": 16740, "text": "Similarly, we’d want to look at some posterior test statistics, keeping in mind that statistics related to our model parameters might not be as useful for detecting model misspecification. Below, observe how the mean fails to capture the lack-of-fit of the linear regression while the skewness coefficient clearly shows a misspecification." }, { "code": null, "e": 17305, "s": 17080, "text": "We can also look at the county-specific test statistics to identify potential lack-of-fit. Below we observe that the mixed models also tend to capture the county medians (thick lines) better than the linear regression model." }, { "code": null, "e": 17559, "s": 17305, "text": "Next, looking at the LOO-PIT diagnostic we see no lack-of-fit for any of our models given all PIT values (thick lines) follow probable random uniform samples (thin lines). However, as discussed above, there seems to be some sticky points for all models." }, { "code": null, "e": 17925, "s": 17559, "text": "The linear regression seems to present under-dispersion (i.e. values concentrating towards 1) while the mixed models present some over-dispersion (i.e. values concentrating towards 0.5). This provides hints that further modeling effort could focus on narrowing the univariate posterior predictive distributions in the mixed models to better capture the uncertainty." }, { "code": null, "e": 18110, "s": 17925, "text": "Now, looking at the predictive performance between models using the ELPD information criteria we see that the random intercept model seems to be the best model (i.e. elpd_diff = 0.0 )." }, { "code": null, "e": 18258, "s": 18110, "text": "## elpd_diff se_diff## bayes_rintercept 0.0 0.0 ## bayes_rslope -1.3 0.3 ## lin_reg -347.8 18.8" }, { "code": null, "e": 18827, "s": 18258, "text": "We can look at the pointwise differences between the random intercept model and the other two to see where it performs better (i.e. ELPD_rand_int_i — ELDP_other_model_i ). The top diagrams shows the random intercept model performs better than the linear regression for most points ( ELPD Pointwise Diff > 0 ) and thus the large difference in model performance above. A similar comparison between the mixed models demonstrates their similar performance but we can also use this analysis to identify observations that are harder to predict (e.g. those in Dorset county)." }, { "code": null, "e": 19032, "s": 18827, "text": "Finally, looking at the indices of those hard-to-predict observations in the Pareto-k diagnostic we can see the random intercept model is able to better resolve these observations (i.e. smaller k̂ value)." }, { "code": null, "e": 19293, "s": 19032, "text": "Congrats, you’ve reached the Bayesian lands! You should feel proud of yourself at this point. Having to tread through all that material can be daunting but hopefully you’ve gained a better understanding and some intuition about how to evaluate Bayesian models." }, { "code": null, "e": 19591, "s": 19293, "text": "From the analysis above we see that the best model for this data is the random intercept one. It not only shows good predictive performance but also shows a good fit for our data. So as a final step, let’s look at our inferences and answers our initial question: “How does age affect bounce time?”" }, { "code": null, "e": 19756, "s": 19591, "text": "The table below provides a summary of some fixed effects and within-/between-group variance estimate with 95% credible intervals. Two important things to note here:" }, { "code": null, "e": 19851, "s": 19756, "text": "Given the 95% intervals don’t contain 0, we’re confident that all these estimates are non-zero" }, { "code": null, "e": 20090, "s": 19851, "text": "Related to our original question, the effect of age on bounce time is about 1.8. Since we center-scaled our variable, the effect will be positive or negative relative to whether we’re considering deviations above or below the average age." }, { "code": null, "e": 20197, "s": 20090, "text": "You can achieve summary tables like these using tidybayes in R or PyMC3’s pm.summary() function in Python." }, { "code": null, "e": 20776, "s": 20197, "text": "A very useful approach for understanding the estimated differences amongst groups is to visualize the random effects. Below we see that cheshire, cumbria, essex, and kent tend to have higher average bounce times while london and norfolk have lower ones. We can’t say that for dorset and devon since their 95% intervals contain zero and thus we can’t be certain the bounce rates in these counties deviate from the population average. One thing to note is how our Bayesian framework is able to capture uncertainty even in counties with smaller sample sizes (i.e. kent and essex )." }, { "code": null, "e": 20882, "s": 20776, "text": "Using tidybayes in R or PyMC3’s pm.foresplot() function in Python you can achieve these very nice visuals" }, { "code": null, "e": 21090, "s": 20882, "text": "We observe that counties with larger sample sizes have narrower intervals around the fits (e.g. cheshire) while smaller ones have wider intervals (e.g. kent). Finally, we can check the fits against the data." }, { "code": null, "e": 21242, "s": 21090, "text": "Using tidybayes in R you can achieve these very nice visuals quite easily, in Python it can be more tedious but still possible with seaborn and pandas." }, { "code": null, "e": 21695, "s": 21242, "text": "Evaluating Bayesian models follows many of the same goodness-of-fit testing and performance comparison steps as for any other model you’d encounter. However, there are tools and concepts that are particularly useful for assessing Bayesian models. Some are quite complex and it can feel daunting to use them if you’re unfamiliar with what their outputs mean. (There’s nothing more distressing than not being able to understand a model’s output summary.)" }, { "code": null, "e": 21826, "s": 21695, "text": "Luckily there are visual ways of diagnosing model fit, evaluating performance, and even interpreting results from Bayesian models." }, { "code": null, "e": 21988, "s": 21826, "text": "I hope this part 2 on Bayesian mixed models has continued to build your intuition about Bayesian modeling such that it becomes a powerful method in your toolset." }, { "code": null, "e": 22011, "s": 21988, "text": "towardsdatascience.com" }, { "code": null, "e": 22034, "s": 22011, "text": "towardsdatascience.com" }, { "code": null, "e": 22660, "s": 22034, "text": "Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., & Rubin, D. B. (2013). Bayesian data analysis. CRC press.Gabry, Jonah, et al. “Visualization in Bayesian workflow.” Journal of the Royal Statistical Society: Series A (Statistics in Society) 182.2 (2019): 389–402.Gelman, Andrew, Jessica Hwang, and Aki Vehtari. “Understanding predictive information criteria for Bayesian models.” Statistics and computing 24.6 (2014): 997–1016.Vehtari, Aki, Andrew Gelman, and Jonah Gabry. “Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC.” Statistics and computing 27.5 (2017): 1413–1432." }, { "code": null, "e": 22787, "s": 22660, "text": "Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., & Rubin, D. B. (2013). Bayesian data analysis. CRC press." }, { "code": null, "e": 22944, "s": 22787, "text": "Gabry, Jonah, et al. “Visualization in Bayesian workflow.” Journal of the Royal Statistical Society: Series A (Statistics in Society) 182.2 (2019): 389–402." }, { "code": null, "e": 23109, "s": 22944, "text": "Gelman, Andrew, Jessica Hwang, and Aki Vehtari. “Understanding predictive information criteria for Bayesian models.” Statistics and computing 24.6 (2014): 997–1016." }, { "code": null, "e": 23289, "s": 23109, "text": "Vehtari, Aki, Andrew Gelman, and Jonah Gabry. “Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC.” Statistics and computing 27.5 (2017): 1413–1432." }, { "code": null, "e": 23437, "s": 23289, "text": "If you liked the article feel free to share! Comment or tweet (@ecoronado92) if you have any questions, or you see anything incorrect/questionable." }, { "code": null, "e": 23466, "s": 23437, "text": "All R code can be found here" } ]
Largest K digit number divisible by all numbers in given array
15 Dec, 2021 Given an array arr[] of size N and an integer K. The task is to find the largest K digit number divisible by all number of arr[]. Examples: Input: arr[] = {2, 3, 5}, K = 3Output: 990Explanation: 990 is the largest 3 digit number divisible by 2, 3 and 5. Input: arr[] = {91, 93, 95}, K = 3Output: -1Explanation: There is no 3 digit number divisible by all 91, 93 and 95. Approach: The solution is based on the idea similar to finding largest K digit number divisible by X. Follow the steps mentioned below. Find LCM of all numbers of array arr[] Find the largest multiple of LCM having K digits using the formula: LCM(arr) * ((10K-1)/LCM(arr)) Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ code to implement above approach#include <bits/stdc++.h>using namespace std; int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // Base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Function to find LCM of the array int findLCM(int arr[], int n, int idx) { // lcm(a, b) = (a*b / gcd(a, b)) if (idx == n - 1) { return arr[idx]; } int a = arr[idx]; int b = findLCM(arr, n, idx + 1); double gcd = __gcd(a, b); return (a * (int)floor(b / gcd)); } // Function to find the number int findNum(int arr[], int n, int K) { int lcm = findLCM(arr, n, 0); int ans = (int)floor((pow(10, K) - 1) / lcm); ans = (ans) * lcm; if (ans == 0) return -1; return ans; } // Driver code int main() { int arr[] = { 2, 3, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 3; cout << findNum(arr, n, K); } // This code is contributed by Samim Hossain Mondal. // Java code to implement above approachclass GFG{ static int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // Base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Function to find LCM of the array static int findLCM(int []arr, int idx) { // lcm(a, b) = (a*b / gcd(a, b)) if (idx == arr.length - 1) { return arr[idx]; } int a = arr[idx]; int b = findLCM(arr, idx + 1); double gcd = __gcd(a, b); return (a * (int)Math.floor(b / gcd)); } // Function to find the number static int findNum(int []arr, int K) { int lcm = findLCM(arr, 0); int ans = (int)Math.floor((Math.pow(10, K) - 1) / lcm); ans = (ans) * lcm; if (ans == 0) return -1; return ans; } // Driver code public static void main(String []args) { int []arr = { 2, 3, 5 }; int K = 3; System.out.println(findNum(arr, K)); }} // This code is contributed by 29AjayKumar # python code to implement above approachimport math # Function to find LCM of the arraydef findLCM(arr, idx): # lcm(a, b) = (a*b / gcd(a, b)) if (idx == len(arr) - 1): return arr[idx] a = arr[idx] b = findLCM(arr, idx + 1) return (a * b // math.gcd(a, b)) # Function to find the numberdef findNum(arr, K): lcm = findLCM(arr, 0) ans = (pow(10, K) - 1) // lcm ans = (ans)*lcm if (ans == 0): return -1 return ans # Driver codeif __name__ == "__main__": arr = [2, 3, 5] K = 3 print(findNum(arr, K)) # This code is contributed by rakeshsahni // C# code to implement above approachusing System;using System.Collections;class GFG{static int __gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // Base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Function to find LCM of the arraystatic int findLCM(int []arr, int idx){ // lcm(a, b) = (a*b / gcd(a, b)) if (idx == arr.Length - 1) { return arr[idx]; } int a = arr[idx]; int b = findLCM(arr, idx + 1); double gcd = __gcd(a, b); return (a * (int)Math.Floor(b / gcd));} // Function to find the numberstatic int findNum(int []arr, int K){ int lcm = findLCM(arr, 0); int ans = (int)Math.Floor((Math.Pow(10, K) - 1) / lcm); ans = (ans) * lcm; if (ans == 0) return -1; return ans;} // Driver codepublic static void Main(){int []arr = { 2, 3, 5 };int K = 3; Console.Write(findNum(arr, K));}} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript code to implement above approachfunction __gcd(a, b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // Base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Function to find LCM of the arrayfunction findLCM(arr, idx){ // lcm(a, b) = (a*b / gcd(a, b)) if (idx == arr.length - 1) { return arr[idx]; } let a = arr[idx]; let b = findLCM(arr, idx + 1); return Math.floor((a * b / __gcd(a, b)));} // Function to find the numberfunction findNum(arr, K){ let lcm = findLCM(arr, 0); let ans = Math.floor((Math.pow(10, K) - 1) / lcm); ans = (ans) * lcm; if (ans == 0) return -1; return ans;} // Driver codelet arr = [ 2, 3, 5 ];let K = 3; document.write(findNum(arr, K)); // This code is contributed by Potta Lokesh </script> 990 Time Complexity: O(N*logD) where D is the maximum element of the arrayAuxiliary Space: O(1) lokeshpotta20 rakeshsahni samim2000 29AjayKumar GCD-LCM Arrays Greedy Mathematical Arrays Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Write a program to print all permutations of a given string Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Dec, 2021" }, { "code": null, "e": 158, "s": 28, "text": "Given an array arr[] of size N and an integer K. The task is to find the largest K digit number divisible by all number of arr[]." }, { "code": null, "e": 168, "s": 158, "text": "Examples:" }, { "code": null, "e": 282, "s": 168, "text": "Input: arr[] = {2, 3, 5}, K = 3Output: 990Explanation: 990 is the largest 3 digit number divisible by 2, 3 and 5." }, { "code": null, "e": 398, "s": 282, "text": "Input: arr[] = {91, 93, 95}, K = 3Output: -1Explanation: There is no 3 digit number divisible by all 91, 93 and 95." }, { "code": null, "e": 534, "s": 398, "text": "Approach: The solution is based on the idea similar to finding largest K digit number divisible by X. Follow the steps mentioned below." }, { "code": null, "e": 573, "s": 534, "text": "Find LCM of all numbers of array arr[]" }, { "code": null, "e": 641, "s": 573, "text": "Find the largest multiple of LCM having K digits using the formula:" }, { "code": null, "e": 671, "s": 641, "text": "LCM(arr) * ((10K-1)/LCM(arr))" }, { "code": null, "e": 722, "s": 671, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 726, "s": 722, "text": "C++" }, { "code": null, "e": 731, "s": 726, "text": "Java" }, { "code": null, "e": 739, "s": 731, "text": "Python3" }, { "code": null, "e": 742, "s": 739, "text": "C#" }, { "code": null, "e": 753, "s": 742, "text": "Javascript" }, { "code": "// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // Base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Function to find LCM of the array int findLCM(int arr[], int n, int idx) { // lcm(a, b) = (a*b / gcd(a, b)) if (idx == n - 1) { return arr[idx]; } int a = arr[idx]; int b = findLCM(arr, n, idx + 1); double gcd = __gcd(a, b); return (a * (int)floor(b / gcd)); } // Function to find the number int findNum(int arr[], int n, int K) { int lcm = findLCM(arr, n, 0); int ans = (int)floor((pow(10, K) - 1) / lcm); ans = (ans) * lcm; if (ans == 0) return -1; return ans; } // Driver code int main() { int arr[] = { 2, 3, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 3; cout << findNum(arr, n, K); } // This code is contributed by Samim Hossain Mondal.", "e": 1834, "s": 753, "text": null }, { "code": "// Java code to implement above approachclass GFG{ static int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // Base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Function to find LCM of the array static int findLCM(int []arr, int idx) { // lcm(a, b) = (a*b / gcd(a, b)) if (idx == arr.length - 1) { return arr[idx]; } int a = arr[idx]; int b = findLCM(arr, idx + 1); double gcd = __gcd(a, b); return (a * (int)Math.floor(b / gcd)); } // Function to find the number static int findNum(int []arr, int K) { int lcm = findLCM(arr, 0); int ans = (int)Math.floor((Math.pow(10, K) - 1) / lcm); ans = (ans) * lcm; if (ans == 0) return -1; return ans; } // Driver code public static void main(String []args) { int []arr = { 2, 3, 5 }; int K = 3; System.out.println(findNum(arr, K)); }} // This code is contributed by 29AjayKumar", "e": 2890, "s": 1834, "text": null }, { "code": "# python code to implement above approachimport math # Function to find LCM of the arraydef findLCM(arr, idx): # lcm(a, b) = (a*b / gcd(a, b)) if (idx == len(arr) - 1): return arr[idx] a = arr[idx] b = findLCM(arr, idx + 1) return (a * b // math.gcd(a, b)) # Function to find the numberdef findNum(arr, K): lcm = findLCM(arr, 0) ans = (pow(10, K) - 1) // lcm ans = (ans)*lcm if (ans == 0): return -1 return ans # Driver codeif __name__ == \"__main__\": arr = [2, 3, 5] K = 3 print(findNum(arr, K)) # This code is contributed by rakeshsahni", "e": 3485, "s": 2890, "text": null }, { "code": "// C# code to implement above approachusing System;using System.Collections;class GFG{static int __gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // Base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Function to find LCM of the arraystatic int findLCM(int []arr, int idx){ // lcm(a, b) = (a*b / gcd(a, b)) if (idx == arr.Length - 1) { return arr[idx]; } int a = arr[idx]; int b = findLCM(arr, idx + 1); double gcd = __gcd(a, b); return (a * (int)Math.Floor(b / gcd));} // Function to find the numberstatic int findNum(int []arr, int K){ int lcm = findLCM(arr, 0); int ans = (int)Math.Floor((Math.Pow(10, K) - 1) / lcm); ans = (ans) * lcm; if (ans == 0) return -1; return ans;} // Driver codepublic static void Main(){int []arr = { 2, 3, 5 };int K = 3; Console.Write(findNum(arr, K));}} // This code is contributed by Samim Hossain Mondal.", "e": 4575, "s": 3485, "text": null }, { "code": "<script> // JavaScript code to implement above approachfunction __gcd(a, b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // Base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Function to find LCM of the arrayfunction findLCM(arr, idx){ // lcm(a, b) = (a*b / gcd(a, b)) if (idx == arr.length - 1) { return arr[idx]; } let a = arr[idx]; let b = findLCM(arr, idx + 1); return Math.floor((a * b / __gcd(a, b)));} // Function to find the numberfunction findNum(arr, K){ let lcm = findLCM(arr, 0); let ans = Math.floor((Math.pow(10, K) - 1) / lcm); ans = (ans) * lcm; if (ans == 0) return -1; return ans;} // Driver codelet arr = [ 2, 3, 5 ];let K = 3; document.write(findNum(arr, K)); // This code is contributed by Potta Lokesh </script>", "e": 5530, "s": 4575, "text": null }, { "code": null, "e": 5534, "s": 5530, "text": "990" }, { "code": null, "e": 5626, "s": 5534, "text": "Time Complexity: O(N*logD) where D is the maximum element of the arrayAuxiliary Space: O(1)" }, { "code": null, "e": 5642, "s": 5628, "text": "lokeshpotta20" }, { "code": null, "e": 5654, "s": 5642, "text": "rakeshsahni" }, { "code": null, "e": 5664, "s": 5654, "text": "samim2000" }, { "code": null, "e": 5676, "s": 5664, "text": "29AjayKumar" }, { "code": null, "e": 5684, "s": 5676, "text": "GCD-LCM" }, { "code": null, "e": 5691, "s": 5684, "text": "Arrays" }, { "code": null, "e": 5698, "s": 5691, "text": "Greedy" }, { "code": null, "e": 5711, "s": 5698, "text": "Mathematical" }, { "code": null, "e": 5718, "s": 5711, "text": "Arrays" }, { "code": null, "e": 5725, "s": 5718, "text": "Greedy" }, { "code": null, "e": 5738, "s": 5725, "text": "Mathematical" }, { "code": null, "e": 5836, "s": 5738, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5868, "s": 5836, "text": "Introduction to Data Structures" }, { "code": null, "e": 5893, "s": 5868, "text": "Window Sliding Technique" }, { "code": null, "e": 5940, "s": 5893, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 6004, "s": 5940, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 6035, "s": 6004, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 6086, "s": 6035, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 6137, "s": 6086, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 6197, "s": 6137, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 6255, "s": 6197, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
value_of_css_property() element method – Selenium Python
27 Apr, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies This article revolves around how to use value_of_css_property method in Selenium. value_of_css_property method is used to get value of a css property for a element. element.clear() Example – <input type="text" name="passwd" style="font-size:120px" id="passwd-id" /> To find an element one needs to use one of the locating strategies, For example, element = driver.find_element_by_id("passwd-id") element = driver.find_element_by_name("passwd") element = driver.find_element_by_xpath("//input[@id='passwd-id']") Also, to find multiple elements, we can use – elements = driver.find_elements_by_name("passwd") Now one can get this field’s css properties with element.value_of_css_property('font-size') Let’s try to get value_of_css_property of search field on geeksforgeeks.Program – # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_id("gsc-i-id2") # print widthprint(element.value_of_css_property('width')) Output- Terminal Output – 161px Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Apr, 2020" }, { "code": null, "e": 585, "s": 28, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies" }, { "code": null, "e": 750, "s": 585, "text": "This article revolves around how to use value_of_css_property method in Selenium. value_of_css_property method is used to get value of a css property for a element." }, { "code": null, "e": 766, "s": 750, "text": "element.clear()" }, { "code": null, "e": 776, "s": 766, "text": "Example –" }, { "code": "<input type=\"text\" name=\"passwd\" style=\"font-size:120px\" id=\"passwd-id\" />", "e": 851, "s": 776, "text": null }, { "code": null, "e": 932, "s": 851, "text": "To find an element one needs to use one of the locating strategies, For example," }, { "code": null, "e": 1096, "s": 932, "text": "element = driver.find_element_by_id(\"passwd-id\")\nelement = driver.find_element_by_name(\"passwd\")\nelement = driver.find_element_by_xpath(\"//input[@id='passwd-id']\")" }, { "code": null, "e": 1142, "s": 1096, "text": "Also, to find multiple elements, we can use –" }, { "code": null, "e": 1192, "s": 1142, "text": "elements = driver.find_elements_by_name(\"passwd\")" }, { "code": null, "e": 1241, "s": 1192, "text": "Now one can get this field’s css properties with" }, { "code": null, "e": 1284, "s": 1241, "text": "element.value_of_css_property('font-size')" }, { "code": null, "e": 1366, "s": 1284, "text": "Let’s try to get value_of_css_property of search field on geeksforgeeks.Program –" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_id(\"gsc-i-id2\") # print widthprint(element.value_of_css_property('width'))", "e": 1665, "s": 1366, "text": null }, { "code": null, "e": 1673, "s": 1665, "text": "Output-" }, { "code": null, "e": 1691, "s": 1673, "text": "Terminal Output –" }, { "code": null, "e": 1697, "s": 1691, "text": "161px" }, { "code": null, "e": 1713, "s": 1697, "text": "Python-selenium" }, { "code": null, "e": 1722, "s": 1713, "text": "selenium" }, { "code": null, "e": 1729, "s": 1722, "text": "Python" } ]
Lazy import in Python
11 May, 2021 In this article, we will learn how to do Lazy import in Python. For this, let’s first understand the lazy import. It is a feature of the Pyforest module that allows the user to perform the task without adding libraries to the code snippet as the task of this function is to add those libraries themselves into the code snippet. It was designed for the users who are tired of writing those import statements in the program. It is very useful for the developers who need to write long lengthy codes it gives an edge to them. As a Python user, we often face the problem of importing multiple modules such as NumPy, pandas, sklearn, nltk, os, sys, pickle, and many others in every program every time which is actually annoying and irritating as we are doing some work which is no benefit, rather is a wastage of time and if any time we forgot to import any module in the program then the program gives an error, and we don’t want our program to crash just because of the modules. So Pyforest has made a solution for this problem by creating an in-built function that has the details of almost 99% of the popular modules of Python which identifies the imports we are using and automatically adds the module for the program so that we don’t need to do that again and again. This way it is easier and faster because we can use the pre-installed modules without importing them into different programs, and it also doesn’t add all the modules it checks the program and only the used modules will be added, so there is no such a disadvantage at the ease that we do not need to add those modules, again and again, our work gets done by adding just a single module. Example: Let’s write some code of lines, and we don’t import the required module. This is our simple and continuous habit. Python3 # forget to import numpy # using numpyarray = np.array([1, 2, 3])print(array) If we run the above piece of code we will get the following error : Now, we get the error as the module is not imported. In this similar way, we forget to import the required modules in big lines of codes. To import we have to write importing statements for each and every module used in our code. So, do this in one line we use lazy_import from pyforest module. For the installation process to begin we need to have python installed on our device, then we need to open the command prompt and write the following command in the prompt to install the ‘pyforest’ module which gives us the functionality of the lazy_module(). Installation: pip install pyforest Installation/Upgradation: pip install --upgrade pyforest To see the import function in pyforest module we can print the lazy_modules() function: Python3 import pyforest print(lazy_imports()) Output: So we can see in the above output what all modules are existing in the pyforest library which is available for use without importing multiple times. This was just one line but if we had to import a lot of modules we will have to focus more on importing modules rather than writing the code. So here Pyforest solves the problem. Just add one module ‘import pyforest’ and we are ready to go. Example 1: Python3 # forget to import numpy# nut importing pyforestimport pyforest # using numpyarray = np.array([1, 2, 3])print(array) print(active_imports()) Output: [1 2 3] import numpy as np ['import numpy as np'] Example 2: Python3 # forget to import numpy, matplotlib# but importing pyforestimport pyforest # using numpyarray = np.array([1, 2, 3]) # using matplotlib.pyplotplt.plot(array) print(active_imports()) Output: Lazy import is a very useful feature of the Pyforest library as this feature automatically imports the library for us, if we don’t use the library it won’t be added. This feature is very useful to those who don’t want to write the import statements again and again in their code. The main benefit of this library is that it contains most of the libraries, and we can use the library as we like anytime without importing that library as the lazy import feature will do it for us. It resolved the problem of importing libraries in the code snippet. It automatically sets the variable name as per the usage to avoid any error for libraries. Libraries will only be imported when you use them, no extra libraries will be added to reduce compilation time. It contains nearly 99% of the available Python libraries, which makes it easier to use as no extra library is needed. Its implementation is easy and the rest is done automatically Picked python-modules Python 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 How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 54, "s": 26, "text": "\n11 May, 2021" }, { "code": null, "e": 168, "s": 54, "text": "In this article, we will learn how to do Lazy import in Python. For this, let’s first understand the lazy import." }, { "code": null, "e": 577, "s": 168, "text": "It is a feature of the Pyforest module that allows the user to perform the task without adding libraries to the code snippet as the task of this function is to add those libraries themselves into the code snippet. It was designed for the users who are tired of writing those import statements in the program. It is very useful for the developers who need to write long lengthy codes it gives an edge to them." }, { "code": null, "e": 1031, "s": 577, "text": "As a Python user, we often face the problem of importing multiple modules such as NumPy, pandas, sklearn, nltk, os, sys, pickle, and many others in every program every time which is actually annoying and irritating as we are doing some work which is no benefit, rather is a wastage of time and if any time we forgot to import any module in the program then the program gives an error, and we don’t want our program to crash just because of the modules. " }, { "code": null, "e": 1709, "s": 1031, "text": "So Pyforest has made a solution for this problem by creating an in-built function that has the details of almost 99% of the popular modules of Python which identifies the imports we are using and automatically adds the module for the program so that we don’t need to do that again and again. This way it is easier and faster because we can use the pre-installed modules without importing them into different programs, and it also doesn’t add all the modules it checks the program and only the used modules will be added, so there is no such a disadvantage at the ease that we do not need to add those modules, again and again, our work gets done by adding just a single module." }, { "code": null, "e": 1718, "s": 1709, "text": "Example:" }, { "code": null, "e": 1832, "s": 1718, "text": "Let’s write some code of lines, and we don’t import the required module. This is our simple and continuous habit." }, { "code": null, "e": 1840, "s": 1832, "text": "Python3" }, { "code": "# forget to import numpy # using numpyarray = np.array([1, 2, 3])print(array)", "e": 1919, "s": 1840, "text": null }, { "code": null, "e": 1988, "s": 1919, "text": "If we run the above piece of code we will get the following error : " }, { "code": null, "e": 2283, "s": 1988, "text": "Now, we get the error as the module is not imported. In this similar way, we forget to import the required modules in big lines of codes. To import we have to write importing statements for each and every module used in our code. So, do this in one line we use lazy_import from pyforest module." }, { "code": null, "e": 2543, "s": 2283, "text": "For the installation process to begin we need to have python installed on our device, then we need to open the command prompt and write the following command in the prompt to install the ‘pyforest’ module which gives us the functionality of the lazy_module()." }, { "code": null, "e": 2638, "s": 2543, "text": "Installation: \npip install pyforest\n\nInstallation/Upgradation: \npip install --upgrade pyforest" }, { "code": null, "e": 2726, "s": 2638, "text": "To see the import function in pyforest module we can print the lazy_modules() function:" }, { "code": null, "e": 2734, "s": 2726, "text": "Python3" }, { "code": "import pyforest print(lazy_imports())", "e": 2775, "s": 2734, "text": null }, { "code": null, "e": 2783, "s": 2775, "text": "Output:" }, { "code": null, "e": 2932, "s": 2783, "text": "So we can see in the above output what all modules are existing in the pyforest library which is available for use without importing multiple times." }, { "code": null, "e": 3173, "s": 2932, "text": "This was just one line but if we had to import a lot of modules we will have to focus more on importing modules rather than writing the code. So here Pyforest solves the problem. Just add one module ‘import pyforest’ and we are ready to go." }, { "code": null, "e": 3184, "s": 3173, "text": "Example 1:" }, { "code": null, "e": 3192, "s": 3184, "text": "Python3" }, { "code": "# forget to import numpy# nut importing pyforestimport pyforest # using numpyarray = np.array([1, 2, 3])print(array) print(active_imports())", "e": 3335, "s": 3192, "text": null }, { "code": null, "e": 3343, "s": 3335, "text": "Output:" }, { "code": null, "e": 3393, "s": 3343, "text": "[1 2 3]\nimport numpy as np\n['import numpy as np']" }, { "code": null, "e": 3404, "s": 3393, "text": "Example 2:" }, { "code": null, "e": 3412, "s": 3404, "text": "Python3" }, { "code": "# forget to import numpy, matplotlib# but importing pyforestimport pyforest # using numpyarray = np.array([1, 2, 3]) # using matplotlib.pyplotplt.plot(array) print(active_imports())", "e": 3597, "s": 3412, "text": null }, { "code": null, "e": 3605, "s": 3597, "text": "Output:" }, { "code": null, "e": 4086, "s": 3605, "text": "Lazy import is a very useful feature of the Pyforest library as this feature automatically imports the library for us, if we don’t use the library it won’t be added. This feature is very useful to those who don’t want to write the import statements again and again in their code. The main benefit of this library is that it contains most of the libraries, and we can use the library as we like anytime without importing that library as the lazy import feature will do it for us. " }, { "code": null, "e": 4154, "s": 4086, "text": "It resolved the problem of importing libraries in the code snippet." }, { "code": null, "e": 4245, "s": 4154, "text": "It automatically sets the variable name as per the usage to avoid any error for libraries." }, { "code": null, "e": 4357, "s": 4245, "text": "Libraries will only be imported when you use them, no extra libraries will be added to reduce compilation time." }, { "code": null, "e": 4475, "s": 4357, "text": "It contains nearly 99% of the available Python libraries, which makes it easier to use as no extra library is needed." }, { "code": null, "e": 4537, "s": 4475, "text": "Its implementation is easy and the rest is done automatically" }, { "code": null, "e": 4544, "s": 4537, "text": "Picked" }, { "code": null, "e": 4559, "s": 4544, "text": "python-modules" }, { "code": null, "e": 4566, "s": 4559, "text": "Python" }, { "code": null, "e": 4664, "s": 4566, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4696, "s": 4664, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4723, "s": 4696, "text": "Python Classes and Objects" }, { "code": null, "e": 4744, "s": 4723, "text": "Python OOPs Concepts" }, { "code": null, "e": 4767, "s": 4744, "text": "Introduction To PYTHON" }, { "code": null, "e": 4823, "s": 4767, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4854, "s": 4823, "text": "Python | os.path.join() method" }, { "code": null, "e": 4896, "s": 4854, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4938, "s": 4896, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4977, "s": 4938, "text": "Python | Get unique values from a list" } ]
BigDecimal equals() Method in Java
04 Dec, 2018 The java.math.BigDecimal.equals() method checks for equality of a BigDecimal value with the object passed. This method considers two BigDecimal objects equal if only if they are equal in value and scale. Syntax: public boolean equals(Object obj) Parameters: This function accepts an Object obj as a mandatory parameter for comparison with this BigDecimal object. Return Value: This method returns boolean true if and only if the Object passed as parameter is a BigDecimal whose value and scale are equal to that of this BigDecimal object and returns false otherwise. Thus, this function does not return true when it compares 124.0 and 124.0000. Examples: Input: b1 = new BigDecimal("4743.00") b2 = new BigDecimal("4743.00000") Output: false Input: b1 = new BigDecimal(4743) b2 = new BigDecimal("4743") Output: true Below programs illustrate equals() method of BigDecimal class:Program 1: // Java program to demonstrate equals() method import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating 2 BigDecimal objects BigDecimal b1, b2; b1 = new BigDecimal("4743.00"); b2 = new BigDecimal("4743.00000"); if (b1.equals(b2)) { System.out.println(b1 + " and " + b2 + " are equal."); } else { System.out.println(b1 + " and " + b2 + " are not equal."); } }} 4743.00 and 4743.00000 are not equal. Program 2: // Java program to demonstrate equals() method import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating 2 BigDecimal objects BigDecimal b1, b2; b1 = new BigDecimal(67891); b2 = new BigDecimal("67891"); if (b1.equals(b2)) { System.out.println(b1 + " and " + b2 + " are equal."); } else { System.out.println(b1 + " and " + b2 + " are not equal."); } }} 67891 and 67891 are equal. Java-BigDecimal Java-Functions java-math Java-math-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. List Interface in Java with Examples Strings in Java Different ways of Reading a text file in Java Reverse an array in Java How to remove an element from ArrayList in Java? Checked vs Unchecked Exceptions in Java ArrayList get(index) Method in Java with Examples ArrayList to Array Conversion in Java : toArray() Methods Comparator Interface in Java with Examples Exceptions in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Dec, 2018" }, { "code": null, "e": 232, "s": 28, "text": "The java.math.BigDecimal.equals() method checks for equality of a BigDecimal value with the object passed. This method considers two BigDecimal objects equal if only if they are equal in value and scale." }, { "code": null, "e": 240, "s": 232, "text": "Syntax:" }, { "code": null, "e": 274, "s": 240, "text": "public boolean equals(Object obj)" }, { "code": null, "e": 391, "s": 274, "text": "Parameters: This function accepts an Object obj as a mandatory parameter for comparison with this BigDecimal object." }, { "code": null, "e": 673, "s": 391, "text": "Return Value: This method returns boolean true if and only if the Object passed as parameter is a BigDecimal whose value and scale are equal to that of this BigDecimal object and returns false otherwise. Thus, this function does not return true when it compares 124.0 and 124.0000." }, { "code": null, "e": 683, "s": 673, "text": "Examples:" }, { "code": null, "e": 847, "s": 683, "text": "Input: \nb1 = new BigDecimal(\"4743.00\")\nb2 = new BigDecimal(\"4743.00000\")\nOutput: false\n\nInput: \nb1 = new BigDecimal(4743)\nb2 = new BigDecimal(\"4743\")\nOutput: true\n" }, { "code": null, "e": 920, "s": 847, "text": "Below programs illustrate equals() method of BigDecimal class:Program 1:" }, { "code": "// Java program to demonstrate equals() method import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating 2 BigDecimal objects BigDecimal b1, b2; b1 = new BigDecimal(\"4743.00\"); b2 = new BigDecimal(\"4743.00000\"); if (b1.equals(b2)) { System.out.println(b1 + \" and \" + b2 + \" are equal.\"); } else { System.out.println(b1 + \" and \" + b2 + \" are not equal.\"); } }}", "e": 1429, "s": 920, "text": null }, { "code": null, "e": 1468, "s": 1429, "text": "4743.00 and 4743.00000 are not equal.\n" }, { "code": null, "e": 1479, "s": 1468, "text": "Program 2:" }, { "code": "// Java program to demonstrate equals() method import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating 2 BigDecimal objects BigDecimal b1, b2; b1 = new BigDecimal(67891); b2 = new BigDecimal(\"67891\"); if (b1.equals(b2)) { System.out.println(b1 + \" and \" + b2 + \" are equal.\"); } else { System.out.println(b1 + \" and \" + b2 + \" are not equal.\"); } }}", "e": 1979, "s": 1479, "text": null }, { "code": null, "e": 2007, "s": 1979, "text": "67891 and 67891 are equal.\n" }, { "code": null, "e": 2023, "s": 2007, "text": "Java-BigDecimal" }, { "code": null, "e": 2038, "s": 2023, "text": "Java-Functions" }, { "code": null, "e": 2048, "s": 2038, "text": "java-math" }, { "code": null, "e": 2066, "s": 2048, "text": "Java-math-package" }, { "code": null, "e": 2071, "s": 2066, "text": "Java" }, { "code": null, "e": 2076, "s": 2071, "text": "Java" }, { "code": null, "e": 2174, "s": 2076, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2211, "s": 2174, "text": "List Interface in Java with Examples" }, { "code": null, "e": 2227, "s": 2211, "text": "Strings in Java" }, { "code": null, "e": 2273, "s": 2227, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 2298, "s": 2273, "text": "Reverse an array in Java" }, { "code": null, "e": 2347, "s": 2298, "text": "How to remove an element from ArrayList in Java?" }, { "code": null, "e": 2387, "s": 2347, "text": "Checked vs Unchecked Exceptions in Java" }, { "code": null, "e": 2437, "s": 2387, "text": "ArrayList get(index) Method in Java with Examples" }, { "code": null, "e": 2495, "s": 2437, "text": "ArrayList to Array Conversion in Java : toArray() Methods" }, { "code": null, "e": 2538, "s": 2495, "text": "Comparator Interface in Java with Examples" } ]
Ways to remove particular List element in Python
03 Dec, 2020 List is an important container and used almost in every code of day-day programming as well as web-development. The more it is used, more is the requirement to master it and hence knowledge of its operations is necessary. Let’s see the different ways of removing particular list element. Method #1 : Using remove()remove() can perform the task of removal of list element. Its removal is inplace and does not require extra space. But the drawback that it faces is that it just removes the first occurrence from the list. All the other occurrences are not deleted hence only useful if list doesn’t contain duplicates. # Python code to demonstrate# element removal in list# using remove() method test_list1 = [1, 3, 4, 6, 3]test_list2 = [1, 4, 5, 4, 5] # Printing initial listprint ("The list before element removal is : " + str(test_list1)) # using remove() to remove list element3test_list1.remove(3) # Printing list after removal# only first occurrence deletedprint ("The list after element removal is : " + str(test_list1)) Output: The list before element removal is : [1, 3, 4, 6, 3] The list after element removal is : [1, 4, 6, 3] Method #2 : Using set.disard()set.disard() can perform the task of removal of list element. Its removal is inplace and does not require extra space. List is first converted to set, hence other duplicates are removed and also list ordering is sacrificed. Hence not a good idea when we need to preserve ordering or need to keep duplicates. # Python code to demonstrate# element removal in list# using discard() method test_list1 = [1, 3, 4, 6, 3]test_list2 = [1, 4, 5, 4, 5] # Printing initial listprint ("The list before element removal is : " + str(test_list2)) # using discard() to remove list element 4test_list2 = set(test_list2)test_list2.discard(4) test_list2 = list(test_list2) # Printing list after removal# removes element as distinct initiallyprint ("The list after element removal is : " + str(test_list2)) Output : The list before element removal is : [1, 4, 5, 4, 5] The list after element removal is : [1, 5] Method #3 : Using Lambda Function + filter()Lambda functions have always been a useful utility and hence can be used to perform tough task in just 1 liners. These can also perform this particular task. Drawback is that they are not inplace and require extra space or requires a overwrite. It actually constructs a new list, and filters out all of the required elements. It removes all the occurrences of element. # Python code to demonstrate# element removal in list# using filter() + Lambda function test_list1 = [1, 3, 4, 6, 3]test_list2 = [1, 4, 5, 4, 5] # Printing initial listprint ("The list before element removal is : " + str(test_list1)) # using filter() + Lambda function # to remove list element 3test_list1 = list(filter(lambda x: x != 3, test_list1)) # Printing list after removalprint ("The list after element removal is : " + str(test_list1)) Output: The list before element removal is : [1, 3, 4, 6, 3] The list after element removal is : [1, 4, 6] Method #4 : Using List ComprehensionList comprehensions are easier method to perform the similar task as performed by lambda function. It has the same drawback of not being inplace and also requires extra space or overwrite. It is better in a way that filter() is not required to perform it. It removes all the occurrences of element. # Python code to demonstrate# element removal in list# using List Comprehension test_list1 = [1, 3, 4, 6, 3]test_list2 = [1, 4, 5, 4, 5] # Printing initial listprint ("The list before element removal is : " + str(test_list2)) # using List Comprehension# to remove list element 4test_list2 = [x for x in test_list2 if x != 4] # Printing list after removalprint ("The list after element removal is : " + str(test_list2)) Output : The list before element removal is : [1, 4, 5, 4, 5] The list after element removal is : [1, 5, 5] Method #5 : Using pop()Using pop method with list index to pop element out of list # Python code to demonstrate# element removal in list# using pop() method test_list1 = [1, 3, 4, 6, 3] # Printing initial listprint ("The list before element removal is : " + str(test_list1)) rmv_element = 4 # using pop()# to remove list element 4if rmv_element in test_list1: test_list1.pop(test_list1.index(rmv_element)) # Printing list after removalprint ("The list after element removal is : " + str(test_list1)) # Added by Paras Jain(everythingispossible) Output : The list before element removal is : [1, 3, 4, 6, 3] The list after element removal is : [1, 3, 6, 3] everythingispossible Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2020" }, { "code": null, "e": 250, "s": 28, "text": "List is an important container and used almost in every code of day-day programming as well as web-development. The more it is used, more is the requirement to master it and hence knowledge of its operations is necessary." }, { "code": null, "e": 316, "s": 250, "text": "Let’s see the different ways of removing particular list element." }, { "code": null, "e": 644, "s": 316, "text": "Method #1 : Using remove()remove() can perform the task of removal of list element. Its removal is inplace and does not require extra space. But the drawback that it faces is that it just removes the first occurrence from the list. All the other occurrences are not deleted hence only useful if list doesn’t contain duplicates." }, { "code": "# Python code to demonstrate# element removal in list# using remove() method test_list1 = [1, 3, 4, 6, 3]test_list2 = [1, 4, 5, 4, 5] # Printing initial listprint (\"The list before element removal is : \" + str(test_list1)) # using remove() to remove list element3test_list1.remove(3) # Printing list after removal# only first occurrence deletedprint (\"The list after element removal is : \" + str(test_list1))", "e": 1111, "s": 644, "text": null }, { "code": null, "e": 1119, "s": 1111, "text": "Output:" }, { "code": null, "e": 1221, "s": 1119, "text": "The list before element removal is : [1, 3, 4, 6, 3]\nThe list after element removal is : [1, 4, 6, 3]" }, { "code": null, "e": 1560, "s": 1221, "text": " Method #2 : Using set.disard()set.disard() can perform the task of removal of list element. Its removal is inplace and does not require extra space. List is first converted to set, hence other duplicates are removed and also list ordering is sacrificed. Hence not a good idea when we need to preserve ordering or need to keep duplicates." }, { "code": "# Python code to demonstrate# element removal in list# using discard() method test_list1 = [1, 3, 4, 6, 3]test_list2 = [1, 4, 5, 4, 5] # Printing initial listprint (\"The list before element removal is : \" + str(test_list2)) # using discard() to remove list element 4test_list2 = set(test_list2)test_list2.discard(4) test_list2 = list(test_list2) # Printing list after removal# removes element as distinct initiallyprint (\"The list after element removal is : \" + str(test_list2))", "e": 2100, "s": 1560, "text": null }, { "code": null, "e": 2109, "s": 2100, "text": "Output :" }, { "code": null, "e": 2205, "s": 2109, "text": "The list before element removal is : [1, 4, 5, 4, 5]\nThe list after element removal is : [1, 5]" }, { "code": null, "e": 2619, "s": 2205, "text": " Method #3 : Using Lambda Function + filter()Lambda functions have always been a useful utility and hence can be used to perform tough task in just 1 liners. These can also perform this particular task. Drawback is that they are not inplace and require extra space or requires a overwrite. It actually constructs a new list, and filters out all of the required elements. It removes all the occurrences of element." }, { "code": "# Python code to demonstrate# element removal in list# using filter() + Lambda function test_list1 = [1, 3, 4, 6, 3]test_list2 = [1, 4, 5, 4, 5] # Printing initial listprint (\"The list before element removal is : \" + str(test_list1)) # using filter() + Lambda function # to remove list element 3test_list1 = list(filter(lambda x: x != 3, test_list1)) # Printing list after removalprint (\"The list after element removal is : \" + str(test_list1))", "e": 3122, "s": 2619, "text": null }, { "code": null, "e": 3130, "s": 3122, "text": "Output:" }, { "code": null, "e": 3229, "s": 3130, "text": "The list before element removal is : [1, 3, 4, 6, 3]\nThe list after element removal is : [1, 4, 6]" }, { "code": null, "e": 3566, "s": 3231, "text": "Method #4 : Using List ComprehensionList comprehensions are easier method to perform the similar task as performed by lambda function. It has the same drawback of not being inplace and also requires extra space or overwrite. It is better in a way that filter() is not required to perform it. It removes all the occurrences of element." }, { "code": "# Python code to demonstrate# element removal in list# using List Comprehension test_list1 = [1, 3, 4, 6, 3]test_list2 = [1, 4, 5, 4, 5] # Printing initial listprint (\"The list before element removal is : \" + str(test_list2)) # using List Comprehension# to remove list element 4test_list2 = [x for x in test_list2 if x != 4] # Printing list after removalprint (\"The list after element removal is : \" + str(test_list2))", "e": 4045, "s": 3566, "text": null }, { "code": null, "e": 4054, "s": 4045, "text": "Output :" }, { "code": null, "e": 4154, "s": 4054, "text": "The list before element removal is : [1, 4, 5, 4, 5]\nThe list after element removal is : [1, 5, 5]\n" }, { "code": null, "e": 4239, "s": 4156, "text": "Method #5 : Using pop()Using pop method with list index to pop element out of list" }, { "code": "# Python code to demonstrate# element removal in list# using pop() method test_list1 = [1, 3, 4, 6, 3] # Printing initial listprint (\"The list before element removal is : \" + str(test_list1)) rmv_element = 4 # using pop()# to remove list element 4if rmv_element in test_list1: test_list1.pop(test_list1.index(rmv_element)) # Printing list after removalprint (\"The list after element removal is : \" + str(test_list1)) # Added by Paras Jain(everythingispossible)", "e": 4763, "s": 4239, "text": null }, { "code": null, "e": 4772, "s": 4763, "text": "Output :" }, { "code": null, "e": 4875, "s": 4772, "text": "The list before element removal is : [1, 3, 4, 6, 3]\nThe list after element removal is : [1, 3, 6, 3]\n" }, { "code": null, "e": 4896, "s": 4875, "text": "everythingispossible" }, { "code": null, "e": 4917, "s": 4896, "text": "Python list-programs" }, { "code": null, "e": 4929, "s": 4917, "text": "python-list" }, { "code": null, "e": 4936, "s": 4929, "text": "Python" }, { "code": null, "e": 4948, "s": 4936, "text": "python-list" } ]
YACC program to implement a Calculator and recognize a valid Arithmetic expression
26 Aug, 2020 Problem: YACC program to implement a Calculator and recognize a valid Arithmetic expression. Explanation:Yacc (for “yet another compiler compiler.”) is the standard parser generator for the Unix operating system. An open source program, yacc generates code for the parser in the C programming language. The acronym is usually rendered in lowercase but is occasionally seen as YACC or Yacc. Examples: Input: 4+5 Output: Result=9 Entered arithmetic expression is Valid Input: 10-5 Output: Result=5 Entered arithmetic expression is Valid Input: 10+5- Output: Entered arithmetic expression is Invalid Input: 10/5 Output: Result=2 Entered arithmetic expression is Valid Input: (2+5)*3 Output: Result=21 Entered arithmetic expression is Valid Input: (2*4)+ Output: Entered arithmetic expression is Invalid Input: 2%5 Output: Result=2 Entered arithmetic expression is Valid Lexical Analyzer Source Code: %{ /* Definition section */ #include<stdio.h> #include "y.tab.h" extern int yylval;%} /* Rule Section */%%[0-9]+ { yylval=atoi(yytext); return NUMBER; }[\t] ; [\n] return 0; . return yytext[0]; %% int yywrap(){ return 1;} Parser Source Code : %{ /* Definition section */ #include<stdio.h> int flag=0;%} %token NUMBER %left '+' '-' %left '*' '/' '%' %left '(' ')' /* Rule Section */%% ArithmeticExpression: E{ printf("\nResult=%d\n", $$); return 0; }; E:E'+'E {$$=$1+$3;} |E'-'E {$$=$1-$3;} |E'*'E {$$=$1*$3;} |E'/'E {$$=$1/$3;} |E'%'E {$$=$1%$3;} |'('E')' {$$=$2;} | NUMBER {$$=$1;} ; %% //driver codevoid main(){ printf("\nEnter Any Arithmetic Expression which can have operations Addition, Subtraction, Multiplication, Division, Modulus and Round brackets:\n"); yyparse(); if(flag==0) printf("\nEntered arithmetic expression is Valid\n\n");} void yyerror(){ printf("\nEntered arithmetic expression is Invalid\n\n"); flag=1;} Output: nidhi_biet Lex program Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Issues in the design of a code generator Peephole Optimization in Compiler Design Code Optimization in Compiler Design Type Checking in Compiler Design Directed Acyclic graph in Compiler Design (with examples) Data flow analysis in Compiler S - attributed and L - attributed SDTs in Syntax directed translation Difference between Compiler and Interpreter Introduction of Compiler Design Runtime Environments in Compiler Design
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Aug, 2020" }, { "code": null, "e": 145, "s": 52, "text": "Problem: YACC program to implement a Calculator and recognize a valid Arithmetic expression." }, { "code": null, "e": 442, "s": 145, "text": "Explanation:Yacc (for “yet another compiler compiler.”) is the standard parser generator for the Unix operating system. An open source program, yacc generates code for the parser in the C programming language. The acronym is usually rendered in lowercase but is occasionally seen as YACC or Yacc." }, { "code": null, "e": 452, "s": 442, "text": "Examples:" }, { "code": null, "e": 929, "s": 452, "text": "Input: 4+5 \nOutput: Result=9\nEntered arithmetic expression is Valid\n\nInput: 10-5\nOutput: Result=5\nEntered arithmetic expression is Valid\n\nInput: 10+5-\nOutput: \nEntered arithmetic expression is Invalid\n\nInput: 10/5\nOutput: Result=2\nEntered arithmetic expression is Valid\n\nInput: (2+5)*3\nOutput: Result=21\nEntered arithmetic expression is Valid\n\nInput: (2*4)+\nOutput: \nEntered arithmetic expression is Invalid\n\nInput: 2%5\nOutput: Result=2\nEntered arithmetic expression is Valid " }, { "code": null, "e": 959, "s": 929, "text": "Lexical Analyzer Source Code:" }, { "code": "%{ /* Definition section */ #include<stdio.h> #include \"y.tab.h\" extern int yylval;%} /* Rule Section */%%[0-9]+ { yylval=atoi(yytext); return NUMBER; }[\\t] ; [\\n] return 0; . return yytext[0]; %% int yywrap(){ return 1;}", "e": 1217, "s": 959, "text": null }, { "code": null, "e": 1238, "s": 1217, "text": "Parser Source Code :" }, { "code": "%{ /* Definition section */ #include<stdio.h> int flag=0;%} %token NUMBER %left '+' '-' %left '*' '/' '%' %left '(' ')' /* Rule Section */%% ArithmeticExpression: E{ printf(\"\\nResult=%d\\n\", $$); return 0; }; E:E'+'E {$$=$1+$3;} |E'-'E {$$=$1-$3;} |E'*'E {$$=$1*$3;} |E'/'E {$$=$1/$3;} |E'%'E {$$=$1%$3;} |'('E')' {$$=$2;} | NUMBER {$$=$1;} ; %% //driver codevoid main(){ printf(\"\\nEnter Any Arithmetic Expression which can have operations Addition, Subtraction, Multiplication, Division, Modulus and Round brackets:\\n\"); yyparse(); if(flag==0) printf(\"\\nEntered arithmetic expression is Valid\\n\\n\");} void yyerror(){ printf(\"\\nEntered arithmetic expression is Invalid\\n\\n\"); flag=1;}", "e": 2056, "s": 1238, "text": null }, { "code": null, "e": 2064, "s": 2056, "text": "Output:" }, { "code": null, "e": 2075, "s": 2064, "text": "nidhi_biet" }, { "code": null, "e": 2087, "s": 2075, "text": "Lex program" }, { "code": null, "e": 2103, "s": 2087, "text": "Compiler Design" }, { "code": null, "e": 2201, "s": 2103, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2242, "s": 2201, "text": "Issues in the design of a code generator" }, { "code": null, "e": 2283, "s": 2242, "text": "Peephole Optimization in Compiler Design" }, { "code": null, "e": 2320, "s": 2283, "text": "Code Optimization in Compiler Design" }, { "code": null, "e": 2353, "s": 2320, "text": "Type Checking in Compiler Design" }, { "code": null, "e": 2411, "s": 2353, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 2442, "s": 2411, "text": "Data flow analysis in Compiler" }, { "code": null, "e": 2512, "s": 2442, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 2556, "s": 2512, "text": "Difference between Compiler and Interpreter" }, { "code": null, "e": 2588, "s": 2556, "text": "Introduction of Compiler Design" } ]
Comparison between Lists and Array in Python
08 Jul, 2020 Python programming language has four collection data types namely List, Tuple, Set, and Dictionary. A list is a mutable and ordered collection i.e., elements of the list can be changed and it maintains the order of insertion of its items. Because of the property of order maintaining, each element of the list has a fixed index and it permits the list to have duplicate elements. In Python, list is very useful as it has the ability to contain non-homogeneous elements. Following are some operations which can be performed on the list: # Python program to demonstrate# some operations on list # Declaring a List of integers IntList = [10, 20, 30] print("List of numbers: ") # Printing the list print(IntList) # Declaring a List of stringsStrList = ["Geeks", "For", "Geeks"] print("List of Strings: ") # Printing the list print(StrList) # Declaring a list of non-homogeneous elementsNon_homogeneous_list = [10, "Geeks", 20.890,\ "for", 30, "geeks"]print("List of non-homogeneous elements: ") # Printing the listprint(Non_homogeneous_list) # Printing size of a listprint("Size of the Non-homogeneous list: ",\ len(Non_homogeneous_list)) # Declaring a listNewList = ["Geeks", "for", "Geeks"]print("Original List: ", NewList) # Adding an item to the list # Adding an item in the list # using the append methodNewList.append("the") # Printing the modified listprint("After adding an element the"\ "list becomes: ")print(NewList) # Adding an item in the list using the insert # method to add an element at a specific positionNewList.insert(3, "is") # Printing the modified listprint("After adding an element at"\ "index 3 the list becomes: ")print(NewList) # Adding multiple items to the list at the# end using extend methodNewList.extend(["best", "CS", "website"]) # Printing the modified listprint("After adding 3 elements at the"\ "end, the list becomes: ")print(NewList) # Removing an item from the list # Removing an element by # writing the element itselfNewList.remove("the") # Printing the modified listprint("After removing an element"\ "the list becomes: ")print(NewList) # Removing an element by # specifying its positionNewList.pop(3) # Printing the modified listprint("After removing an element "\ "from index 3 the list becomes: ")print(NewList) List of numbers: [10, 20, 30] List of Strings: ['Geeks', 'For', 'Geeks'] List of non-homogeneous elements: [10, 'Geeks', 20.89, 'for', 30, 'geeks'] Size of the Non-homogeneous list: 6 Original List: ['Geeks', 'for', 'Geeks'] After adding an element thelist becomes: ['Geeks', 'for', 'Geeks', 'the'] After adding an element atindex 3 the list becomes: ['Geeks', 'for', 'Geeks', 'is', 'the'] After adding 3 elements at theend, the list becomes: ['Geeks', 'for', 'Geeks', 'is', 'the', 'best', 'CS', 'website'] After removing an elementthe list becomes: ['Geeks', 'for', 'Geeks', 'is', 'best', 'CS', 'website'] After removing an element from index 3 the list becomes: ['Geeks', 'for', 'Geeks', 'best', 'CS', 'website'] To get more in-depth knowledge about python list click here. Python arrays are also a collection but its items are stored at contiguous memory locations. It can store only homogeneous elements(elements of the same data type). Arrays are very beneficial in performing mathematical operations on the elements. Unlike lists, arrays can not be declared directly. To create an array the array module must be imported and the syntax of the declaration is different from that of the list. Following are some operations which can be performed on the array: # Python program to demonstrate# some operations on arrays # importing array module import array as arr # declaring an array of integer type# 'i' signifies integer type and# elements inside [] are the array elements a1 = arr.array('i', [10, 20, 30]) # printing array with # data type and elementsprint("Array a1: ", a1) # printing elements of arrayprint ("Elements of the array"\ "a1 is : ", end = " ") for i in range (len(a1)): print (a1[i], end =", ")print() # Declaring an array of float type# 'd' signifies integer type and# elements inside [] are the array elements a2 = arr.array('d', [1.5, 2.4, 3.9]) # printing elements of arrayprint ("Elements of the array"\ "a2 is : ", end = " ") for i in range (len(a2)): print (a2[i], end =", ")print() # Adding an item to the array # Printing the elements of array a1print ("Original elements of the"\ "array a1 is : ", end = " ") print(*a1) # Adding an element at the end of# array by using the append methoda1.append(40) # printing the modified arrayprint ("Elements of the array a1"\ "after adding an element"\ "at last: ", end = " ")print(*a1) # Adding an element to the array at a # specific index using the insert methoda1.insert(3, 35) # printing the modified arrayprint ("Elements of the array a1"\ "after adding an element"\ "at index 3: ", end = " ")print(*a1) # Removing an element from the array # Removing an element by writing the elements itselfa1.remove(20) # Printing the modified arrayprint("Array a1 after removing"\ "element 20: ", end = " ")print(*a1) # Removing an element of a specific index# Removing the element of array a1 present at index 2a1.pop(2) # Printing the modified arrayprint("Array a1 after removing"\"element of index 2: ", end = " ")print(*a1) Array a1: array('i', [10, 20, 30]) Elements of the arraya1 is : 10, 20, 30, Elements of the arraya2 is : 1.5, 2.4, 3.9, Original elements of thearray a1 is : 10 20 30 Elements of the array a1after adding an elementat last: 10 20 30 40 Elements of the array a1after adding an elementat index 3: 10 20 30 35 40 Array a1 after removingelement 20: 10 30 35 40 Array a1 after removingelement of index 2: 10 30 40 To get more in-depth knowledge about python array click here. Both array and lists are used for storing the data: The purpose of both the collection is to store the data. While the list is used to store homogeneous as well as non-homogeneous data, an array can store only homogeneous data. # Python program to demonstrate data # storing similarities in array and list # importing array module import array as arr # Declaring a Homogeneous List of stringsHomogeneous_List = ["Geeks", "For", "Geeks"] print("List of Strings: ") # Printing the list print(Homogeneous_List) # Declaring a list of # non-homogeneous elementsNon_homogeneous_list = [10, "Geeks",\ 20.890, "for", 30, "geeks"]print("List of non-homogeneous elements: ") # Printing the listprint(Non_homogeneous_list) # declaring an array of float type# 'd' signifies integer type and# elements inside [] are the array elements Homogeneous_array = arr.array('d',\ [1.5, 2.4, 3.9]) # printing elements of arrayprint ("Elements of the array is"\ " : ", end = " ") for i in range (len(Homogeneous_array)): print (Homogeneous_array[i], end =", ") List of Strings: ['Geeks', 'For', 'Geeks'] List of non-homogeneous elements: [10, 'Geeks', 20.89, 'for', 30, 'geeks'] Elements of the array is : 1.5, 2.4, 3.9, List and Array both are mutable: List, as well as the array, have the ability to modify their elements i.e., they are mutable. # Python program to demonstrate # both the list and array is mutable # importing array module import array as arr # Declaring a listList1 = ["Geeks", 1, "Geeks"] # Printing original listprint("Original list: ", List1) # Changing the value of the # element at a specific indexList1[1] = "for" # Printing modified listprint("\nModified list: ", List1) # Declaring an array with integers valuesArray1 = arr.array('i', \ [10, 20, 30, 37, 50, ]) # Printing original array print ("\nOriginal array: ", end =" ") for i in range (len(Array1)): print (Array1[i], end =" ") # Updating an element in the array Array1[3] = 40 # Printing modified Array:print("\nModified array: ", end ="") for i in range (len(Array1)): print (Array1[i], end =" ") Original list: ['Geeks', 1, 'Geeks'] Modified list: ['Geeks', 'for', 'Geeks'] Original array: 10 20 30 37 50 Modified array: 10 20 30 40 50 Elements of both list and array can be accessed by index and iteration: In order to access the elements of list and array, we have the option of using index number or we can traverse them by iteration. # Python program to demonstrate # that elements of list and array can# be accessed through index and iteration # importing array module import array as arr # Declaring a list List1 = [10, 20, 30, 20, 10, 40] # Printing the listprint("List1 elements: ", List1, "\n") # Accessing elements of list by index numberprint("Element at index 0: ", List1[0])print("Element at index 1: ", List1[1])print("Element at index 3: ", List1[3])print("Element at index 4: ", List1[4]) # Accessing elements of the list# using negative indexing # Printing last element of the listprint("Element at last index: ", List1[-1]) # Printing 3rd last # the element of the listprint("Element at "\ "3rd last index: ", List1[-3]) # Accessing elements of list through iterationprint("Accessing through iteration: ", end = " ")for item in range(len(List1)): print(List1[item], end =" ") # Declaring an arrayArray1 = arr.array('i',\[10, 20, 30, 40, 50, 60])print("\nArray1: ", Array1) # Accessing the elements of an array # Access element of # array by index numberprint("Element of Array1"\ " at index 3: ", Array1[3]) # Accessing elements of # array through iterationprint("Accessing through iteration:"\ " ", end = " ")for i in range (len(Array1)): print (Array1[i], end =" ") List1 elements: [10, 20, 30, 20, 10, 40] Element at index 0: 10 Element at index 1: 20 Element at index 3: 20 Element at index 4: 10 Element at last index: 40 Element at 3rd last index: 20 Accessing through iteration: 10 20 30 20 10 40 Array1: array('i', [10, 20, 30, 40, 50, 60]) Element of Array1 at index 3: 40 Accessing through iteration: 10 20 30 40 50 60 List and array both can be sliced: Slicing operation is valid for both the list and array to get a range of elements. # Python program to demonstrate # that both list and array can# be accessed sliced # importing array module import array as arr # Declaring a list List1 = [10, 20, 30, 20, 10, 40] # Accessing a range of elements in the # list using slicing operation # Printing items of the list# from index 1 to 3 print("List elements from "\ "index 1 to 4: ", List1[1:4]) # Printing items of the # list from index 2 to endprint("List elements from "\"index 2 to last: ", List1[2:]) # Declaring an arrayArray1 = arr.array('i', [10, 20, 30, 40, 50, 60]) # Accessing a range of elements in the # array using slicing operationSliced_array1 = Array1[1:4] print("\nSlicing elements of the "\"array in a\nrange from index 1 to 4: ") print(Sliced_array1) # Print elements of the array # from a defined point to end Sliced_array2 = Array1[2:] print("\nSlicing elements of the "\"array from\n2nd index till the end: ") print(Sliced_array2) List elements from index 1 to 4: [20, 30, 20] List elements from index 2 to last: [30, 20, 10, 40] Slicing elements of the array in a range from index 1 to 4: array('i', [20, 30, 40]) Slicing elements of the array from 2nd index till the end: array('i', [30, 40, 50, 60]) Difference in creation: Unlike list which is a part of Python syntax, an array can only be created by importing the array module. A list can be created by simply putting a sequence of elements around a square bracket. All the above codes are the proofs of this difference. Memory consumption between array and lists: List and array take a different amount of memory even if they store the same amount of elements. Arrays are found to be more efficient in this case as they store data in a very compact manner. # Python program to demonstrate the # difference in memory consumption # of list and array # importing array module import array as arr # importing system module import sys # declaring a list of 1000 elements List = range(1000) # printing size of each element of the list print("Size of each element of"\" list in bytes: ", sys.getsizeof(List)) # printing size of the whole list print("Size of the whole list in"\" bytes: ", sys.getsizeof(List)*len(List)) # declaring an array of 1000 elements Array = arr.array('i', [1]*1000) # printing size of each # element of the Numpy array print("Size of each element of "\"the array in bytes: ", Array.itemsize) # printing size of the whole Numpy array print("Size of the whole array"\" in bytes: ", len(Array)*Array.itemsize) Size of each element of list in bytes: 48 Size of the whole list in bytes: 48000 Size of each element of the array in bytes: 4 Size of the whole array in bytes: 4000 Performing mathematical operations: Mathematical operations like dividing or adding each element of the collection with a certain number can be carried out in arrays but lists do not support these kinds of arithmetic operations. Arrays are optimized for this purpose while to carry out these operations in the list, operations have to be applied to every element separately. # Python program to demonstrate the # difference between list and array in # carrying out mathematical operations # importing array module from numpy import array # declaring a list List =[1, 2, 3] # declaring an array Array = array([1, 2, 3]) try: # adding 5 to each element of list List = List + 5 except(TypeError): print("Lists don't support list + int") # for arraytry: Array = Array + 5 # printing the array print("Modified array: ", Array) except(TypeError): print("Arrays don't support list + int") Lists don't support list + int Modified array: [6 7 8] Resizing: Arrays once declared can not be resized. The only way is to copy the elements of the older array into a larger sized array. While the list can be re-sized very efficiently. Data that can be stored: List can store both homogeneous as well as non-homogeneous data while arrays support the storage of only homogeneous data. nidhi_biet Picked Python list-programs Python-array Arrays Articles Data Structures Data Structures Difference Between Programming Language Python Python Programs Data Structures Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Tree Traversals (Inorder, Preorder and Postorder) SQL | Join (Inner, Left, Right and Full Joins) find command in Linux with examples Analysis of Algorithms | Set 1 (Asymptotic Analysis) Time Complexity and Space Complexity
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jul, 2020" }, { "code": null, "e": 524, "s": 54, "text": "Python programming language has four collection data types namely List, Tuple, Set, and Dictionary. A list is a mutable and ordered collection i.e., elements of the list can be changed and it maintains the order of insertion of its items. Because of the property of order maintaining, each element of the list has a fixed index and it permits the list to have duplicate elements. In Python, list is very useful as it has the ability to contain non-homogeneous elements." }, { "code": null, "e": 590, "s": 524, "text": "Following are some operations which can be performed on the list:" }, { "code": "# Python program to demonstrate# some operations on list # Declaring a List of integers IntList = [10, 20, 30] print(\"List of numbers: \") # Printing the list print(IntList) # Declaring a List of stringsStrList = [\"Geeks\", \"For\", \"Geeks\"] print(\"List of Strings: \") # Printing the list print(StrList) # Declaring a list of non-homogeneous elementsNon_homogeneous_list = [10, \"Geeks\", 20.890,\\ \"for\", 30, \"geeks\"]print(\"List of non-homogeneous elements: \") # Printing the listprint(Non_homogeneous_list) # Printing size of a listprint(\"Size of the Non-homogeneous list: \",\\ len(Non_homogeneous_list)) # Declaring a listNewList = [\"Geeks\", \"for\", \"Geeks\"]print(\"Original List: \", NewList) # Adding an item to the list # Adding an item in the list # using the append methodNewList.append(\"the\") # Printing the modified listprint(\"After adding an element the\"\\ \"list becomes: \")print(NewList) # Adding an item in the list using the insert # method to add an element at a specific positionNewList.insert(3, \"is\") # Printing the modified listprint(\"After adding an element at\"\\ \"index 3 the list becomes: \")print(NewList) # Adding multiple items to the list at the# end using extend methodNewList.extend([\"best\", \"CS\", \"website\"]) # Printing the modified listprint(\"After adding 3 elements at the\"\\ \"end, the list becomes: \")print(NewList) # Removing an item from the list # Removing an element by # writing the element itselfNewList.remove(\"the\") # Printing the modified listprint(\"After removing an element\"\\ \"the list becomes: \")print(NewList) # Removing an element by # specifying its positionNewList.pop(3) # Printing the modified listprint(\"After removing an element \"\\ \"from index 3 the list becomes: \")print(NewList)", "e": 2423, "s": 590, "text": null }, { "code": null, "e": 3149, "s": 2423, "text": "List of numbers: \n[10, 20, 30]\nList of Strings: \n['Geeks', 'For', 'Geeks']\nList of non-homogeneous elements: \n[10, 'Geeks', 20.89, 'for', 30, 'geeks']\nSize of the Non-homogeneous list: 6\nOriginal List: ['Geeks', 'for', 'Geeks']\nAfter adding an element thelist becomes: \n['Geeks', 'for', 'Geeks', 'the']\nAfter adding an element atindex 3 the list becomes: \n['Geeks', 'for', 'Geeks', 'is', 'the']\nAfter adding 3 elements at theend, the list becomes: \n['Geeks', 'for', 'Geeks', 'is', 'the', 'best', 'CS', 'website']\nAfter removing an elementthe list becomes: \n['Geeks', 'for', 'Geeks', 'is', 'best', 'CS', 'website']\nAfter removing an element from index 3 the list becomes: \n['Geeks', 'for', 'Geeks', 'best', 'CS', 'website']\n" }, { "code": null, "e": 3210, "s": 3149, "text": "To get more in-depth knowledge about python list click here." }, { "code": null, "e": 3631, "s": 3210, "text": "Python arrays are also a collection but its items are stored at contiguous memory locations. It can store only homogeneous elements(elements of the same data type). Arrays are very beneficial in performing mathematical operations on the elements. Unlike lists, arrays can not be declared directly. To create an array the array module must be imported and the syntax of the declaration is different from that of the list." }, { "code": null, "e": 3698, "s": 3631, "text": "Following are some operations which can be performed on the array:" }, { "code": "# Python program to demonstrate# some operations on arrays # importing array module import array as arr # declaring an array of integer type# 'i' signifies integer type and# elements inside [] are the array elements a1 = arr.array('i', [10, 20, 30]) # printing array with # data type and elementsprint(\"Array a1: \", a1) # printing elements of arrayprint (\"Elements of the array\"\\ \"a1 is : \", end = \" \") for i in range (len(a1)): print (a1[i], end =\", \")print() # Declaring an array of float type# 'd' signifies integer type and# elements inside [] are the array elements a2 = arr.array('d', [1.5, 2.4, 3.9]) # printing elements of arrayprint (\"Elements of the array\"\\ \"a2 is : \", end = \" \") for i in range (len(a2)): print (a2[i], end =\", \")print() # Adding an item to the array # Printing the elements of array a1print (\"Original elements of the\"\\ \"array a1 is : \", end = \" \") print(*a1) # Adding an element at the end of# array by using the append methoda1.append(40) # printing the modified arrayprint (\"Elements of the array a1\"\\ \"after adding an element\"\\ \"at last: \", end = \" \")print(*a1) # Adding an element to the array at a # specific index using the insert methoda1.insert(3, 35) # printing the modified arrayprint (\"Elements of the array a1\"\\ \"after adding an element\"\\ \"at index 3: \", end = \" \")print(*a1) # Removing an element from the array # Removing an element by writing the elements itselfa1.remove(20) # Printing the modified arrayprint(\"Array a1 after removing\"\\ \"element 20: \", end = \" \")print(*a1) # Removing an element of a specific index# Removing the element of array a1 present at index 2a1.pop(2) # Printing the modified arrayprint(\"Array a1 after removing\"\\\"element of index 2: \", end = \" \")print(*a1)", "e": 5543, "s": 3698, "text": null }, { "code": null, "e": 5962, "s": 5543, "text": "Array a1: array('i', [10, 20, 30])\nElements of the arraya1 is : 10, 20, 30, \nElements of the arraya2 is : 1.5, 2.4, 3.9, \nOriginal elements of thearray a1 is : 10 20 30\nElements of the array a1after adding an elementat last: 10 20 30 40\nElements of the array a1after adding an elementat index 3: 10 20 30 35 40\nArray a1 after removingelement 20: 10 30 35 40\nArray a1 after removingelement of index 2: 10 30 40\n" }, { "code": null, "e": 6024, "s": 5962, "text": "To get more in-depth knowledge about python array click here." }, { "code": null, "e": 6252, "s": 6024, "text": "Both array and lists are used for storing the data: The purpose of both the collection is to store the data. While the list is used to store homogeneous as well as non-homogeneous data, an array can store only homogeneous data." }, { "code": "# Python program to demonstrate data # storing similarities in array and list # importing array module import array as arr # Declaring a Homogeneous List of stringsHomogeneous_List = [\"Geeks\", \"For\", \"Geeks\"] print(\"List of Strings: \") # Printing the list print(Homogeneous_List) # Declaring a list of # non-homogeneous elementsNon_homogeneous_list = [10, \"Geeks\",\\ 20.890, \"for\", 30, \"geeks\"]print(\"List of non-homogeneous elements: \") # Printing the listprint(Non_homogeneous_list) # declaring an array of float type# 'd' signifies integer type and# elements inside [] are the array elements Homogeneous_array = arr.array('d',\\ [1.5, 2.4, 3.9]) # printing elements of arrayprint (\"Elements of the array is\"\\ \" : \", end = \" \") for i in range (len(Homogeneous_array)): print (Homogeneous_array[i], end =\", \")", "e": 7110, "s": 6252, "text": null }, { "code": null, "e": 7274, "s": 7110, "text": "List of Strings: \n['Geeks', 'For', 'Geeks']\nList of non-homogeneous elements: \n[10, 'Geeks', 20.89, 'for', 30, 'geeks']\nElements of the array is : 1.5, 2.4, 3.9,\n" }, { "code": null, "e": 7401, "s": 7274, "text": "List and Array both are mutable: List, as well as the array, have the ability to modify their elements i.e., they are mutable." }, { "code": "# Python program to demonstrate # both the list and array is mutable # importing array module import array as arr # Declaring a listList1 = [\"Geeks\", 1, \"Geeks\"] # Printing original listprint(\"Original list: \", List1) # Changing the value of the # element at a specific indexList1[1] = \"for\" # Printing modified listprint(\"\\nModified list: \", List1) # Declaring an array with integers valuesArray1 = arr.array('i', \\ [10, 20, 30, 37, 50, ]) # Printing original array print (\"\\nOriginal array: \", end =\" \") for i in range (len(Array1)): print (Array1[i], end =\" \") # Updating an element in the array Array1[3] = 40 # Printing modified Array:print(\"\\nModified array: \", end =\"\") for i in range (len(Array1)): print (Array1[i], end =\" \") ", "e": 8167, "s": 7401, "text": null }, { "code": null, "e": 8314, "s": 8167, "text": "Original list: ['Geeks', 1, 'Geeks']\n\nModified list: ['Geeks', 'for', 'Geeks']\n\nOriginal array: 10 20 30 37 50 \nModified array: 10 20 30 40 50\n" }, { "code": null, "e": 8516, "s": 8314, "text": "Elements of both list and array can be accessed by index and iteration: In order to access the elements of list and array, we have the option of using index number or we can traverse them by iteration." }, { "code": "# Python program to demonstrate # that elements of list and array can# be accessed through index and iteration # importing array module import array as arr # Declaring a list List1 = [10, 20, 30, 20, 10, 40] # Printing the listprint(\"List1 elements: \", List1, \"\\n\") # Accessing elements of list by index numberprint(\"Element at index 0: \", List1[0])print(\"Element at index 1: \", List1[1])print(\"Element at index 3: \", List1[3])print(\"Element at index 4: \", List1[4]) # Accessing elements of the list# using negative indexing # Printing last element of the listprint(\"Element at last index: \", List1[-1]) # Printing 3rd last # the element of the listprint(\"Element at \"\\ \"3rd last index: \", List1[-3]) # Accessing elements of list through iterationprint(\"Accessing through iteration: \", end = \" \")for item in range(len(List1)): print(List1[item], end =\" \") # Declaring an arrayArray1 = arr.array('i',\\[10, 20, 30, 40, 50, 60])print(\"\\nArray1: \", Array1) # Accessing the elements of an array # Access element of # array by index numberprint(\"Element of Array1\"\\ \" at index 3: \", Array1[3]) # Accessing elements of # array through iterationprint(\"Accessing through iteration:\"\\ \" \", end = \" \")for i in range (len(Array1)): print (Array1[i], end =\" \")", "e": 9804, "s": 8516, "text": null }, { "code": null, "e": 10180, "s": 9804, "text": "List1 elements: [10, 20, 30, 20, 10, 40] \n\nElement at index 0: 10\nElement at index 1: 20\nElement at index 3: 20\nElement at index 4: 10\nElement at last index: 40\nElement at 3rd last index: 20\nAccessing through iteration: 10 20 30 20 10 40 \nArray1: array('i', [10, 20, 30, 40, 50, 60])\nElement of Array1 at index 3: 40\nAccessing through iteration: 10 20 30 40 50 60\n" }, { "code": null, "e": 10298, "s": 10180, "text": "List and array both can be sliced: Slicing operation is valid for both the list and array to get a range of elements." }, { "code": "# Python program to demonstrate # that both list and array can# be accessed sliced # importing array module import array as arr # Declaring a list List1 = [10, 20, 30, 20, 10, 40] # Accessing a range of elements in the # list using slicing operation # Printing items of the list# from index 1 to 3 print(\"List elements from \"\\ \"index 1 to 4: \", List1[1:4]) # Printing items of the # list from index 2 to endprint(\"List elements from \"\\\"index 2 to last: \", List1[2:]) # Declaring an arrayArray1 = arr.array('i', [10, 20, 30, 40, 50, 60]) # Accessing a range of elements in the # array using slicing operationSliced_array1 = Array1[1:4] print(\"\\nSlicing elements of the \"\\\"array in a\\nrange from index 1 to 4: \") print(Sliced_array1) # Print elements of the array # from a defined point to end Sliced_array2 = Array1[2:] print(\"\\nSlicing elements of the \"\\\"array from\\n2nd index till the end: \") print(Sliced_array2) ", "e": 11227, "s": 10298, "text": null }, { "code": null, "e": 11506, "s": 11227, "text": "List elements from index 1 to 4: [20, 30, 20]\nList elements from index 2 to last: [30, 20, 10, 40]\n\nSlicing elements of the array in a\nrange from index 1 to 4: \narray('i', [20, 30, 40])\n\nSlicing elements of the array from\n2nd index till the end: \narray('i', [30, 40, 50, 60])\n" }, { "code": null, "e": 11779, "s": 11506, "text": "Difference in creation: Unlike list which is a part of Python syntax, an array can only be created by importing the array module. A list can be created by simply putting a sequence of elements around a square bracket. All the above codes are the proofs of this difference." }, { "code": null, "e": 12016, "s": 11779, "text": "Memory consumption between array and lists: List and array take a different amount of memory even if they store the same amount of elements. Arrays are found to be more efficient in this case as they store data in a very compact manner." }, { "code": "# Python program to demonstrate the # difference in memory consumption # of list and array # importing array module import array as arr # importing system module import sys # declaring a list of 1000 elements List = range(1000) # printing size of each element of the list print(\"Size of each element of\"\\\" list in bytes: \", sys.getsizeof(List)) # printing size of the whole list print(\"Size of the whole list in\"\\\" bytes: \", sys.getsizeof(List)*len(List)) # declaring an array of 1000 elements Array = arr.array('i', [1]*1000) # printing size of each # element of the Numpy array print(\"Size of each element of \"\\\"the array in bytes: \", Array.itemsize) # printing size of the whole Numpy array print(\"Size of the whole array\"\\\" in bytes: \", len(Array)*Array.itemsize) ", "e": 12814, "s": 12016, "text": null }, { "code": null, "e": 12985, "s": 12814, "text": "Size of each element of list in bytes: 48\nSize of the whole list in bytes: 48000\nSize of each element of the array in bytes: 4\nSize of the whole array in bytes: 4000\n" }, { "code": null, "e": 13360, "s": 12985, "text": "Performing mathematical operations: Mathematical operations like dividing or adding each element of the collection with a certain number can be carried out in arrays but lists do not support these kinds of arithmetic operations. Arrays are optimized for this purpose while to carry out these operations in the list, operations have to be applied to every element separately." }, { "code": "# Python program to demonstrate the # difference between list and array in # carrying out mathematical operations # importing array module from numpy import array # declaring a list List =[1, 2, 3] # declaring an array Array = array([1, 2, 3]) try: # adding 5 to each element of list List = List + 5 except(TypeError): print(\"Lists don't support list + int\") # for arraytry: Array = Array + 5 # printing the array print(\"Modified array: \", Array) except(TypeError): print(\"Arrays don't support list + int\") ", "e": 13936, "s": 13360, "text": null }, { "code": null, "e": 13993, "s": 13936, "text": "Lists don't support list + int\nModified array: [6 7 8]\n" }, { "code": null, "e": 14176, "s": 13993, "text": "Resizing: Arrays once declared can not be resized. The only way is to copy the elements of the older array into a larger sized array. While the list can be re-sized very efficiently." }, { "code": null, "e": 14324, "s": 14176, "text": "Data that can be stored: List can store both homogeneous as well as non-homogeneous data while arrays support the storage of only homogeneous data." }, { "code": null, "e": 14335, "s": 14324, "text": "nidhi_biet" }, { "code": null, "e": 14342, "s": 14335, "text": "Picked" }, { "code": null, "e": 14363, "s": 14342, "text": "Python list-programs" }, { "code": null, "e": 14376, "s": 14363, "text": "Python-array" }, { "code": null, "e": 14383, "s": 14376, "text": "Arrays" }, { "code": null, "e": 14392, "s": 14383, "text": "Articles" }, { "code": null, "e": 14408, "s": 14392, "text": "Data Structures" }, { "code": null, "e": 14424, "s": 14408, "text": "Data Structures" }, { "code": null, "e": 14443, "s": 14424, "text": "Difference Between" }, { "code": null, "e": 14464, "s": 14443, "text": "Programming Language" }, { "code": null, "e": 14471, "s": 14464, "text": "Python" }, { "code": null, "e": 14487, "s": 14471, "text": "Python Programs" }, { "code": null, "e": 14503, "s": 14487, "text": "Data Structures" }, { "code": null, "e": 14510, "s": 14503, "text": "Arrays" }, { "code": null, "e": 14608, "s": 14510, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14640, "s": 14608, "text": "Introduction to Data Structures" }, { "code": null, "e": 14665, "s": 14640, "text": "Window Sliding Technique" }, { "code": null, "e": 14712, "s": 14665, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 14776, "s": 14712, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 14807, "s": 14776, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 14857, "s": 14807, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 14904, "s": 14857, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 14940, "s": 14904, "text": "find command in Linux with examples" }, { "code": null, "e": 14993, "s": 14940, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" } ]
Python | Longest String in list
11 Dec, 2019 Sometimes, while working with Python Lists, we can have a problem in which we receive Strings as elements and wish to compute the String which has maximum length. This kind of problem can have applications in many domains. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using loopThis is the brute method in which we perform this task. In this, we run a loop to keep a memory of longest string length and return the string which has max length in list. # Python3 code to demonstrate working of# Longest String in list# using loop # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks'] # printing original list print("The original list : " + str(test_list)) # Longest String in list# using loopmax_len = -1for ele in test_list: if len(ele) > max_len: max_len = len(ele) res = ele # printing resultprint("Maximum length string is : " + res) The original list : ['gfg', 'is', 'best', 'for', 'geeks'] Maximum length string is : geeks Method #2 : Using max() + keyThis method can also be used to solve this problem. In this, we use inbuilt max() with “len” as key argument to extract the string with the maximum length. # Python3 code to demonstrate working of# Longest String in list# using max() + key # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks'] # printing original list print("The original list : " + str(test_list)) # Longest String in list# using max() + keyres = max(test_list, key = len) # printing resultprint("Maximum length string is : " + res) The original list : ['gfg', 'is', 'best', 'for', 'geeks'] Maximum length string is : geeks Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Defaultdict in Python Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary Python | Split string into list of characters
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Dec, 2019" }, { "code": null, "e": 340, "s": 53, "text": "Sometimes, while working with Python Lists, we can have a problem in which we receive Strings as elements and wish to compute the String which has maximum length. This kind of problem can have applications in many domains. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 535, "s": 340, "text": "Method #1 : Using loopThis is the brute method in which we perform this task. In this, we run a loop to keep a memory of longest string length and return the string which has max length in list." }, { "code": "# Python3 code to demonstrate working of# Longest String in list# using loop # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks'] # printing original list print(\"The original list : \" + str(test_list)) # Longest String in list# using loopmax_len = -1for ele in test_list: if len(ele) > max_len: max_len = len(ele) res = ele # printing resultprint(\"Maximum length string is : \" + res)", "e": 955, "s": 535, "text": null }, { "code": null, "e": 1047, "s": 955, "text": "The original list : ['gfg', 'is', 'best', 'for', 'geeks']\nMaximum length string is : geeks\n" }, { "code": null, "e": 1234, "s": 1049, "text": "Method #2 : Using max() + keyThis method can also be used to solve this problem. In this, we use inbuilt max() with “len” as key argument to extract the string with the maximum length." }, { "code": "# Python3 code to demonstrate working of# Longest String in list# using max() + key # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks'] # printing original list print(\"The original list : \" + str(test_list)) # Longest String in list# using max() + keyres = max(test_list, key = len) # printing resultprint(\"Maximum length string is : \" + res)", "e": 1597, "s": 1234, "text": null }, { "code": null, "e": 1689, "s": 1597, "text": "The original list : ['gfg', 'is', 'best', 'for', 'geeks']\nMaximum length string is : geeks\n" }, { "code": null, "e": 1710, "s": 1689, "text": "Python list-programs" }, { "code": null, "e": 1717, "s": 1710, "text": "Python" }, { "code": null, "e": 1733, "s": 1717, "text": "Python Programs" }, { "code": null, "e": 1831, "s": 1733, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1873, "s": 1831, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1895, "s": 1873, "text": "Enumerate() in Python" }, { "code": null, "e": 1921, "s": 1895, "text": "Python String | replace()" }, { "code": null, "e": 1953, "s": 1921, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1982, "s": 1953, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2004, "s": 1982, "text": "Defaultdict in Python" }, { "code": null, "e": 2042, "s": 2004, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2079, "s": 2042, "text": "Python Program for Fibonacci numbers" }, { "code": null, "e": 2128, "s": 2079, "text": "Python | Convert string dictionary to dictionary" } ]
Race Condition in Golang
07 Jul, 2020 As per Wikipedia, race condition is defined as the condition of an electronics, software, or other systems where the system’s substantive behavior is dependent on the sequence or timing of other uncontrollable events. Race condition falls under the “Concurrency” department. Concurrency is the art of making progress on multiple tasks simultaneously. Let’s understand what concurrency actually means. Consider the following scenario to understand concurrency in a better way. Imagine a basket full of laddoos and two people standing near the basket. One is assigned a task to measure the count, quality, weight, and examine other important features of each and every laddu in the basket. Now as soon as he begins to observe the laddoos to derive some conclusion, simultaneously the second person tampers some laddoos shape, beats them so they’re powdered, and even eats some bits of some laddoos. It’s happening simultaneously: one taking note of the features of laddoos & the other damaging the original features. Now there’s no way in the world that the first one knows the original data as he’s only taking note of the tampered data which even he is unaware of. This is a race condition. Both tasks executing simultaneously interfering with some common things leading to a great deal of data loss. Lets code and understand race condition practically! package main import ( "fmt" "time") func execute(some string) { // initializing a infinite for loop for i := 1; true; i++ { // prints string and number fmt.Println(some, i) // this makes the program sleep for // 100 milliseconds, wiz 10 seconds time.Sleep(time.Millisecond * 100) }} func main() { // Simple go synchronous program // without any concurrency execute("First") // when this func is called it executes // and then passes on to next line execute("Second") // after the first second is to be executed // the problem is, execute function will // never finish execution, its trapped // in an infinite loop so the program will // never move to second execution. fmt.Println("program ends successfully") // if I'm wrong and both first and second // execute, then this line should print too // check the output} If you use Windows, you’re likely to see such output on the screen. The above output goes on like that and has no end unless you manually stop it or it runs out of system memory for execution. Consider the second code. package main import ( "fmt" "time") func execute(some string) { // initializing a infinite for loop for i := 1; true; i++ { // prints string and number fmt.Println(some, i) // this makes the program sleep for // 100 milliseconds, wiz 10 seconds time.Sleep(time.Millisecond * 100) }} func main() { // Simple go program with concurrency go execute("First") // Placing the go command infront of the // func call simply creates a goroutine execute("Second") // The goroutine ensures that both functions // execute simultaneously & successfully fmt.Println("program ends successfully") // This statement still won't execute because // the func call is stuck in an infinite loop // check the output} If you use Windows, you’re likely to see such output on the screen. When you create a goroutine in Go, it typically makes the execution faster by giving off the waiting time to other prevailing tasks, Now let’s see what happens if you create two goroutines in the same program. package main import ( "fmt" "time") func execute(some string) { // initializing a infinite for loop for i := 1; true; i++ { // prints string and number fmt.Println(some, i) // this makes the program sleep for // 100 milliseconds, wiz 10 seconds time.Sleep(time.Millisecond * 100) }} func main() { // Simple go program with concurrency go execute("First") // Placing the go command in front of the // func call simply creates a goroutine go execute("Second") // The second goroutine, you may think that the // program will now run with lightning speed // But, both goroutines go to the background // and result in no output at all Because the // program exits after the main goroutine fmt.Println("Program ends successfully") // This statement will now be executed // and nothing else will be executed // check the output} If you use Windows, you’re likely to see such output on the screen. Let’s consider one race condition scenario to wind up our topic: package main // one goroutine is the main// goroutine that comes by defaultimport ( "fmt" "runtime" "sync") var wgIns sync.WaitGroup func main() { // shared variable counter := 0 // the other 10 goroutines are // supposed to come from here wgIns.Add(10) for i := 0; i < 10; i++ { // goroutines are made go func() { for j := 0; j < 10; j++ { // shared variable execution counter += 1 // 100 should be the counter value but // it may be equal to 100 or lesser // due to race condition } wgIns.Done() }() } // this value should actually be 11 fmt.Println("The number of goroutines before wait = ", runtime.NumGoroutine()) wgIns.Wait() // value should be 100 fmt.Println("Counter value = ", counter) fmt.Println("The number of goroutines after wait = ", runtime.NumGoroutine()) // this value is supposed to be 1 // but lets see if these values // stay consistently same every // time we run the code} This inconsistency happens because of race conditions. Race condition in simple terms can be explained as, you have one candy and two kids run to you claiming that they’re both hungry. They both end up fighting for that one chocolate, they race to get the candy. This is a race condition. Here the solution is: get another candy so that the two enjoy a candy peacefully. Likewise, we can increase the resources allocation in order to ensure race condition does not occur. Golang-Concurrency Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jul, 2020" }, { "code": null, "e": 429, "s": 28, "text": "As per Wikipedia, race condition is defined as the condition of an electronics, software, or other systems where the system’s substantive behavior is dependent on the sequence or timing of other uncontrollable events. Race condition falls under the “Concurrency” department. Concurrency is the art of making progress on multiple tasks simultaneously. Let’s understand what concurrency actually means." }, { "code": null, "e": 1329, "s": 429, "text": "Consider the following scenario to understand concurrency in a better way. Imagine a basket full of laddoos and two people standing near the basket. One is assigned a task to measure the count, quality, weight, and examine other important features of each and every laddu in the basket. Now as soon as he begins to observe the laddoos to derive some conclusion, simultaneously the second person tampers some laddoos shape, beats them so they’re powdered, and even eats some bits of some laddoos. It’s happening simultaneously: one taking note of the features of laddoos & the other damaging the original features. Now there’s no way in the world that the first one knows the original data as he’s only taking note of the tampered data which even he is unaware of. This is a race condition. Both tasks executing simultaneously interfering with some common things leading to a great deal of data loss." }, { "code": null, "e": 1382, "s": 1329, "text": "Lets code and understand race condition practically!" }, { "code": "package main import ( \"fmt\" \"time\") func execute(some string) { // initializing a infinite for loop for i := 1; true; i++ { // prints string and number fmt.Println(some, i) // this makes the program sleep for // 100 milliseconds, wiz 10 seconds time.Sleep(time.Millisecond * 100) }} func main() { // Simple go synchronous program // without any concurrency execute(\"First\") // when this func is called it executes // and then passes on to next line execute(\"Second\") // after the first second is to be executed // the problem is, execute function will // never finish execution, its trapped // in an infinite loop so the program will // never move to second execution. fmt.Println(\"program ends successfully\") // if I'm wrong and both first and second // execute, then this line should print too // check the output}", "e": 2330, "s": 1382, "text": null }, { "code": null, "e": 2523, "s": 2330, "text": "If you use Windows, you’re likely to see such output on the screen. The above output goes on like that and has no end unless you manually stop it or it runs out of system memory for execution." }, { "code": null, "e": 2549, "s": 2523, "text": "Consider the second code." }, { "code": "package main import ( \"fmt\" \"time\") func execute(some string) { // initializing a infinite for loop for i := 1; true; i++ { // prints string and number fmt.Println(some, i) // this makes the program sleep for // 100 milliseconds, wiz 10 seconds time.Sleep(time.Millisecond * 100) }} func main() { // Simple go program with concurrency go execute(\"First\") // Placing the go command infront of the // func call simply creates a goroutine execute(\"Second\") // The goroutine ensures that both functions // execute simultaneously & successfully fmt.Println(\"program ends successfully\") // This statement still won't execute because // the func call is stuck in an infinite loop // check the output}", "e": 3343, "s": 2549, "text": null }, { "code": null, "e": 3621, "s": 3343, "text": "If you use Windows, you’re likely to see such output on the screen. When you create a goroutine in Go, it typically makes the execution faster by giving off the waiting time to other prevailing tasks, Now let’s see what happens if you create two goroutines in the same program." }, { "code": "package main import ( \"fmt\" \"time\") func execute(some string) { // initializing a infinite for loop for i := 1; true; i++ { // prints string and number fmt.Println(some, i) // this makes the program sleep for // 100 milliseconds, wiz 10 seconds time.Sleep(time.Millisecond * 100) }} func main() { // Simple go program with concurrency go execute(\"First\") // Placing the go command in front of the // func call simply creates a goroutine go execute(\"Second\") // The second goroutine, you may think that the // program will now run with lightning speed // But, both goroutines go to the background // and result in no output at all Because the // program exits after the main goroutine fmt.Println(\"Program ends successfully\") // This statement will now be executed // and nothing else will be executed // check the output}", "e": 4574, "s": 3621, "text": null }, { "code": null, "e": 4707, "s": 4574, "text": "If you use Windows, you’re likely to see such output on the screen. Let’s consider one race condition scenario to wind up our topic:" }, { "code": "package main // one goroutine is the main// goroutine that comes by defaultimport ( \"fmt\" \"runtime\" \"sync\") var wgIns sync.WaitGroup func main() { // shared variable counter := 0 // the other 10 goroutines are // supposed to come from here wgIns.Add(10) for i := 0; i < 10; i++ { // goroutines are made go func() { for j := 0; j < 10; j++ { // shared variable execution counter += 1 // 100 should be the counter value but // it may be equal to 100 or lesser // due to race condition } wgIns.Done() }() } // this value should actually be 11 fmt.Println(\"The number of goroutines before wait = \", runtime.NumGoroutine()) wgIns.Wait() // value should be 100 fmt.Println(\"Counter value = \", counter) fmt.Println(\"The number of goroutines after wait = \", runtime.NumGoroutine()) // this value is supposed to be 1 // but lets see if these values // stay consistently same every // time we run the code}", "e": 5814, "s": 4707, "text": null }, { "code": null, "e": 6286, "s": 5814, "text": "This inconsistency happens because of race conditions. Race condition in simple terms can be explained as, you have one candy and two kids run to you claiming that they’re both hungry. They both end up fighting for that one chocolate, they race to get the candy. This is a race condition. Here the solution is: get another candy so that the two enjoy a candy peacefully. Likewise, we can increase the resources allocation in order to ensure race condition does not occur." }, { "code": null, "e": 6305, "s": 6286, "text": "Golang-Concurrency" }, { "code": null, "e": 6317, "s": 6305, "text": "Go Language" } ]
Program to find Circumcenter of a Triangle
20 Jun, 2022 Given 3 non-collinear points in the 2D Plane P, Q and R with their respective x and y coordinates, find the circumcenter of the triangle.Note: Circumcenter of a triangle is the centre of the circle, formed by the three vertices of a triangle. Note that three points can uniquely determine a circle.Examples: Input : P(6, 0) Q(0, 0) R(0, 8) Output : The circumcenter of the triangle PQR is: (3, 4) Input : P(1, 1) Q(0, 0) R(2, 2) Output : The two perpendicular bisectors found come parallel. Thus, the given points do not form a triangle and are collinear Given, three points of the triangle, we can easily find the sides of the triangle. Now, we have the equations of the lines for the three sides of the triangle. After getting these, we can find the circumcenter of the triangle by a simple property stated as under: The circumcenter of the triangle is point where all the perpendicular bisectors of the sides of the triangle intersect. This is well explained in the following diagram. Note here that, there is no need to find all of the three sides of the triangle. Finding two sides is sufficient as we can uniquely find the point of intersection using just two perpendicular bisectors. The third perpendicular bisector will itself pass through the so found circumcenter.The things to be done can be divided as under: Find 2 lines (say PQ and QR) which form the sides of the triangle.Find the perpendicular bisectors of PQ and QR (say lines L and M respectively).Find the point of intersection of lines L and M as the circumcenter of the given triangle. Find 2 lines (say PQ and QR) which form the sides of the triangle. Find the perpendicular bisectors of PQ and QR (say lines L and M respectively). Find the point of intersection of lines L and M as the circumcenter of the given triangle. STEP 1 Refer this post Program to find line passing through 2 PointsSTEP 2 Let PQ be represented as ax + by = c A line perpendicular to this line is represented as -bx + ay = d for some d. However, we are interested in the perpendicular bisector. So, we find the mid-point of P and Q and putting this value in the standard equation, we get the value of d. Similarly, we repeat the process for QR. d = -bx + ay where, x = (xp + xq)/2 AND y = (yp + yq)/2 STEP 3 Refer this post Program for Point of Intersection of Two Lines CPP Python3 C# Javascript // C++ program to find the CIRCUMCENTER of a// triangle#include <iostream>#include <cfloat>using namespace std; // This pair is used to store the X and Y// coordinate of a point respectively#define pdd pair<double, double> // Function to find the line given two pointsvoid lineFromPoints(pdd P, pdd Q, double &a, double &b, double &c){ a = Q.second - P.second; b = P.first - Q.first; c = a*(P.first)+ b*(P.second);} // Function which converts the input line to its// perpendicular bisector. It also inputs the points// whose mid-point lies on the bisectorvoid perpendicularBisectorFromLine(pdd P, pdd Q, double &a, double &b, double &c){ pdd mid_point = make_pair((P.first + Q.first)/2, (P.second + Q.second)/2); // c = -bx + ay c = -b*(mid_point.first) + a*(mid_point.second); double temp = a; a = -b; b = temp;} // Returns the intersection point of two linespdd lineLineIntersection(double a1, double b1, double c1, double a2, double b2, double c2){ double determinant = a1*b2 - a2*b1; if (determinant == 0) { // The lines are parallel. This is simplified // by returning a pair of FLT_MAX return make_pair(FLT_MAX, FLT_MAX); } else { double x = (b2*c1 - b1*c2)/determinant; double y = (a1*c2 - a2*c1)/determinant; return make_pair(x, y); }} void findCircumCenter(pdd P, pdd Q, pdd R){ // Line PQ is represented as ax + by = c double a, b, c; lineFromPoints(P, Q, a, b, c); // Line QR is represented as ex + fy = g double e, f, g; lineFromPoints(Q, R, e, f, g); // Converting lines PQ and QR to perpendicular // vbisectors. After this, L = ax + by = c // M = ex + fy = g perpendicularBisectorFromLine(P, Q, a, b, c); perpendicularBisectorFromLine(Q, R, e, f, g); // The point of intersection of L and M gives // the circumcenter pdd circumcenter = lineLineIntersection(a, b, c, e, f, g); if (circumcenter.first == FLT_MAX && circumcenter.second == FLT_MAX) { cout << "The two perpendicular bisectors " "found come parallel" << endl; cout << "Thus, the given points do not form " "a triangle and are collinear" << endl; } else { cout << "The circumcenter of the triangle PQR is: "; cout << "(" << circumcenter.first << ", " << circumcenter.second << ")" << endl; }} // Driver code.int main(){ pdd P = make_pair(6, 0); pdd Q = make_pair(0, 0); pdd R = make_pair(0, 8); findCircumCenter(P, Q, R); return 0;} # Python3 program to find the CIRCUMCENTER of a# triangle # This pair is used to store the X and Y# coordinate of a point respectively# define pair<double, double> # Function to find the line given two pointsdef lineFromPoints(P, Q, a, b, c): a = Q[1] - P[1] b = P[0] - Q[0] c = a * (P[0]) + b * (P[1]) return a, b, c # Function which converts the input line to its# perpendicular bisector. It also inputs the points# whose mid-point lies on the bisectordef perpendicularBisectorFromLine(P, Q, a, b, c): mid_point = [(P[0] + Q[0])//2, (P[1] + Q[1])//2] # c = -bx + ay c = -b * (mid_point[0]) + a * (mid_point[1]) temp = a a = -b b = temp return a, b, c # Returns the intersection point of two linesdef lineLineIntersection(a1, b1, c1, a2, b2, c2): determinant = a1 * b2 - a2 * b1 if (determinant == 0): # The lines are parallel. This is simplified # by returning a pair of (10.0)**19 return [(10.0)**19, (10.0)**19] else: x = (b2 * c1 - b1 * c2)//determinant y = (a1 * c2 - a2 * c1)//determinant return [x, y] def findCircumCenter(P, Q, R): # Line PQ is represented as ax + by = c a, b, c = 0.0, 0.0, 0.0 a, b, c = lineFromPoints(P, Q, a, b, c) # Line QR is represented as ex + fy = g e, f, g = 0.0, 0.0, 0.0 e, f, g = lineFromPoints(Q, R, e, f, g) # Converting lines PQ and QR to perpendicular # vbisectors. After this, L = ax + by = c # M = ex + fy = g a, b, c = perpendicularBisectorFromLine(P, Q, a, b, c) e, f, g = perpendicularBisectorFromLine(Q, R, e, f, g) # The point of intersection of L and M gives # the circumcenter circumcenter = lineLineIntersection(a, b, c, e, f, g) if (circumcenter[0] == (10.0)**19 and circumcenter[1] == (10.0)**19): print("The two perpendicular bisectors found come parallel") print("Thus, the given points do not form a triangle and are collinear") else: print("The circumcenter of the triangle PQR is: ", end="") print("(", circumcenter[0], ",", circumcenter[1], ")") # Driver code.if __name__ == '__main__': P = [6, 0] Q = [0, 0] R = [0, 8] findCircumCenter(P, Q, R) # This code is contributed by mohit kumar 29 using System;using System.Collections.Generic; public static class GFG { // C# program to find the CIRCUMCENTER of a // triangle // This pair is used to store the X and Y // coordinate of a point respectively // Function to find the line given two points public static void lineFromPoints(List<double> P, List<double> Q, ref double a, ref double b, ref double c) { a = Q[1] - P[1]; b = P[0] - Q[0]; c = a * (P[0]) + b * (P[1]); } // Function which converts the input line to its // perpendicular bisector. It also inputs the points // whose mid-point lies on the bisector public static void perpendicularBisectorFromLine( List<double> P, List<double> Q, ref double a, ref double b, ref double c) { List<double> mid_point = new List<double>(); mid_point.Add((P[0] + Q[0]) / 2); mid_point.Add((P[1] + Q[1]) / 2); // c = -bx + ay c = -b * (mid_point[0]) + a * (mid_point[1]); double temp = a; a = -b; b = temp; } // Returns the intersection point of two lines public static List<double> lineLineIntersection(double a1, double b1, double c1, double a2, double b2, double c2) { List<double> ans = new List<double>(); double determinant = a1 * b2 - a2 * b1; if (determinant == 0) { // The lines are parallel. This is simplified // by returning a pair of FLT_MAX ans.Add(double.MaxValue); ans.Add(double.MaxValue); } else { double x = (b2 * c1 - b1 * c2) / determinant; double y = (a1 * c2 - a2 * c1) / determinant; ans.Add(x); ans.Add(y); } return ans; } public static void findCircumCenter(List<double> P, List<double> Q, List<double> R) { // Line PQ is represented as ax + by = c double a = 0; double b = 0; double c = 0; lineFromPoints(P, Q, ref a, ref b, ref c); // Line QR is represented as ex + fy = g double e = 0; double f = 0; double g = 0; lineFromPoints(Q, R, ref e, ref f, ref g); // Converting lines PQ and QR to perpendicular // vbisectors. After this, L = ax + by = c // M = ex + fy = g perpendicularBisectorFromLine(P, Q, ref a, ref b, ref c); perpendicularBisectorFromLine(Q, R, ref e, ref f, ref g); // The point of intersection of L and M gives // the circumcenter List<double> circumcenter = lineLineIntersection(a, b, c, e, f, g); if (circumcenter[0] == float.MaxValue && circumcenter[1] == float.MaxValue) { Console.Write("The two perpendicular bisectors " + "found come parallel"); Console.Write("\n"); Console.Write( "Thus, the given points do not form " + "a triangle and are collinear"); Console.Write("\n"); } else { Console.Write( "The circumcenter of the triangle PQR is: "); Console.Write("("); Console.Write(circumcenter[0]); Console.Write(", "); Console.Write(circumcenter[1]); Console.Write(")"); Console.Write("\n"); } } // Driver code. public static void Main() { List<double> P = new List<double>(); P.Add(6); P.Add(0); List<double> Q = new List<double>(); Q.Add(0); Q.Add(0); List<double> R = new List<double>(); R.Add(0); R.Add(8); findCircumCenter(P, Q, R); }} // The code is contributed by Aarti_Rathi // JavaScript program to find the CIRCUMCENTER of a// triangle // This pair is used to store the X and Y// coordinate of a point respectively// #define pdd pair<double, double> // Function to find the line given two pointsfunction lineFromPoints(P, Q){ let a = Q[1] - P[1]; let b = P[0] - Q[0]; let c = a*(P[0])+ b*(P[1]); return [a, b, c];} // Function which converts the input line to its// perpendicular bisector. It also inputs the points// whose mid-point lies on the bisectorfunction perpendicularBisectorFromLine(P, Q, a, b, c){ let mid_point = [(P[0] + Q[0])/2, (P[1] + Q[1])/2]; // c = -bx + ay c = -b*(mid_point[0]) + a*(mid_point[1]); let temp = a; a = -b; b = temp; return [a, b, c];} // Returns the intersection point of two linesfunction lineLineIntersection(a1, b1, c1, a2, b2, c2){ let determinant = a1*b2 - a2*b1; if (determinant == 0) { // The lines are parallel. This is simplified // by returning a pair of FLT_MAX return [(10.0)**19, (10.0)**19]; } else { let x = (b2*c1 - b1*c2)/determinant; let y = (a1*c2 - a2*c1)/determinant; return [x, y]; }} function findCircumCenter(P, Q, R){ // Line PQ is represented as ax + by = c let PQ_line = lineFromPoints(P, Q); let a = PQ_line[0]; let b = PQ_line[1]; let c = PQ_line[2]; // Line QR is represented as ex + fy = g let QR_line = lineFromPoints(Q, R); let e = QR_line[0]; let f = QR_line[1]; let g = QR_line[2]; // Converting lines PQ and QR to perpendicular // vbisectors. After this, L = ax + by = c // M = ex + fy = g let PQ_perpendicular = perpendicularBisectorFromLine(P, Q, a, b, c); a = PQ_perpendicular[0]; b = PQ_perpendicular[1]; c = PQ_perpendicular[2]; let QR_perpendicular = perpendicularBisectorFromLine(Q, R, e, f, g); e = QR_perpendicular[0]; f = QR_perpendicular[1]; g = QR_perpendicular[2]; // The point of intersection of L and M gives // the circumcenter let circumcenter = lineLineIntersection(a, b, c, e, f, g); if (circumcenter[0] == (10.0)**19 && circumcenter[1] == (10.0)**19){ console.log("The two perpendicular bisectors found come parallel" ) console.log("Thus, the given points do not form a triangle and are collinear"); } else{ console.log("The circumcenter of the triangle PQR is: (", circumcenter[0], ",", circumcenter[1], ")"); }} // Driver code.let P = [6, 0];let Q = [0, 0];let R = [0, 8];findCircumCenter(P, Q, R); // The code is contributed by Gautam goel (gautamgoel962) Output: The circumcenter of the triangle PQR is: (3, 4) This article is contributed by Aanya Jindal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. mohit kumar 29 gautamgoel962 _shinchancode triangle Geometric Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimum location of point to minimize total distance Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Check whether a given point lies inside a triangle or not Program for Point of Intersection of Two Lines Window to Viewport Transformation in Computer Graphics with Implementation Given n line segments, find if any two segments intersect Find K Closest Points to the Origin Closest Pair of Points | O(nlogn) Implementation Count maximum points on same line
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jun, 2022" }, { "code": null, "e": 362, "s": 52, "text": "Given 3 non-collinear points in the 2D Plane P, Q and R with their respective x and y coordinates, find the circumcenter of the triangle.Note: Circumcenter of a triangle is the centre of the circle, formed by the three vertices of a triangle. Note that three points can uniquely determine a circle.Examples: " }, { "code": null, "e": 672, "s": 362, "text": "Input : P(6, 0)\n Q(0, 0)\n R(0, 8)\nOutput : The circumcenter of the triangle PQR \n is: (3, 4)\n\nInput : P(1, 1)\n Q(0, 0)\n R(2, 2)\nOutput : The two perpendicular bisectors found \n come parallel. Thus, the given points \n do not form a triangle and are collinear" }, { "code": null, "e": 939, "s": 674, "text": "Given, three points of the triangle, we can easily find the sides of the triangle. Now, we have the equations of the lines for the three sides of the triangle. After getting these, we can find the circumcenter of the triangle by a simple property stated as under: " }, { "code": null, "e": 1059, "s": 939, "text": "The circumcenter of the triangle is point where all the perpendicular bisectors of the sides of the triangle intersect." }, { "code": null, "e": 1109, "s": 1059, "text": "This is well explained in the following diagram. " }, { "code": null, "e": 1445, "s": 1109, "text": "Note here that, there is no need to find all of the three sides of the triangle. Finding two sides is sufficient as we can uniquely find the point of intersection using just two perpendicular bisectors. The third perpendicular bisector will itself pass through the so found circumcenter.The things to be done can be divided as under: " }, { "code": null, "e": 1681, "s": 1445, "text": "Find 2 lines (say PQ and QR) which form the sides of the triangle.Find the perpendicular bisectors of PQ and QR (say lines L and M respectively).Find the point of intersection of lines L and M as the circumcenter of the given triangle." }, { "code": null, "e": 1748, "s": 1681, "text": "Find 2 lines (say PQ and QR) which form the sides of the triangle." }, { "code": null, "e": 1828, "s": 1748, "text": "Find the perpendicular bisectors of PQ and QR (say lines L and M respectively)." }, { "code": null, "e": 1919, "s": 1828, "text": "Find the point of intersection of lines L and M as the circumcenter of the given triangle." }, { "code": null, "e": 2317, "s": 1919, "text": "STEP 1 Refer this post Program to find line passing through 2 PointsSTEP 2 Let PQ be represented as ax + by = c A line perpendicular to this line is represented as -bx + ay = d for some d. However, we are interested in the perpendicular bisector. So, we find the mid-point of P and Q and putting this value in the standard equation, we get the value of d. Similarly, we repeat the process for QR. " }, { "code": null, "e": 2373, "s": 2317, "text": "d = -bx + ay\nwhere, x = (xp + xq)/2\nAND y = (yp + yq)/2" }, { "code": null, "e": 2444, "s": 2373, "text": "STEP 3 Refer this post Program for Point of Intersection of Two Lines " }, { "code": null, "e": 2448, "s": 2444, "text": "CPP" }, { "code": null, "e": 2456, "s": 2448, "text": "Python3" }, { "code": null, "e": 2459, "s": 2456, "text": "C#" }, { "code": null, "e": 2470, "s": 2459, "text": "Javascript" }, { "code": "// C++ program to find the CIRCUMCENTER of a// triangle#include <iostream>#include <cfloat>using namespace std; // This pair is used to store the X and Y// coordinate of a point respectively#define pdd pair<double, double> // Function to find the line given two pointsvoid lineFromPoints(pdd P, pdd Q, double &a, double &b, double &c){ a = Q.second - P.second; b = P.first - Q.first; c = a*(P.first)+ b*(P.second);} // Function which converts the input line to its// perpendicular bisector. It also inputs the points// whose mid-point lies on the bisectorvoid perpendicularBisectorFromLine(pdd P, pdd Q, double &a, double &b, double &c){ pdd mid_point = make_pair((P.first + Q.first)/2, (P.second + Q.second)/2); // c = -bx + ay c = -b*(mid_point.first) + a*(mid_point.second); double temp = a; a = -b; b = temp;} // Returns the intersection point of two linespdd lineLineIntersection(double a1, double b1, double c1, double a2, double b2, double c2){ double determinant = a1*b2 - a2*b1; if (determinant == 0) { // The lines are parallel. This is simplified // by returning a pair of FLT_MAX return make_pair(FLT_MAX, FLT_MAX); } else { double x = (b2*c1 - b1*c2)/determinant; double y = (a1*c2 - a2*c1)/determinant; return make_pair(x, y); }} void findCircumCenter(pdd P, pdd Q, pdd R){ // Line PQ is represented as ax + by = c double a, b, c; lineFromPoints(P, Q, a, b, c); // Line QR is represented as ex + fy = g double e, f, g; lineFromPoints(Q, R, e, f, g); // Converting lines PQ and QR to perpendicular // vbisectors. After this, L = ax + by = c // M = ex + fy = g perpendicularBisectorFromLine(P, Q, a, b, c); perpendicularBisectorFromLine(Q, R, e, f, g); // The point of intersection of L and M gives // the circumcenter pdd circumcenter = lineLineIntersection(a, b, c, e, f, g); if (circumcenter.first == FLT_MAX && circumcenter.second == FLT_MAX) { cout << \"The two perpendicular bisectors \" \"found come parallel\" << endl; cout << \"Thus, the given points do not form \" \"a triangle and are collinear\" << endl; } else { cout << \"The circumcenter of the triangle PQR is: \"; cout << \"(\" << circumcenter.first << \", \" << circumcenter.second << \")\" << endl; }} // Driver code.int main(){ pdd P = make_pair(6, 0); pdd Q = make_pair(0, 0); pdd R = make_pair(0, 8); findCircumCenter(P, Q, R); return 0;}", "e": 5128, "s": 2470, "text": null }, { "code": "# Python3 program to find the CIRCUMCENTER of a# triangle # This pair is used to store the X and Y# coordinate of a point respectively# define pair<double, double> # Function to find the line given two pointsdef lineFromPoints(P, Q, a, b, c): a = Q[1] - P[1] b = P[0] - Q[0] c = a * (P[0]) + b * (P[1]) return a, b, c # Function which converts the input line to its# perpendicular bisector. It also inputs the points# whose mid-point lies on the bisectordef perpendicularBisectorFromLine(P, Q, a, b, c): mid_point = [(P[0] + Q[0])//2, (P[1] + Q[1])//2] # c = -bx + ay c = -b * (mid_point[0]) + a * (mid_point[1]) temp = a a = -b b = temp return a, b, c # Returns the intersection point of two linesdef lineLineIntersection(a1, b1, c1, a2, b2, c2): determinant = a1 * b2 - a2 * b1 if (determinant == 0): # The lines are parallel. This is simplified # by returning a pair of (10.0)**19 return [(10.0)**19, (10.0)**19] else: x = (b2 * c1 - b1 * c2)//determinant y = (a1 * c2 - a2 * c1)//determinant return [x, y] def findCircumCenter(P, Q, R): # Line PQ is represented as ax + by = c a, b, c = 0.0, 0.0, 0.0 a, b, c = lineFromPoints(P, Q, a, b, c) # Line QR is represented as ex + fy = g e, f, g = 0.0, 0.0, 0.0 e, f, g = lineFromPoints(Q, R, e, f, g) # Converting lines PQ and QR to perpendicular # vbisectors. After this, L = ax + by = c # M = ex + fy = g a, b, c = perpendicularBisectorFromLine(P, Q, a, b, c) e, f, g = perpendicularBisectorFromLine(Q, R, e, f, g) # The point of intersection of L and M gives # the circumcenter circumcenter = lineLineIntersection(a, b, c, e, f, g) if (circumcenter[0] == (10.0)**19 and circumcenter[1] == (10.0)**19): print(\"The two perpendicular bisectors found come parallel\") print(\"Thus, the given points do not form a triangle and are collinear\") else: print(\"The circumcenter of the triangle PQR is: \", end=\"\") print(\"(\", circumcenter[0], \",\", circumcenter[1], \")\") # Driver code.if __name__ == '__main__': P = [6, 0] Q = [0, 0] R = [0, 8] findCircumCenter(P, Q, R) # This code is contributed by mohit kumar 29", "e": 7371, "s": 5128, "text": null }, { "code": "using System;using System.Collections.Generic; public static class GFG { // C# program to find the CIRCUMCENTER of a // triangle // This pair is used to store the X and Y // coordinate of a point respectively // Function to find the line given two points public static void lineFromPoints(List<double> P, List<double> Q, ref double a, ref double b, ref double c) { a = Q[1] - P[1]; b = P[0] - Q[0]; c = a * (P[0]) + b * (P[1]); } // Function which converts the input line to its // perpendicular bisector. It also inputs the points // whose mid-point lies on the bisector public static void perpendicularBisectorFromLine( List<double> P, List<double> Q, ref double a, ref double b, ref double c) { List<double> mid_point = new List<double>(); mid_point.Add((P[0] + Q[0]) / 2); mid_point.Add((P[1] + Q[1]) / 2); // c = -bx + ay c = -b * (mid_point[0]) + a * (mid_point[1]); double temp = a; a = -b; b = temp; } // Returns the intersection point of two lines public static List<double> lineLineIntersection(double a1, double b1, double c1, double a2, double b2, double c2) { List<double> ans = new List<double>(); double determinant = a1 * b2 - a2 * b1; if (determinant == 0) { // The lines are parallel. This is simplified // by returning a pair of FLT_MAX ans.Add(double.MaxValue); ans.Add(double.MaxValue); } else { double x = (b2 * c1 - b1 * c2) / determinant; double y = (a1 * c2 - a2 * c1) / determinant; ans.Add(x); ans.Add(y); } return ans; } public static void findCircumCenter(List<double> P, List<double> Q, List<double> R) { // Line PQ is represented as ax + by = c double a = 0; double b = 0; double c = 0; lineFromPoints(P, Q, ref a, ref b, ref c); // Line QR is represented as ex + fy = g double e = 0; double f = 0; double g = 0; lineFromPoints(Q, R, ref e, ref f, ref g); // Converting lines PQ and QR to perpendicular // vbisectors. After this, L = ax + by = c // M = ex + fy = g perpendicularBisectorFromLine(P, Q, ref a, ref b, ref c); perpendicularBisectorFromLine(Q, R, ref e, ref f, ref g); // The point of intersection of L and M gives // the circumcenter List<double> circumcenter = lineLineIntersection(a, b, c, e, f, g); if (circumcenter[0] == float.MaxValue && circumcenter[1] == float.MaxValue) { Console.Write(\"The two perpendicular bisectors \" + \"found come parallel\"); Console.Write(\"\\n\"); Console.Write( \"Thus, the given points do not form \" + \"a triangle and are collinear\"); Console.Write(\"\\n\"); } else { Console.Write( \"The circumcenter of the triangle PQR is: \"); Console.Write(\"(\"); Console.Write(circumcenter[0]); Console.Write(\", \"); Console.Write(circumcenter[1]); Console.Write(\")\"); Console.Write(\"\\n\"); } } // Driver code. public static void Main() { List<double> P = new List<double>(); P.Add(6); P.Add(0); List<double> Q = new List<double>(); Q.Add(0); Q.Add(0); List<double> R = new List<double>(); R.Add(0); R.Add(8); findCircumCenter(P, Q, R); }} // The code is contributed by Aarti_Rathi", "e": 11264, "s": 7371, "text": null }, { "code": "// JavaScript program to find the CIRCUMCENTER of a// triangle // This pair is used to store the X and Y// coordinate of a point respectively// #define pdd pair<double, double> // Function to find the line given two pointsfunction lineFromPoints(P, Q){ let a = Q[1] - P[1]; let b = P[0] - Q[0]; let c = a*(P[0])+ b*(P[1]); return [a, b, c];} // Function which converts the input line to its// perpendicular bisector. It also inputs the points// whose mid-point lies on the bisectorfunction perpendicularBisectorFromLine(P, Q, a, b, c){ let mid_point = [(P[0] + Q[0])/2, (P[1] + Q[1])/2]; // c = -bx + ay c = -b*(mid_point[0]) + a*(mid_point[1]); let temp = a; a = -b; b = temp; return [a, b, c];} // Returns the intersection point of two linesfunction lineLineIntersection(a1, b1, c1, a2, b2, c2){ let determinant = a1*b2 - a2*b1; if (determinant == 0) { // The lines are parallel. This is simplified // by returning a pair of FLT_MAX return [(10.0)**19, (10.0)**19]; } else { let x = (b2*c1 - b1*c2)/determinant; let y = (a1*c2 - a2*c1)/determinant; return [x, y]; }} function findCircumCenter(P, Q, R){ // Line PQ is represented as ax + by = c let PQ_line = lineFromPoints(P, Q); let a = PQ_line[0]; let b = PQ_line[1]; let c = PQ_line[2]; // Line QR is represented as ex + fy = g let QR_line = lineFromPoints(Q, R); let e = QR_line[0]; let f = QR_line[1]; let g = QR_line[2]; // Converting lines PQ and QR to perpendicular // vbisectors. After this, L = ax + by = c // M = ex + fy = g let PQ_perpendicular = perpendicularBisectorFromLine(P, Q, a, b, c); a = PQ_perpendicular[0]; b = PQ_perpendicular[1]; c = PQ_perpendicular[2]; let QR_perpendicular = perpendicularBisectorFromLine(Q, R, e, f, g); e = QR_perpendicular[0]; f = QR_perpendicular[1]; g = QR_perpendicular[2]; // The point of intersection of L and M gives // the circumcenter let circumcenter = lineLineIntersection(a, b, c, e, f, g); if (circumcenter[0] == (10.0)**19 && circumcenter[1] == (10.0)**19){ console.log(\"The two perpendicular bisectors found come parallel\" ) console.log(\"Thus, the given points do not form a triangle and are collinear\"); } else{ console.log(\"The circumcenter of the triangle PQR is: (\", circumcenter[0], \",\", circumcenter[1], \")\"); }} // Driver code.let P = [6, 0];let Q = [0, 0];let R = [0, 8];findCircumCenter(P, Q, R); // The code is contributed by Gautam goel (gautamgoel962)", "e": 13866, "s": 11264, "text": null }, { "code": null, "e": 13876, "s": 13866, "text": "Output: " }, { "code": null, "e": 13924, "s": 13876, "text": "The circumcenter of the triangle PQR is: (3, 4)" }, { "code": null, "e": 14345, "s": 13924, "text": "This article is contributed by Aanya Jindal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. " }, { "code": null, "e": 14360, "s": 14345, "text": "mohit kumar 29" }, { "code": null, "e": 14374, "s": 14360, "text": "gautamgoel962" }, { "code": null, "e": 14388, "s": 14374, "text": "_shinchancode" }, { "code": null, "e": 14397, "s": 14388, "text": "triangle" }, { "code": null, "e": 14407, "s": 14397, "text": "Geometric" }, { "code": null, "e": 14417, "s": 14407, "text": "Geometric" }, { "code": null, "e": 14515, "s": 14417, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14568, "s": 14515, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 14621, "s": 14568, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 14672, "s": 14621, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 14730, "s": 14672, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 14777, "s": 14730, "text": "Program for Point of Intersection of Two Lines" }, { "code": null, "e": 14852, "s": 14777, "text": "Window to Viewport Transformation in Computer Graphics with Implementation" }, { "code": null, "e": 14910, "s": 14852, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 14946, "s": 14910, "text": "Find K Closest Points to the Origin" }, { "code": null, "e": 14995, "s": 14946, "text": "Closest Pair of Points | O(nlogn) Implementation" } ]
Baud Rate and its importance
19 Oct, 2021 Computers communicate by transmitting bits of digital data from one device to another device through transmission media. You can send and receive data without worrying about setting up the details. However, for some devices, we need to supply baud rates and other details. Old devices use parallel and serial communication ports, though their speeds would be considered slow in today’s time. All the devices that are used today handle all the coordination of communication in the background of the computer. For example, when you plug a new device in your computer, it prompts a message like “installing device drivers” after they are installed and the device is configured you never have to repeat this process. Though for industrial devices it could be different they might ask you to provide information such as Baud rate, communication ports to route the information, etc. People often confuse baud rate with bit rate, though they are completely different. The baud rate can be higher or lower than the bit rate depending upon the type of encoding scheme used (Such as NRZ, Manchester, etc.). 1. Bit rate :Bit rate is the number of binary bits (1s or 0s) transmitted per second. Bit rate = number of bits transmitted/ total time (in seconds) The bit rate can also be defined in terms of baud rate: Bit rate = Baud rate x bits per signal or symbol 2. Baud rate :Baud rate is the rate at which the number of signal elements or changes to the signal occurs per second when it passes through a transmission medium. The higher a baud rate is the faster the data is sent/received. Baud rate = number of signal elements/total time (in seconds) For Example: Image 1 In Image 1, Number of signal elements (marked in red color) = 3, Number of bits transmitted (1, 0, 1) = 3. So, Here Bit rate = 3/1 = 3 bits per second. And, Baud rate = 3/1 = 3 baud per second. Image 2 In Image 2, Number of signal elements (marked in red color) = 6, Number of bits transmitted (1, 1, 0) = 3. So, Here Bit rate = 3/1 = 3 bits per second. and, Baud rate = 6/1 = 6 baud per second. Signal element: A signal element is the smallest unit of a digital signal. A signal is one of several voltages, phase changes, or frequencies. For Digital signals 1 signal element is a signal with constant amplitude. For Analog signals, 1 signal element is a signal with the same amplitude, phase, and frequency. Why baud rate is important ?Baud rate is important because: Baud rate can determine the bandwidth requirements for transmission of the signal. Baud rate is also used for the calculation of the Bit rate of a communication channel. It is a tuning parameter (i.e., it adjusts the Network congestion in data networking) for the transmission of a signal. It specifies how fast data can be sent over a serial line or serial interface (it’s an interface that sends data as a series of bits over a single wire.). Picked Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) Advanced Encryption Standard (AES) Introduction of Mobile Ad hoc Network (MANET) Intrusion Detection System (IDS) Cryptography and its Types Difference between URL and URI Dynamic Host Configuration Protocol (DHCP)
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Oct, 2021" }, { "code": null, "e": 301, "s": 28, "text": "Computers communicate by transmitting bits of digital data from one device to another device through transmission media. You can send and receive data without worrying about setting up the details. However, for some devices, we need to supply baud rates and other details." }, { "code": null, "e": 537, "s": 301, "text": "Old devices use parallel and serial communication ports, though their speeds would be considered slow in today’s time. All the devices that are used today handle all the coordination of communication in the background of the computer. " }, { "code": null, "e": 906, "s": 537, "text": "For example, when you plug a new device in your computer, it prompts a message like “installing device drivers” after they are installed and the device is configured you never have to repeat this process. Though for industrial devices it could be different they might ask you to provide information such as Baud rate, communication ports to route the information, etc." }, { "code": null, "e": 1126, "s": 906, "text": "People often confuse baud rate with bit rate, though they are completely different. The baud rate can be higher or lower than the bit rate depending upon the type of encoding scheme used (Such as NRZ, Manchester, etc.)." }, { "code": null, "e": 1212, "s": 1126, "text": "1. Bit rate :Bit rate is the number of binary bits (1s or 0s) transmitted per second." }, { "code": null, "e": 1275, "s": 1212, "text": "Bit rate = number of bits transmitted/ total time (in seconds)" }, { "code": null, "e": 1331, "s": 1275, "text": "The bit rate can also be defined in terms of baud rate:" }, { "code": null, "e": 1380, "s": 1331, "text": "Bit rate = Baud rate x bits per signal or symbol" }, { "code": null, "e": 1608, "s": 1380, "text": "2. Baud rate :Baud rate is the rate at which the number of signal elements or changes to the signal occurs per second when it passes through a transmission medium. The higher a baud rate is the faster the data is sent/received." }, { "code": null, "e": 1670, "s": 1608, "text": "Baud rate = number of signal elements/total time (in seconds)" }, { "code": null, "e": 1684, "s": 1670, "text": "For Example: " }, { "code": null, "e": 1692, "s": 1684, "text": "Image 1" }, { "code": null, "e": 1886, "s": 1692, "text": "In Image 1, Number of signal elements (marked in red color) = 3, Number of bits transmitted (1, 0, 1) = 3. So, Here Bit rate = 3/1 = 3 bits per second. And, Baud rate = 3/1 = 3 baud per second." }, { "code": null, "e": 1894, "s": 1886, "text": "Image 2" }, { "code": null, "e": 2088, "s": 1894, "text": "In Image 2, Number of signal elements (marked in red color) = 6, Number of bits transmitted (1, 1, 0) = 3. So, Here Bit rate = 3/1 = 3 bits per second. and, Baud rate = 6/1 = 6 baud per second." }, { "code": null, "e": 2401, "s": 2088, "text": "Signal element: A signal element is the smallest unit of a digital signal. A signal is one of several voltages, phase changes, or frequencies. For Digital signals 1 signal element is a signal with constant amplitude. For Analog signals, 1 signal element is a signal with the same amplitude, phase, and frequency." }, { "code": null, "e": 2462, "s": 2401, "text": "Why baud rate is important ?Baud rate is important because: " }, { "code": null, "e": 2545, "s": 2462, "text": "Baud rate can determine the bandwidth requirements for transmission of the signal." }, { "code": null, "e": 2632, "s": 2545, "text": "Baud rate is also used for the calculation of the Bit rate of a communication channel." }, { "code": null, "e": 2752, "s": 2632, "text": "It is a tuning parameter (i.e., it adjusts the Network congestion in data networking) for the transmission of a signal." }, { "code": null, "e": 2907, "s": 2752, "text": "It specifies how fast data can be sent over a serial line or serial interface (it’s an interface that sends data as a series of bits over a single wire.)." }, { "code": null, "e": 2914, "s": 2907, "text": "Picked" }, { "code": null, "e": 2932, "s": 2914, "text": "Computer Networks" }, { "code": null, "e": 2950, "s": 2932, "text": "Computer Networks" }, { "code": null, "e": 3048, "s": 2950, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3078, "s": 3048, "text": "GSM in Wireless Communication" }, { "code": null, "e": 3104, "s": 3078, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 3134, "s": 3104, "text": "Wireless Application Protocol" }, { "code": null, "e": 3174, "s": 3134, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 3209, "s": 3174, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 3255, "s": 3209, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 3288, "s": 3255, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 3315, "s": 3288, "text": "Cryptography and its Types" }, { "code": null, "e": 3346, "s": 3315, "text": "Difference between URL and URI" } ]
Radar Chart or Spider Chart in Excel
24 May, 2021 Radar Chart is a pictorial representation of multivariate data. Multivariate data analysis in statistics is nothing but dealing with more than one outcome or observations. Radar graphs can be of two dimensions, three dimensions, or more on the basis of the multiple comparable variables used. The variables are represented on the axis starting from the same points with equal intervals on the axes. The number of axes in a radar graph solely depends on the number of variables used. The Radar Chart has various other names like spider chart, web chart, spider web chart, cobweb chart, irregular polygon, star chart, Kiviat Diagram, etc. The data from the observations in the form of tables are plotted on each axis and by joining all these points in the axes a polygon type structure is formed. So, the number of polygons is dependent on the number of observations. In this article, we will see how to plot a Radar Chart in Microsoft Excel for a given data set using two examples. Example 1 : Consider the table shown below which consists of the data of two Geek students who enrolled in our various courses. Our mentors have rated them on the basis of the student’s performance in the individual course. The rating is on a scale of 0 to 5. The demonstration is done in Microsoft Excel Version 2010. Students Performance in GeeksforGeeks (Scale 0-5, 5 is the maximum rating) Step 1: Make the above dataset in MS Excel. There should be three columns and six rows. Now select all the rows and columns and click on the “Insert” button as shown below. Then click on the “Other Charts” followed by Radar. Select -> Insert -> Other Charts -> Radar Creating a Radar Chart Step 2: There are basically three types of Radar Charts in SQL. They are “Radar”, “Radar with Markers”, “Filled Radar”. Let’s select normal radar and observe the chart for the given dataset. Radar Chart We can observe that two polygons are formed by joining all the data points in the axes. The blue polygon depicts the performance of Parvez in the courses and similarly, the dark red polygon is about Sonia’s performance. Step 3: Now, we can perform various format operations and make the chart more informative and beautiful by adding titles and changing color. We can select from various chart layouts and styles according to our requirements. To add Title, select the first option from the “Chart Layout” option as highlighted in the image below and add a suitable title. Unlike Excel Version 2016 or higher, there is no direct drop-down menu to format the graph. So, just right-click on the point in the chart which needs to be formatted. To perform more operations like changing the color, increasing the font, etc. simply right-click and do the formatting. Formatting the Radar Chart Step 4: Now to change the Radar type, right-click on the chart and select the “Change Chart Type” option and then select the Radar with marker chart or Filled Radar Chart. Radar Chart with Marker Filled Radar Chart The above two polygons are equally likely. Their size and shape almost the same which infer that both have similar performance in the courses. Geek Parvez got better ratings in DSA and Python courses and in Java Geek Sonia got better ratings than Parvez. Similarly, we can do comparative analysis on the basis of the polygons formed. Now let’s take a second example and see how we can make a Radar Chart in Excel 2016 version or higher. Example 2: Consider the table shown below which consists of the data about the count of the number of employees having birthdays per month. Step 1: It is exactly the same as above. The only difference would be the change of icon for adding the Radar Chart as shown below : Creating Radar Chart Step 2: The chart will be formed and now various formatting operations can be done as shown. Click on the ” [+] ” symbol in the top right corner for adding titles, legends, formatting, etc. For formatting, select the chart and then click on the chart elements needed to be formatted and then click on More Options. Select Chart -> Click on Plus Button -> Click on Chart Elements -> Click on the Black arrow beside the Chart element to be edited -> Click More Options -> Format Window Opens Radar Chart Step 3: A suitable Chart Style can be selected from the menu in the top right corner of the chart. Step 4: Axis can be modified using the format window as discussed above. The gridlines on the axes can be added by clicking on Radar (Value) Axis in the Format Axis window and then make the line “Solid Line”. Opening the Format Window Formatting the Axis Step 5: Some other modifications can be done in the above chart according to one’s requirements. Now, we can also change the Radar Type as discussed in Example 1. Radar Type Finally, after all the modifications and addition of legends, titles, type the chart looks like : Marked Radar Chart Filled Radar Chart From the polygon, we can infer that the maximum employees birthdays fall in the month of November and the minimum in the month of August. The major flaw is when the number of axes and variables increases the number of polygons also increases. So, the spider chart becomes confusing and crowded with data as shown below. There is a high chance that a lot of polygons will overlap with each other. This will prohibit doing correct comparative analysis. It is recommended to keep few variables for forming polygons and few axes for better inferences from the chart. Complex Radar Chart Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Delete Blank Columns in Excel? How to Normalize Data in Excel? How to Get Length of Array in Excel VBA? How to Find the Last Used Row and Column in Excel VBA? How to Use Solver in Excel? How to make a 3 Axis Graph using Excel? Introduction to Excel Spreadsheet Macros in Excel How to Create a Macro in Excel? How to Show Percentages in Stacked Column Chart in Excel?
[ { "code": null, "e": 54, "s": 26, "text": "\n24 May, 2021" }, { "code": null, "e": 538, "s": 54, "text": "Radar Chart is a pictorial representation of multivariate data. Multivariate data analysis in statistics is nothing but dealing with more than one outcome or observations. Radar graphs can be of two dimensions, three dimensions, or more on the basis of the multiple comparable variables used. The variables are represented on the axis starting from the same points with equal intervals on the axes. The number of axes in a radar graph solely depends on the number of variables used. " }, { "code": null, "e": 923, "s": 538, "text": "The Radar Chart has various other names like spider chart, web chart, spider web chart, cobweb chart, irregular polygon, star chart, Kiviat Diagram, etc. The data from the observations in the form of tables are plotted on each axis and by joining all these points in the axes a polygon type structure is formed. So, the number of polygons is dependent on the number of observations." }, { "code": null, "e": 1039, "s": 923, "text": "In this article, we will see how to plot a Radar Chart in Microsoft Excel for a given data set using two examples. " }, { "code": null, "e": 1358, "s": 1039, "text": "Example 1 : Consider the table shown below which consists of the data of two Geek students who enrolled in our various courses. Our mentors have rated them on the basis of the student’s performance in the individual course. The rating is on a scale of 0 to 5. The demonstration is done in Microsoft Excel Version 2010." }, { "code": null, "e": 1396, "s": 1358, "text": "Students Performance in GeeksforGeeks" }, { "code": null, "e": 1433, "s": 1396, "text": "(Scale 0-5, 5 is the maximum rating)" }, { "code": null, "e": 1658, "s": 1433, "text": "Step 1: Make the above dataset in MS Excel. There should be three columns and six rows. Now select all the rows and columns and click on the “Insert” button as shown below. Then click on the “Other Charts” followed by Radar." }, { "code": null, "e": 1700, "s": 1658, "text": "Select -> Insert -> Other Charts -> Radar" }, { "code": null, "e": 1723, "s": 1700, "text": "Creating a Radar Chart" }, { "code": null, "e": 1914, "s": 1723, "text": "Step 2: There are basically three types of Radar Charts in SQL. They are “Radar”, “Radar with Markers”, “Filled Radar”. Let’s select normal radar and observe the chart for the given dataset." }, { "code": null, "e": 1926, "s": 1914, "text": "Radar Chart" }, { "code": null, "e": 2146, "s": 1926, "text": "We can observe that two polygons are formed by joining all the data points in the axes. The blue polygon depicts the performance of Parvez in the courses and similarly, the dark red polygon is about Sonia’s performance." }, { "code": null, "e": 2499, "s": 2146, "text": "Step 3: Now, we can perform various format operations and make the chart more informative and beautiful by adding titles and changing color. We can select from various chart layouts and styles according to our requirements. To add Title, select the first option from the “Chart Layout” option as highlighted in the image below and add a suitable title." }, { "code": null, "e": 2667, "s": 2499, "text": "Unlike Excel Version 2016 or higher, there is no direct drop-down menu to format the graph. So, just right-click on the point in the chart which needs to be formatted." }, { "code": null, "e": 2787, "s": 2667, "text": "To perform more operations like changing the color, increasing the font, etc. simply right-click and do the formatting." }, { "code": null, "e": 2814, "s": 2787, "text": "Formatting the Radar Chart" }, { "code": null, "e": 2986, "s": 2814, "text": "Step 4: Now to change the Radar type, right-click on the chart and select the “Change Chart Type” option and then select the Radar with marker chart or Filled Radar Chart." }, { "code": null, "e": 3010, "s": 2986, "text": "Radar Chart with Marker" }, { "code": null, "e": 3029, "s": 3010, "text": "Filled Radar Chart" }, { "code": null, "e": 3363, "s": 3029, "text": "The above two polygons are equally likely. Their size and shape almost the same which infer that both have similar performance in the courses. Geek Parvez got better ratings in DSA and Python courses and in Java Geek Sonia got better ratings than Parvez. Similarly, we can do comparative analysis on the basis of the polygons formed." }, { "code": null, "e": 3466, "s": 3363, "text": "Now let’s take a second example and see how we can make a Radar Chart in Excel 2016 version or higher." }, { "code": null, "e": 3606, "s": 3466, "text": "Example 2: Consider the table shown below which consists of the data about the count of the number of employees having birthdays per month." }, { "code": null, "e": 3739, "s": 3606, "text": "Step 1: It is exactly the same as above. The only difference would be the change of icon for adding the Radar Chart as shown below :" }, { "code": null, "e": 3760, "s": 3739, "text": "Creating Radar Chart" }, { "code": null, "e": 3952, "s": 3760, "text": "Step 2: The chart will be formed and now various formatting operations can be done as shown. Click on the ” [+] ” symbol in the top right corner for adding titles, legends, formatting, etc. " }, { "code": null, "e": 4077, "s": 3952, "text": "For formatting, select the chart and then click on the chart elements needed to be formatted and then click on More Options." }, { "code": null, "e": 4255, "s": 4077, "text": "Select Chart -> Click on Plus Button -> Click on Chart Elements -> \nClick on the Black arrow beside the Chart element to be edited -> Click More Options -> Format Window Opens" }, { "code": null, "e": 4267, "s": 4255, "text": "Radar Chart" }, { "code": null, "e": 4366, "s": 4267, "text": "Step 3: A suitable Chart Style can be selected from the menu in the top right corner of the chart." }, { "code": null, "e": 4575, "s": 4366, "text": "Step 4: Axis can be modified using the format window as discussed above. The gridlines on the axes can be added by clicking on Radar (Value) Axis in the Format Axis window and then make the line “Solid Line”." }, { "code": null, "e": 4601, "s": 4575, "text": "Opening the Format Window" }, { "code": null, "e": 4621, "s": 4601, "text": "Formatting the Axis" }, { "code": null, "e": 4784, "s": 4621, "text": "Step 5: Some other modifications can be done in the above chart according to one’s requirements. Now, we can also change the Radar Type as discussed in Example 1." }, { "code": null, "e": 4795, "s": 4784, "text": "Radar Type" }, { "code": null, "e": 4893, "s": 4795, "text": "Finally, after all the modifications and addition of legends, titles, type the chart looks like :" }, { "code": null, "e": 4912, "s": 4893, "text": "Marked Radar Chart" }, { "code": null, "e": 4931, "s": 4912, "text": "Filled Radar Chart" }, { "code": null, "e": 5070, "s": 4931, "text": "From the polygon, we can infer that the maximum employees birthdays fall in the month of November and the minimum in the month of August. " }, { "code": null, "e": 5495, "s": 5070, "text": "The major flaw is when the number of axes and variables increases the number of polygons also increases. So, the spider chart becomes confusing and crowded with data as shown below. There is a high chance that a lot of polygons will overlap with each other. This will prohibit doing correct comparative analysis. It is recommended to keep few variables for forming polygons and few axes for better inferences from the chart." }, { "code": null, "e": 5515, "s": 5495, "text": "Complex Radar Chart" }, { "code": null, "e": 5522, "s": 5515, "text": "Picked" }, { "code": null, "e": 5528, "s": 5522, "text": "Excel" }, { "code": null, "e": 5626, "s": 5528, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5664, "s": 5626, "text": "How to Delete Blank Columns in Excel?" }, { "code": null, "e": 5696, "s": 5664, "text": "How to Normalize Data in Excel?" }, { "code": null, "e": 5737, "s": 5696, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 5792, "s": 5737, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 5820, "s": 5792, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 5860, "s": 5820, "text": "How to make a 3 Axis Graph using Excel?" }, { "code": null, "e": 5894, "s": 5860, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 5910, "s": 5894, "text": "Macros in Excel" }, { "code": null, "e": 5942, "s": 5910, "text": "How to Create a Macro in Excel?" } ]
Java Program to Convert File to a Byte Array
22 Apr, 2022 Here, we will go through the different ways to convert file to byte array in Java. Note: Keep a check that prior doing anything first. Create a file on the system repository to deal with our program\writing a program as we will be accessing the same directory through our programs. Methods: Using read(byte[]) method of FileInputStream classUsing Files.readAllBytes() method Using read(byte[]) method of FileInputStream class Using Files.readAllBytes() method FileInputStream is useful to read data from a file in the form of a sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. read(byte[]) method of FileInputStream class which reads up to the length of the file and then converts bytes of data from this input stream into the byte array. Procedure: Create an instance of File Input Stream with the file path.Create a byte array of the same length as the file.Read that file content to an array.Print the byte array.Close the instance of the file input stream as it is a good practice in order to avoid any exception or error being faced during runtime and to release the memory resources making our program optimized leading to faster execution. Create an instance of File Input Stream with the file path. Create a byte array of the same length as the file. Read that file content to an array. Print the byte array. Close the instance of the file input stream as it is a good practice in order to avoid any exception or error being faced during runtime and to release the memory resources making our program optimized leading to faster execution. Implementation: In order to illustrate the conversion of a text file present in the local directory on a machine to the byte array, we will be considering a random file named say it be ‘demo.rtf’ which is present in the local directory. Example: Java // Java Program to Convert File to a Byte Array// Using read(byte[]) Method // Importing required classesimport java.io.*;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.util.Arrays; // Main classpublic class GFG { // Method 1 // To convert file to byte array public static byte[] method(File file) throws IOException { // Creating an object of FileInputStream to // read from a file FileInputStream fl = new FileInputStream(file); // Now creating byte array of same length as file byte[] arr = new byte[(int)file.length()]; // Reading file content to byte array // using standard read() method fl.read(arr); // lastly closing an instance of file input stream // to avoid memory leakage fl.close(); // Returning above byte array return arr; } // Method 2 // Main driver method public static void main(String[] args) throws IOException { // Creating an object of File class and // providing local directory path of a file File path = new File( "/Users/mayanksolanki/Desktop/demo.rtf"); // Calling the Method1 in main() to // convert file to byte array byte[] array = method(path); // Printing the byte array System.out.print(Arrays.toString(array)); }} Output: java.nio.file.Files class has pre-defined readAllBytes() method which reads all the bytes from a file. Procedure: Take a text file pathConvert that file into a byte array by calling Files.readAllBytes().Print the byte array. Take a text file path Convert that file into a byte array by calling Files.readAllBytes(). Print the byte array. Example: Java // Java Program to Convert File to a Byte Array// Using Files.readAllBytes() Method // Importing required classesimport java.io.*;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.util.Arrays; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating an object of Path class and // assigning local directory path of file to it Path path = Paths.get( "/Users/mayanksolanki/Desktop/demo.rtf"); // Converting the file into a byte array // using Files.readAllBytes() method byte[] arr = Files.readAllBytes(path); // Printing the above byte array System.out.println(Arrays.toString(arr)); }} Output: sweetyty solankimayank Java-Array-Programs Java-Files Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Apr, 2022" }, { "code": null, "e": 136, "s": 53, "text": "Here, we will go through the different ways to convert file to byte array in Java." }, { "code": null, "e": 335, "s": 136, "text": "Note: Keep a check that prior doing anything first. Create a file on the system repository to deal with our program\\writing a program as we will be accessing the same directory through our programs." }, { "code": null, "e": 344, "s": 335, "text": "Methods:" }, { "code": null, "e": 429, "s": 344, "text": "Using read(byte[]) method of FileInputStream classUsing Files.readAllBytes() method " }, { "code": null, "e": 480, "s": 429, "text": "Using read(byte[]) method of FileInputStream class" }, { "code": null, "e": 515, "s": 480, "text": "Using Files.readAllBytes() method " }, { "code": null, "e": 904, "s": 515, "text": "FileInputStream is useful to read data from a file in the form of a sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. read(byte[]) method of FileInputStream class which reads up to the length of the file and then converts bytes of data from this input stream into the byte array." }, { "code": null, "e": 915, "s": 904, "text": "Procedure:" }, { "code": null, "e": 1312, "s": 915, "text": "Create an instance of File Input Stream with the file path.Create a byte array of the same length as the file.Read that file content to an array.Print the byte array.Close the instance of the file input stream as it is a good practice in order to avoid any exception or error being faced during runtime and to release the memory resources making our program optimized leading to faster execution." }, { "code": null, "e": 1372, "s": 1312, "text": "Create an instance of File Input Stream with the file path." }, { "code": null, "e": 1424, "s": 1372, "text": "Create a byte array of the same length as the file." }, { "code": null, "e": 1460, "s": 1424, "text": "Read that file content to an array." }, { "code": null, "e": 1482, "s": 1460, "text": "Print the byte array." }, { "code": null, "e": 1713, "s": 1482, "text": "Close the instance of the file input stream as it is a good practice in order to avoid any exception or error being faced during runtime and to release the memory resources making our program optimized leading to faster execution." }, { "code": null, "e": 1951, "s": 1713, "text": "Implementation: In order to illustrate the conversion of a text file present in the local directory on a machine to the byte array, we will be considering a random file named say it be ‘demo.rtf’ which is present in the local directory. " }, { "code": null, "e": 1960, "s": 1951, "text": "Example:" }, { "code": null, "e": 1965, "s": 1960, "text": "Java" }, { "code": "// Java Program to Convert File to a Byte Array// Using read(byte[]) Method // Importing required classesimport java.io.*;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.util.Arrays; // Main classpublic class GFG { // Method 1 // To convert file to byte array public static byte[] method(File file) throws IOException { // Creating an object of FileInputStream to // read from a file FileInputStream fl = new FileInputStream(file); // Now creating byte array of same length as file byte[] arr = new byte[(int)file.length()]; // Reading file content to byte array // using standard read() method fl.read(arr); // lastly closing an instance of file input stream // to avoid memory leakage fl.close(); // Returning above byte array return arr; } // Method 2 // Main driver method public static void main(String[] args) throws IOException { // Creating an object of File class and // providing local directory path of a file File path = new File( \"/Users/mayanksolanki/Desktop/demo.rtf\"); // Calling the Method1 in main() to // convert file to byte array byte[] array = method(path); // Printing the byte array System.out.print(Arrays.toString(array)); }}", "e": 3383, "s": 1965, "text": null }, { "code": null, "e": 3392, "s": 3383, "text": " Output:" }, { "code": null, "e": 3495, "s": 3392, "text": "java.nio.file.Files class has pre-defined readAllBytes() method which reads all the bytes from a file." }, { "code": null, "e": 3507, "s": 3495, "text": "Procedure: " }, { "code": null, "e": 3618, "s": 3507, "text": "Take a text file pathConvert that file into a byte array by calling Files.readAllBytes().Print the byte array." }, { "code": null, "e": 3640, "s": 3618, "text": "Take a text file path" }, { "code": null, "e": 3709, "s": 3640, "text": "Convert that file into a byte array by calling Files.readAllBytes()." }, { "code": null, "e": 3731, "s": 3709, "text": "Print the byte array." }, { "code": null, "e": 3740, "s": 3731, "text": "Example:" }, { "code": null, "e": 3745, "s": 3740, "text": "Java" }, { "code": "// Java Program to Convert File to a Byte Array// Using Files.readAllBytes() Method // Importing required classesimport java.io.*;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.util.Arrays; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating an object of Path class and // assigning local directory path of file to it Path path = Paths.get( \"/Users/mayanksolanki/Desktop/demo.rtf\"); // Converting the file into a byte array // using Files.readAllBytes() method byte[] arr = Files.readAllBytes(path); // Printing the above byte array System.out.println(Arrays.toString(arr)); }}", "e": 4565, "s": 3745, "text": null }, { "code": null, "e": 4574, "s": 4565, "text": "Output: " }, { "code": null, "e": 4583, "s": 4574, "text": "sweetyty" }, { "code": null, "e": 4597, "s": 4583, "text": "solankimayank" }, { "code": null, "e": 4617, "s": 4597, "text": "Java-Array-Programs" }, { "code": null, "e": 4628, "s": 4617, "text": "Java-Files" }, { "code": null, "e": 4635, "s": 4628, "text": "Picked" }, { "code": null, "e": 4640, "s": 4635, "text": "Java" }, { "code": null, "e": 4654, "s": 4640, "text": "Java Programs" }, { "code": null, "e": 4659, "s": 4654, "text": "Java" }, { "code": null, "e": 4757, "s": 4659, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4772, "s": 4757, "text": "Stream In Java" }, { "code": null, "e": 4793, "s": 4772, "text": "Introduction to Java" }, { "code": null, "e": 4814, "s": 4793, "text": "Constructors in Java" }, { "code": null, "e": 4833, "s": 4814, "text": "Exceptions in Java" }, { "code": null, "e": 4850, "s": 4833, "text": "Generics in Java" }, { "code": null, "e": 4876, "s": 4850, "text": "Java Programming Examples" }, { "code": null, "e": 4910, "s": 4876, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 4957, "s": 4910, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4995, "s": 4957, "text": "Factory method design pattern in Java" } ]
Prototype - addClassName() Method
This method Adds a CSS class to element. element.addClassName(className); An HTML element in which CSS class is added. <html> <head> <title>Prototype examples</title> <script type="text/javascript" src = "/javascript/prototype.js"></script> <script> function addClass() { node = $("firstDiv"); node.addClassName("title"); } </script> </head> <style type = "text/css"> .title { color:#36C; font-size:20px; } </style> <body> <div id = "firstDiv"> <p>This is first paragraph</p> </div> <br /> <input type = "button" value = "Add Class" onclick = "addClass();"/> </body> </html> This is first paragraph
[ { "code": null, "e": 2236, "s": 2195, "text": "This method Adds a CSS class to element." }, { "code": null, "e": 2270, "s": 2236, "text": "element.addClassName(className);\n" }, { "code": null, "e": 2315, "s": 2270, "text": "An HTML element in which CSS class is added." }, { "code": null, "e": 2938, "s": 2315, "text": "<html>\n <head>\n <title>Prototype examples</title>\n <script type=\"text/javascript\" src = \"/javascript/prototype.js\"></script>\n \n <script>\n function addClass() {\n node = $(\"firstDiv\");\n node.addClassName(\"title\");\n }\n </script>\n </head>\n\n <style type = \"text/css\">\n .title {\n color:#36C;\n font-size:20px;\n }\n </style>\n \n <body>\n <div id = \"firstDiv\">\n <p>This is first paragraph</p> \n </div>\n <br />\n \n <input type = \"button\" value = \"Add Class\" onclick = \"addClass();\"/>\n </body>\n</html>" } ]
Ruby | Array length() function
06 Dec, 2019 Array#length() : length() is a Array class method which returns the number of elements in the array. Syntax: Array.length() Parameter: Array Return: the number of elements in the array. Example #1 : # Ruby code for length() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 50, 6] # length method exampleputs "length() method form : #{a.length()}\n\n" puts "length() method form : #{b.length()}\n\n" puts "length() method form : #{c.length()}\n\n" Output : length() method form : 6 length() method form : 6 length() method form : 4 Example #2 : # Ruby code for length() method # declaring arraya = ["abc", "nil", "dog"] # declaring arrayc = ["cat", nil] # declaring arrayb = ["cow", nil, "dog"] # length method exampleputs "length() method form : #{a.length()}\n\n" puts "length() method form : #{b.length()}\n\n" puts "length() method form : #{c.length()}\n\n" Output : length() method form : 3 length() method form : 3 length() method form : 2 Ruby Array-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Global Variable in Ruby Ruby | Enumerator each_with_index function Ruby | Array select() function Ruby | Case Statement Ruby | unless Statement and unless Modifier Ruby | Hash delete() function Ruby | Data Types Ruby | Array class find_index() operation Ruby For Beginners
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Dec, 2019" }, { "code": null, "e": 153, "s": 52, "text": "Array#length() : length() is a Array class method which returns the number of elements in the array." }, { "code": null, "e": 176, "s": 153, "text": "Syntax: Array.length()" }, { "code": null, "e": 193, "s": 176, "text": "Parameter: Array" }, { "code": null, "e": 238, "s": 193, "text": "Return: the number of elements in the array." }, { "code": null, "e": 251, "s": 238, "text": "Example #1 :" }, { "code": "# Ruby code for length() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 50, 6] # length method exampleputs \"length() method form : #{a.length()}\\n\\n\" puts \"length() method form : #{b.length()}\\n\\n\" puts \"length() method form : #{c.length()}\\n\\n\"", "e": 579, "s": 251, "text": null }, { "code": null, "e": 588, "s": 579, "text": "Output :" }, { "code": null, "e": 667, "s": 588, "text": "length() method form : 6\n\nlength() method form : 6\n\nlength() method form : 4\n\n" }, { "code": null, "e": 680, "s": 667, "text": "Example #2 :" }, { "code": "# Ruby code for length() method # declaring arraya = [\"abc\", \"nil\", \"dog\"] # declaring arrayc = [\"cat\", nil] # declaring arrayb = [\"cow\", nil, \"dog\"] # length method exampleputs \"length() method form : #{a.length()}\\n\\n\" puts \"length() method form : #{b.length()}\\n\\n\" puts \"length() method form : #{c.length()}\\n\\n\"", "e": 1005, "s": 680, "text": null }, { "code": null, "e": 1014, "s": 1005, "text": "Output :" }, { "code": null, "e": 1093, "s": 1014, "text": "length() method form : 3\n\nlength() method form : 3\n\nlength() method form : 2\n\n" }, { "code": null, "e": 1110, "s": 1093, "text": "Ruby Array-class" }, { "code": null, "e": 1123, "s": 1110, "text": "Ruby-Methods" }, { "code": null, "e": 1128, "s": 1123, "text": "Ruby" }, { "code": null, "e": 1226, "s": 1128, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1272, "s": 1226, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 1296, "s": 1272, "text": "Global Variable in Ruby" }, { "code": null, "e": 1339, "s": 1296, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 1370, "s": 1339, "text": "Ruby | Array select() function" }, { "code": null, "e": 1392, "s": 1370, "text": "Ruby | Case Statement" }, { "code": null, "e": 1436, "s": 1392, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 1466, "s": 1436, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 1484, "s": 1466, "text": "Ruby | Data Types" }, { "code": null, "e": 1526, "s": 1484, "text": "Ruby | Array class find_index() operation" } ]
How do you separate zeros from non-zeros in an integer array using Java?
To separate zeros from non-zeros in an integer array, and push them to the end, you need to rearrange it array by assigning all the nonzero elements to its positions, sequentially, starting from zero. Then, from last position of the array to its end populate it with zeros. Following Java program pushes all the zeros in an array to its end. import java.util.Arrays; import java.util.Scanner; public class ZerosFromNonZeros { public static void main(String args[]){ //Reading the array from the user Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created: "); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array: "); for(int i=0; i<size; i++){ myArray[i] = sc.nextInt(); } System.out.println("The array created is: "+Arrays.toString(myArray)); System.out.println("Resultant array: "); int pos = 0; for(int i=0; i<myArray.length; i++){ if(myArray[i]!=0){ myArray[pos]=myArray[i]; pos++; } } while(pos<myArray.length) { myArray[pos] = 0; pos++; } System.out.println("The array created is: "+Arrays.toString(myArray)); } } Enter the size of the array that is to be created: 8 Enter the elements of the array: 14 0 56 0 12 47 0 0 The array created is: [14, 0, 56, 0, 12, 47, 0, 0] Resultant array: The array created is: [14, 56, 12, 47, 0, 0, 0, 0] In the same way to place the zeros at the starting of the array, iterate the elements of the array backwards, arrange each non-zero element in the array sequentially starting from the last position. Finally, fill the remaining positions with zeros. rearrange it array by assigning all the nonzero elements to its positions, sequentially, starting from zero. Then, from last position of the array to its end populate it with zeros. Following Java program pushes all the zeros in an array to the start. import java.util.Arrays; import java.util.Scanner; public class ZerosFromNonZeros { public static void main(String args[]){ //Reading the array from the user Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created: "); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array: "); for(int i=0; i<size; i++){ myArray[i] = sc.nextInt(); } System.out.println("The array created is: "+Arrays.toString(myArray)); System.out.println("Resultant array: "); int pos = myArray.length-1; for(int i = myArray.length-1; i>=0; i--){ if(myArray[i]!=0){ myArray[pos]=myArray[i]; pos--; } } while(pos>=0) { myArray[pos] = 0; pos--; } System.out.println("The array created is: "+Arrays.toString(myArray)); } } Enter the size of the array that is to be created: 8 Enter the elements of the array: 14 0 56 0 12 47 0 0 The array created is: [14, 0, 56, 0, 12, 47, 0, 0] Resultant array: The array created is: [0, 0, 0, 0, 14, 56, 12, 47]
[ { "code": null, "e": 1336, "s": 1062, "text": "To separate zeros from non-zeros in an integer array, and push them to the end, you need to rearrange it array by assigning all the nonzero elements to its positions, sequentially, starting from zero. Then, from last position of the array to its end populate it with zeros." }, { "code": null, "e": 1404, "s": 1336, "text": "Following Java program pushes all the zeros in an array to its end." }, { "code": null, "e": 2361, "s": 1404, "text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class ZerosFromNonZeros {\n public static void main(String args[]){\n //Reading the array from the user\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the size of the array that is to be created: \");\n int size = sc.nextInt();\n int[] myArray = new int[size];\n System.out.println(\"Enter the elements of the array: \");\n for(int i=0; i<size; i++){\n myArray[i] = sc.nextInt();\n }\n System.out.println(\"The array created is: \"+Arrays.toString(myArray));\n System.out.println(\"Resultant array: \");\n int pos = 0;\n for(int i=0; i<myArray.length; i++){\n if(myArray[i]!=0){\n myArray[pos]=myArray[i];\n pos++;\n }\n }\n while(pos<myArray.length) {\n myArray[pos] = 0;\n pos++;\n }\n System.out.println(\"The array created is: \"+Arrays.toString(myArray));\n }\n}" }, { "code": null, "e": 2586, "s": 2361, "text": "Enter the size of the array that is to be created:\n8\nEnter the elements of the array:\n14\n0\n56\n0\n12\n47\n0\n0\nThe array created is: [14, 0, 56, 0, 12, 47, 0, 0]\nResultant array:\nThe array created is: [14, 56, 12, 47, 0, 0, 0, 0]" }, { "code": null, "e": 2835, "s": 2586, "text": "In the same way to place the zeros at the starting of the array, iterate the elements of the array backwards, arrange each non-zero element in the array sequentially starting from the last position. Finally, fill the remaining positions with zeros." }, { "code": null, "e": 3017, "s": 2835, "text": "rearrange it array by assigning all the nonzero elements to its positions, sequentially, starting from zero. Then, from last position of the array to its end populate it with zeros." }, { "code": null, "e": 3087, "s": 3017, "text": "Following Java program pushes all the zeros in an array to the start." }, { "code": null, "e": 4052, "s": 3087, "text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class ZerosFromNonZeros {\n public static void main(String args[]){\n //Reading the array from the user\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the size of the array that is to be created: \");\n int size = sc.nextInt();\n int[] myArray = new int[size];\n System.out.println(\"Enter the elements of the array: \");\n for(int i=0; i<size; i++){\n myArray[i] = sc.nextInt();\n }\n System.out.println(\"The array created is: \"+Arrays.toString(myArray));\n System.out.println(\"Resultant array: \");\n int pos = myArray.length-1;\n for(int i = myArray.length-1; i>=0; i--){\n if(myArray[i]!=0){\n myArray[pos]=myArray[i];\n pos--;\n }\n }\n while(pos>=0) {\n myArray[pos] = 0;\n pos--;\n }\n System.out.println(\"The array created is: \"+Arrays.toString(myArray));\n }\n}" }, { "code": null, "e": 4277, "s": 4052, "text": "Enter the size of the array that is to be created:\n8\nEnter the elements of the array:\n14\n0\n56\n0\n12\n47\n0\n0\nThe array created is: [14, 0, 56, 0, 12, 47, 0, 0]\nResultant array:\nThe array created is: [0, 0, 0, 0, 14, 56, 12, 47]" } ]
Equivalent for Row_Number() in SAP ABAP
When you want to modify the contents and store them into table and also to add a column for the value, use something like DATA: my_string TYPE String LOOP AT itab INTO wa_itab. my_string = sy-tabix. CONCATENATE some_text my_string more_text into wa_itab-my_field. MODIFY itab FROM wa_itab. CLEAR my_string. ENDLOOP.
[ { "code": null, "e": 1184, "s": 1062, "text": "When you want to modify the contents and store them into table and also to add a column for the value, use something like" }, { "code": null, "e": 1212, "s": 1184, "text": "DATA: my_string TYPE String" }, { "code": null, "e": 1378, "s": 1212, "text": "LOOP AT itab INTO wa_itab.\nmy_string = sy-tabix.\nCONCATENATE some_text my_string more_text into wa_itab-my_field.\nMODIFY itab FROM wa_itab.\nCLEAR my_string.\nENDLOOP." } ]
How to execute a background process in PHP ? - GeeksforGeeks
12 Jan, 2022 What is the background process and why do we need them? A process that runs behind the scenes (i.e. in the background) and without user intervention is called the background process. Debug/error logging, monitoring any system with grafana or kibana, user notification, scheduling jobs, and publishing some data are a typical example of background process. The background process is usually a child process created by a control process for processing a computing task. After creation, the child process will run on its own, performing the task independent of the parent process’s state. There are a lot of ways to run a job in the background. Crontab, multithreading in java, go routines in golang are examples of such cases. To run a process in ubuntu, we simply type a command on the terminal. For example, to run a PHP file, we use the following command : php filename.php In PHP, we can not directly run any process job in the background even if the parent job terminates. Before we get to know how to run the process in the background let’s know how to execute terminal commands from PHP script or program. To achieve this functionality we can use exec and shell_exec functions in PHP. A sample command to run any command with PHP is: PHP <?php shell_exec(sprintf('%s > /dev/null 2>&1 &', "echo 4"));?> There are the important points of the above code: The output (STDOUT) of the script must be directed to a file. /dev/null indicates that we are not logging the output. The errors (STDERR) also must be directed to a file. 2>&1 means that STDERR is redirected into STDOUT and therefore into the nirvana. The final & tells the command to execute in the background. We can check the status of any running process with command ps, for example: ps -ef So, to run any background process from PHP, we can simply use either exec or shell_exec function to execute any terminal command and in that command, we can simply add & at the last so that, the process can run in the background. Below is the implementation of the above approach: PHP <?php // Function to run process in backgroundfunction run($command, $outputFile = '/dev/null') { $processId = shell_exec(sprintf( '%s > %s 2>&1 & echo $!', $command, $outputFile )); print_r("processID of process in background is: " . $processId);} // "sleep 5" process will run in backgroundrun("sleep 5"); print_r("current processID is: ".getmypid()); ?> processID of process in background is: 19926 current processID is: 19924 PHP-Questions Picked PHP Web Technologies 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 How to generate PDF file using PHP ? How to create admin login page using PHP? Create a drop-down list that options fetched from a MySQL database in PHP Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 24972, "s": 24944, "text": "\n12 Jan, 2022" }, { "code": null, "e": 25028, "s": 24972, "text": "What is the background process and why do we need them?" }, { "code": null, "e": 25560, "s": 25028, "text": "A process that runs behind the scenes (i.e. in the background) and without user intervention is called the background process. Debug/error logging, monitoring any system with grafana or kibana, user notification, scheduling jobs, and publishing some data are a typical example of background process. The background process is usually a child process created by a control process for processing a computing task. After creation, the child process will run on its own, performing the task independent of the parent process’s state." }, { "code": null, "e": 25700, "s": 25560, "text": "There are a lot of ways to run a job in the background. Crontab, multithreading in java, go routines in golang are examples of such cases. " }, { "code": null, "e": 25833, "s": 25700, "text": "To run a process in ubuntu, we simply type a command on the terminal. For example, to run a PHP file, we use the following command :" }, { "code": null, "e": 25850, "s": 25833, "text": "php filename.php" }, { "code": null, "e": 26165, "s": 25850, "text": "In PHP, we can not directly run any process job in the background even if the parent job terminates. Before we get to know how to run the process in the background let’s know how to execute terminal commands from PHP script or program. To achieve this functionality we can use exec and shell_exec functions in PHP." }, { "code": null, "e": 26214, "s": 26165, "text": "A sample command to run any command with PHP is:" }, { "code": null, "e": 26218, "s": 26214, "text": "PHP" }, { "code": "<?php shell_exec(sprintf('%s > /dev/null 2>&1 &', \"echo 4\"));?>", "e": 26284, "s": 26218, "text": null }, { "code": null, "e": 26334, "s": 26284, "text": "There are the important points of the above code:" }, { "code": null, "e": 26452, "s": 26334, "text": "The output (STDOUT) of the script must be directed to a file. /dev/null indicates that we are not logging the output." }, { "code": null, "e": 26586, "s": 26452, "text": "The errors (STDERR) also must be directed to a file. 2>&1 means that STDERR is redirected into STDOUT and therefore into the nirvana." }, { "code": null, "e": 26646, "s": 26586, "text": "The final & tells the command to execute in the background." }, { "code": null, "e": 26724, "s": 26646, "text": " We can check the status of any running process with command ps, for example:" }, { "code": null, "e": 26731, "s": 26724, "text": "ps -ef" }, { "code": null, "e": 26961, "s": 26731, "text": "So, to run any background process from PHP, we can simply use either exec or shell_exec function to execute any terminal command and in that command, we can simply add & at the last so that, the process can run in the background." }, { "code": null, "e": 27012, "s": 26961, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27016, "s": 27012, "text": "PHP" }, { "code": "<?php // Function to run process in backgroundfunction run($command, $outputFile = '/dev/null') { $processId = shell_exec(sprintf( '%s > %s 2>&1 & echo $!', $command, $outputFile )); print_r(\"processID of process in background is: \" . $processId);} // \"sleep 5\" process will run in backgroundrun(\"sleep 5\"); print_r(\"current processID is: \".getmypid()); ?>", "e": 27425, "s": 27016, "text": null }, { "code": null, "e": 27498, "s": 27425, "text": "processID of process in background is: 19926\ncurrent processID is: 19924" }, { "code": null, "e": 27512, "s": 27498, "text": "PHP-Questions" }, { "code": null, "e": 27519, "s": 27512, "text": "Picked" }, { "code": null, "e": 27523, "s": 27519, "text": "PHP" }, { "code": null, "e": 27540, "s": 27523, "text": "Web Technologies" }, { "code": null, "e": 27544, "s": 27540, "text": "PHP" }, { "code": null, "e": 27642, "s": 27544, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27724, "s": 27642, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 27775, "s": 27724, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 27812, "s": 27775, "text": "How to generate PDF file using PHP ?" }, { "code": null, "e": 27854, "s": 27812, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 27928, "s": 27854, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 27970, "s": 27928, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28003, "s": 27970, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28046, "s": 28003, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28096, "s": 28046, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
JSP - Handling Date
In this chapter, we will discuss how to handle data in JSP. One of the most important advantages of using JSP is that you can use all the methods available in core Java. We will take you through the Date class which is available in the java.util package; this class encapsulates the current date and time. The Date class supports two constructors. The first constructor initializes the object with the current date and time. Date( ) The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970. Date(long millisec) Once you have a Date object available, you can call any of the following support methods to play with dates − boolean after(Date date) Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false. boolean before(Date date) Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false. Object clone( ) Duplicates the invoking Date object. int compareTo(Date date) Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date. int compareTo(Object obj) Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException. boolean equals(Object date) Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false. long getTime( ) Returns the number of milliseconds that have elapsed since January 1, 1970. int hashCode( ) Returns a hash code for the invoking object. void setTime(long time) Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970 String toString( ) Converts the invoking Date object into a string and returns the result. With JSP program, it is very easy to get the current date and the time. You can use a simple Date object with the toString() method to print the current date and the time as follows − <%@ page import = "java.io.*,java.util.*, javax.servlet.*" %> <html> <head> <title>Display Current Date & Time</title> </head> <body> <center> <h1>Display Current Date & Time</h1> </center> <% Date date = new Date(); out.print( "<h2 align = \"center\">" +date.toString()+"</h2>"); %> </body> </html> Let us now keep the code in CurrentDate.jsp and then call this JSP using the URL http://localhost:8080/CurrentDate.jsp. You will receive the following result − Display Current Date & Time Mon Jun 21 21:46:49 GMT+04:00 2010 Refresh the page with the URL http://localhost:8080/CurrentDate.jsp. You will find difference in seconds everytime you would refresh. As discussed in the previous sections, you can use all the available Java methods in your JSP scripts. In case you need to compare two dates, consider the following methods − You can use getTime( ) method to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values. You can use getTime( ) method to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values. You can use the methods before( ), after( ), and equals( ) because the 12th of the month comes before the 18th; for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true. You can use the methods before( ), after( ), and equals( ) because the 12th of the month comes before the 18th; for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true. You can use the compareTo( ) method; this method is defined by the Comparable interface and implemented by Date. You can use the compareTo( ) method; this method is defined by the Comparable interface and implemented by Date. SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. Let us modify the above example as follows − <%@ page import = "java.io.*,java.util.*" %> <%@ page import = "javax.servlet.*,java.text.*" %> <html> <head> <title>Display Current Date & Time</title> </head> <body> <center> <h1>Display Current Date & Time</h1> </center> <% Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); out.print( "<h2 align=\"center\">" + ft.format(dNow) + "</h2>"); %> </body> </html> Compile the above servlet once again and then call this servlet using the URL http://localhost:8080/CurrentDate. You will receive the following result − Display Current Date & Time Mon 2010.06.21 at 10:06:44 PM GMT+04:00 To specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following − For a complete list of constant available methods to manipulate date, you can refer to the standard Java documentation. 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2545, "s": 2239, "text": "In this chapter, we will discuss how to handle data in JSP. One of the most important advantages of using JSP is that you can use all the methods available in core Java. We will take you through the Date class which is available in the java.util package; this class encapsulates the current date and time." }, { "code": null, "e": 2664, "s": 2545, "text": "The Date class supports two constructors. The first constructor initializes the object with the current date and time." }, { "code": null, "e": 2673, "s": 2664, "text": "Date( )\n" }, { "code": null, "e": 2810, "s": 2673, "text": "The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970." }, { "code": null, "e": 2831, "s": 2810, "text": "Date(long millisec)\n" }, { "code": null, "e": 2941, "s": 2831, "text": "Once you have a Date object available, you can call any of the following support methods to play with dates −" }, { "code": null, "e": 2966, "s": 2941, "text": "boolean after(Date date)" }, { "code": null, "e": 3098, "s": 2966, "text": "Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false." }, { "code": null, "e": 3124, "s": 3098, "text": "boolean before(Date date)" }, { "code": null, "e": 3258, "s": 3124, "text": "Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false." }, { "code": null, "e": 3274, "s": 3258, "text": "Object clone( )" }, { "code": null, "e": 3311, "s": 3274, "text": "Duplicates the invoking Date object." }, { "code": null, "e": 3336, "s": 3311, "text": "int compareTo(Date date)" }, { "code": null, "e": 3570, "s": 3336, "text": "Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date." }, { "code": null, "e": 3596, "s": 3570, "text": "int compareTo(Object obj)" }, { "code": null, "e": 3704, "s": 3596, "text": "Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException." }, { "code": null, "e": 3732, "s": 3704, "text": "boolean equals(Object date)" }, { "code": null, "e": 3864, "s": 3732, "text": "Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false." }, { "code": null, "e": 3880, "s": 3864, "text": "long getTime( )" }, { "code": null, "e": 3956, "s": 3880, "text": "Returns the number of milliseconds that have elapsed since January 1, 1970." }, { "code": null, "e": 3972, "s": 3956, "text": "int hashCode( )" }, { "code": null, "e": 4017, "s": 3972, "text": "Returns a hash code for the invoking object." }, { "code": null, "e": 4041, "s": 4017, "text": "void setTime(long time)" }, { "code": null, "e": 4166, "s": 4041, "text": "Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970" }, { "code": null, "e": 4185, "s": 4166, "text": "String toString( )" }, { "code": null, "e": 4257, "s": 4185, "text": "Converts the invoking Date object into a string and returns the result." }, { "code": null, "e": 4441, "s": 4257, "text": "With JSP program, it is very easy to get the current date and the time. You can use a simple Date object with the toString() method to print the current date and the time as follows −" }, { "code": null, "e": 4815, "s": 4441, "text": "<%@ page import = \"java.io.*,java.util.*, javax.servlet.*\" %>\n\n<html>\n <head>\n <title>Display Current Date & Time</title>\n </head>\n \n <body>\n <center>\n <h1>Display Current Date & Time</h1>\n </center>\n <%\n Date date = new Date();\n out.print( \"<h2 align = \\\"center\\\">\" +date.toString()+\"</h2>\");\n %>\n </body>\n</html>" }, { "code": null, "e": 4975, "s": 4815, "text": "Let us now keep the code in CurrentDate.jsp and then call this JSP using the URL http://localhost:8080/CurrentDate.jsp. You will receive the following result −" }, { "code": null, "e": 5039, "s": 4975, "text": "Display Current Date & Time\nMon Jun 21 21:46:49 GMT+04:00 2010\n" }, { "code": null, "e": 5173, "s": 5039, "text": "Refresh the page with the URL http://localhost:8080/CurrentDate.jsp. You will find difference in seconds everytime you would refresh." }, { "code": null, "e": 5348, "s": 5173, "text": "As discussed in the previous sections, you can use all the available Java methods in your JSP scripts. In case you need to compare two dates, consider the following methods −" }, { "code": null, "e": 5518, "s": 5348, "text": "You can use getTime( ) method to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values." }, { "code": null, "e": 5688, "s": 5518, "text": "You can use getTime( ) method to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values." }, { "code": null, "e": 5876, "s": 5688, "text": "You can use the methods before( ), after( ), and equals( ) because the 12th of the month comes before the 18th; for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true." }, { "code": null, "e": 6064, "s": 5876, "text": "You can use the methods before( ), after( ), and equals( ) because the 12th of the month comes before the 18th; for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true." }, { "code": null, "e": 6177, "s": 6064, "text": "You can use the compareTo( ) method; this method is defined by the Comparable interface and implemented by Date." }, { "code": null, "e": 6290, "s": 6177, "text": "You can use the compareTo( ) method; this method is defined by the Comparable interface and implemented by Date." }, { "code": null, "e": 6491, "s": 6290, "text": "SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting." }, { "code": null, "e": 6536, "s": 6491, "text": "Let us modify the above example as follows −" }, { "code": null, "e": 7046, "s": 6536, "text": "<%@ page import = \"java.io.*,java.util.*\" %>\n<%@ page import = \"javax.servlet.*,java.text.*\" %>\n\n<html>\n <head>\n <title>Display Current Date & Time</title>\n </head>\n \n <body>\n <center>\n <h1>Display Current Date & Time</h1>\n </center>\n <%\n Date dNow = new Date( );\n SimpleDateFormat ft = \n new SimpleDateFormat (\"E yyyy.MM.dd 'at' hh:mm:ss a zzz\");\n out.print( \"<h2 align=\\\"center\\\">\" + ft.format(dNow) + \"</h2>\");\n %>\n </body>\n</html>" }, { "code": null, "e": 7199, "s": 7046, "text": "Compile the above servlet once again and then call this servlet using the URL http://localhost:8080/CurrentDate. You will receive the following result −" }, { "code": null, "e": 7268, "s": 7199, "text": "Display Current Date & Time\nMon 2010.06.21 at 10:06:44 PM GMT+04:00\n" }, { "code": null, "e": 7428, "s": 7268, "text": "To specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following −" }, { "code": null, "e": 7548, "s": 7428, "text": "For a complete list of constant available methods to manipulate date, you can refer to the standard Java documentation." }, { "code": null, "e": 7583, "s": 7548, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 7598, "s": 7583, "text": " Chaand Sheikh" }, { "code": null, "e": 7633, "s": 7598, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 7648, "s": 7633, "text": " Chaand Sheikh" }, { "code": null, "e": 7683, "s": 7648, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7697, "s": 7683, "text": " Karthikeya T" }, { "code": null, "e": 7732, "s": 7697, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7748, "s": 7732, "text": " TELCOMA Global" }, { "code": null, "e": 7781, "s": 7748, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 7797, "s": 7781, "text": " TELCOMA Global" }, { "code": null, "e": 7831, "s": 7797, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 7839, "s": 7831, "text": " Uplatz" }, { "code": null, "e": 7846, "s": 7839, "text": " Print" }, { "code": null, "e": 7857, "s": 7846, "text": " Add Notes" } ]
C++ STL Priority Queue | Practice | GeeksforGeeks
Implement different operations on Priority Queue .i.e. adding element, removing element, size of priority queue, print the queue and top element of queue. Input: The first line of input contains an integer T denoting the no of test cases. For each test case, the first line of input contains an integer Q denoting the no of queries followed by Q space separated queries. A query can be of the following types: 1 x (Adding x to the priority queue and print the queue) 2 (Removing the element from the top of the priority queue and printing that element ) 3 (Get the element at the top of the priority queue) 4 (Get the size of the priority queue) 5 (Print the priority queue) Note: In each case return or print -1 if priority queue is empty Output: For each test case, the output is according to the query Q performed and if the priority queue is empty the output is -1. Constraints: 1<=T<=100 1<=Q<=100 Example: Input: 1 8 1 6 1 1 1 7 4 3 2 5 2 Output: 6 6 1 7 6 1 3 7 7 6 1 6 Explanation: 1 6 means adding 6 in the queue and printing that, similarly adding 1 and 7 in the queue and printing the queue i.e. 7 6 1. By 4 it returns the size of the queue i.e 3. With 3 as input, it returns the element at the top i.e 7. With 2 it removes the top element i.e 7 from the queue and prints the element i.e. 7. Having 5 as input, it prints the queue i.e. 6 1 and again 2 remove the element and prints that i.e 6. +1 avinav26113 months ago C++ Solution 0 abdulmuqsitzargar015 months ago void addElement(priority_queue<int> & A, int x){ A.push(x); //your code here} /* remove top element from the priority queue*/void remove_Element(priority_queue<int> &A){ if(!A.empty()){ cout<<A.top()<<endl; A.pop();} else cout<<"-1"<<endl;//your code here} /* returns the top element of the priority queue*/int getElement_at_top(priority_queue<int> &A){ if(!A.empty()) return A.top(); else return -1;//your code here} /* returns the size ofthe priority queue*/int getSize(priority_queue<int> &A){ if(!A.empty()) return A.size(); else return -1;//your code here} /* prints the element in the priority queue*/void print(priority_queue<int> &A){ if (A.empty()) { cout << -1 <<endl; } else { vector<int> temp; while (!A.empty()) { temp.push_back(A.top()); cout << A.top() << " "; A.pop(); } cout <<endl; for (auto &itr:temp) { A.push(itr); } } //your code here} +3 badgujarsachin835 months ago void addElement(priority_queue<int> & A, int x) { //your code here A.push(x); } /* remove top element from the priority queue*/ void remove_Element(priority_queue<int> &A) { if (A.empty()) { cout << -1 << '\n'; } else { cout << A.top() << '\n'; A.pop(); } } /* returns the top element of the priority queue*/ int getElement_at_top(priority_queue<int> &A) { //your code here return A.empty() ? -1 : A.top(); } /* returns the size of the priority queue*/ int getSize(priority_queue<int> &A) { //your code herej return A.empty() ? -1 : A.size(); } /* prints the element in the priority queue*/ void print(priority_queue<int> &A) { //your code here if (A.empty()) { cout << -1 << '\n'; } else { vector<int> temp; while (!A.empty()) { temp.push_back(A.top()); cout << A.top() << " "; A.pop(); } cout << '\n'; for (auto &itr:temp) { A.push(itr); } } } 0 rohitpendse1386 months ago /*add the element in the priority queue*/void addElement(priority_queue<int> &A, int x) { //your code here A.push(x);}/* remove top element fromthe priority queue*/void remove_Element(priority_queue<int> &A) { //your code here if (A.empty()) { cout << -1 << '\n'; } else { cout << A.top() << '\n'; A.pop(); }}/* returns the top elementof the priority queue*/int getElement_at_top(priority_queue<int> &A) { //your code here return A.empty() ? -1 : A.top();}/* returns the size ofthe priority queue*/int getSize(priority_queue<int> &A) { //your code here return A.empty() ? -1 : A.size();}/* prints the element inthe priority queue*/void print(priority_queue<int> &A) { //your code here if (A.empty()) { cout << -1 << '\n'; } else { vector<int> temp; while (!A.empty()) { temp.push_back(A.top()); cout << A.top() << " "; A.pop(); } cout << '\n'; for (auto &itr:temp) { A.push(itr); } }} 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": 394, "s": 238, "text": "Implement different operations on Priority Queue .i.e. adding element, removing element, size of priority queue, print the queue and top element of queue. " }, { "code": null, "e": 916, "s": 394, "text": "Input:\nThe first line of input contains an integer T denoting the no of test cases. For each test case, the first line of input contains an integer Q denoting the no of queries followed by Q space separated queries. \nA query can be of the following types:\n1 x (Adding x to the priority queue and print the queue)\n2 (Removing the element from the top of the priority queue and printing that element )\n3 (Get the element at the top of the priority queue)\n4 (Get the size of the priority queue)\n5 (Print the priority queue) " }, { "code": null, "e": 981, "s": 916, "text": "Note: In each case return or print -1 if priority queue is empty" }, { "code": null, "e": 1111, "s": 981, "text": "Output:\nFor each test case, the output is according to the query Q performed and if the priority queue is empty the output is -1." }, { "code": null, "e": 1144, "s": 1111, "text": "Constraints:\n1<=T<=100\n1<=Q<=100" }, { "code": null, "e": 1220, "s": 1144, "text": "Example:\nInput:\n1\n8\n1 6\n1 1\n1 7\n4\n3\n2\n5\n2\nOutput:\n6\n6 1\n7 6 1\n3\n7\n7 \n6 1 \n6" }, { "code": null, "e": 1648, "s": 1220, "text": "Explanation:\n1 6 means adding 6 in the queue and printing that, similarly adding 1 and 7 in the queue and printing the queue i.e. 7 6 1. By 4 it returns the size of the queue i.e 3. With 3 as input, it returns the element at the top i.e 7. With 2 it removes the top element i.e 7 from the queue and prints the element i.e. 7. Having 5 as input, it prints the queue i.e. 6 1 and again 2 remove the element and prints that i.e 6." }, { "code": null, "e": 1651, "s": 1648, "text": "+1" }, { "code": null, "e": 1674, "s": 1651, "text": "avinav26113 months ago" }, { "code": null, "e": 1687, "s": 1674, "text": "C++ Solution" }, { "code": null, "e": 1691, "s": 1689, "text": "0" }, { "code": null, "e": 1723, "s": 1691, "text": "abdulmuqsitzargar015 months ago" }, { "code": null, "e": 1802, "s": 1723, "text": "void addElement(priority_queue<int> & A, int x){ A.push(x); //your code here}" }, { "code": null, "e": 1981, "s": 1802, "text": "/* remove top element from the priority queue*/void remove_Element(priority_queue<int> &A){ if(!A.empty()){ cout<<A.top()<<endl; A.pop();} else cout<<\"-1\"<<endl;//your code here}" }, { "code": null, "e": 2147, "s": 1981, "text": "/* returns the top element of the priority queue*/int getElement_at_top(priority_queue<int> &A){ if(!A.empty()) return A.top(); else return -1;//your code here}" }, { "code": null, "e": 2295, "s": 2147, "text": "/* returns the size ofthe priority queue*/int getSize(priority_queue<int> &A){ if(!A.empty()) return A.size(); else return -1;//your code here}" }, { "code": null, "e": 2679, "s": 2295, "text": "/* prints the element in the priority queue*/void print(priority_queue<int> &A){ if (A.empty()) { cout << -1 <<endl; } else { vector<int> temp; while (!A.empty()) { temp.push_back(A.top()); cout << A.top() << \" \"; A.pop(); } cout <<endl; for (auto &itr:temp) { A.push(itr); } } //your code here}" }, { "code": null, "e": 2682, "s": 2679, "text": "+3" }, { "code": null, "e": 2711, "s": 2682, "text": "badgujarsachin835 months ago" }, { "code": null, "e": 3747, "s": 2711, "text": "void addElement(priority_queue<int> & A, int x)\n{\n //your code here\n A.push(x);\n}\n\n/* remove top element from \nthe priority queue*/\nvoid remove_Element(priority_queue<int> &A)\n{\n if (A.empty()) {\n cout << -1 << '\\n';\n } else {\n cout << A.top() << '\\n';\n A.pop();\n }\n}\n\n/* returns the top element \nof the priority queue*/\nint getElement_at_top(priority_queue<int> &A)\n{\n //your code here\n return A.empty() ? -1 : A.top();\n}\n/* returns the size of\nthe priority queue*/\nint getSize(priority_queue<int> &A)\n{\n //your code herej\n return A.empty() ? -1 : A.size();\n}\n\n/* prints the element in \nthe priority queue*/\nvoid print(priority_queue<int> &A)\n{\n //your code here\n if (A.empty()) {\n cout << -1 << '\\n';\n } else {\n vector<int> temp;\n while (!A.empty()) {\n temp.push_back(A.top());\n cout << A.top() << \" \";\n A.pop();\n }\n cout << '\\n';\n for (auto &itr:temp) {\n A.push(itr);\n }\n }\n}" }, { "code": null, "e": 3749, "s": 3747, "text": "0" }, { "code": null, "e": 3776, "s": 3749, "text": "rohitpendse1386 months ago" }, { "code": null, "e": 4818, "s": 3776, "text": "/*add the element in the priority queue*/void addElement(priority_queue<int> &A, int x) { //your code here A.push(x);}/* remove top element fromthe priority queue*/void remove_Element(priority_queue<int> &A) { //your code here if (A.empty()) { cout << -1 << '\\n'; } else { cout << A.top() << '\\n'; A.pop(); }}/* returns the top elementof the priority queue*/int getElement_at_top(priority_queue<int> &A) { //your code here return A.empty() ? -1 : A.top();}/* returns the size ofthe priority queue*/int getSize(priority_queue<int> &A) { //your code here return A.empty() ? -1 : A.size();}/* prints the element inthe priority queue*/void print(priority_queue<int> &A) { //your code here if (A.empty()) { cout << -1 << '\\n'; } else { vector<int> temp; while (!A.empty()) { temp.push_back(A.top()); cout << A.top() << \" \"; A.pop(); } cout << '\\n'; for (auto &itr:temp) { A.push(itr); } }}" }, { "code": null, "e": 4964, "s": 4818, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5000, "s": 4964, "text": " Login to access your submissions. " }, { "code": null, "e": 5010, "s": 5000, "text": "\nProblem\n" }, { "code": null, "e": 5020, "s": 5010, "text": "\nContest\n" }, { "code": null, "e": 5083, "s": 5020, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5231, "s": 5083, "text": "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." }, { "code": null, "e": 5439, "s": 5231, "text": "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." }, { "code": null, "e": 5545, "s": 5439, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Cordova - Network Information
This plugin provides information about device's network. To install this plugin, we will open command prompt and run the following code − C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-network-information Let's create one button in index.html that will be used for getting info about network. <button id = "networkInfo">INFO</button> We will add three event listeners inside onDeviceReady function in index.js. One will listen for clicks on the button we created before and the other two will listen for changes in connection status. document.getElementById("networkInfo").addEventListener("click", networkInfo); document.addEventListener("offline", onOffline, false); document.addEventListener("online", onOnline, false); networkInfo function will return info about current network connection once button is clicked. We are calling type method. The other functions are onOffline and onOnline. These functions are listening to the connection changes and any change will trigger the corresponding alert message. function networkInfo() { var networkState = navigator.connection.type; var states = {}; states[Connection.UNKNOWN] = 'Unknown connection'; states[Connection.ETHERNET] = 'Ethernet connection'; states[Connection.WIFI] = 'WiFi connection'; states[Connection.CELL_2G] = 'Cell 2G connection'; states[Connection.CELL_3G] = 'Cell 3G connection'; states[Connection.CELL_4G] = 'Cell 4G connection'; states[Connection.CELL] = 'Cell generic connection'; states[Connection.NONE] = 'No network connection'; alert('Connection type: ' + states[networkState]); } function onOffline() { alert('You are now offline!'); } function onOnline() { alert('You are now online!'); } When we start the app connected to the network, onOnline function will trigger alert. If we press INFO button the alert will show our network state. If we disconnect from the network, onOffline function will be called. 45 Lectures 2 hours Skillbakerystudios 16 Lectures 1 hours Nilay Mehta Print Add Notes Bookmark this page
[ { "code": null, "e": 2237, "s": 2180, "text": "This plugin provides information about device's network." }, { "code": null, "e": 2318, "s": 2237, "text": "To install this plugin, we will open command prompt and run the following code −" }, { "code": null, "e": 2418, "s": 2318, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin \n add cordova-plugin-network-information\n" }, { "code": null, "e": 2506, "s": 2418, "text": "Let's create one button in index.html that will be used for getting info about network." }, { "code": null, "e": 2547, "s": 2506, "text": "<button id = \"networkInfo\">INFO</button>" }, { "code": null, "e": 2747, "s": 2547, "text": "We will add three event listeners inside onDeviceReady function in index.js. One will listen for clicks on the button we created before and the other two will listen for changes in connection status." }, { "code": null, "e": 2936, "s": 2747, "text": "document.getElementById(\"networkInfo\").addEventListener(\"click\", networkInfo);\ndocument.addEventListener(\"offline\", onOffline, false);\ndocument.addEventListener(\"online\", onOnline, false);" }, { "code": null, "e": 3224, "s": 2936, "text": "networkInfo function will return info about current network connection once button is clicked. We are calling type method. The other functions are onOffline and onOnline. These functions are listening to the connection changes and any change will trigger the corresponding alert message." }, { "code": null, "e": 3938, "s": 3224, "text": "function networkInfo() {\n var networkState = navigator.connection.type;\n var states = {};\n states[Connection.UNKNOWN] = 'Unknown connection';\n states[Connection.ETHERNET] = 'Ethernet connection';\n states[Connection.WIFI] = 'WiFi connection';\n states[Connection.CELL_2G] = 'Cell 2G connection';\n states[Connection.CELL_3G] = 'Cell 3G connection';\n states[Connection.CELL_4G] = 'Cell 4G connection';\n states[Connection.CELL] = 'Cell generic connection';\n states[Connection.NONE] = 'No network connection';\n alert('Connection type: ' + states[networkState]);\n}\n\nfunction onOffline() {\n alert('You are now offline!');\n}\n\nfunction onOnline() {\n alert('You are now online!');\n}" }, { "code": null, "e": 4024, "s": 3938, "text": "When we start the app connected to the network, onOnline function will trigger alert." }, { "code": null, "e": 4087, "s": 4024, "text": "If we press INFO button the alert will show our network state." }, { "code": null, "e": 4157, "s": 4087, "text": "If we disconnect from the network, onOffline function will be called." }, { "code": null, "e": 4190, "s": 4157, "text": "\n 45 Lectures \n 2 hours \n" }, { "code": null, "e": 4210, "s": 4190, "text": " Skillbakerystudios" }, { "code": null, "e": 4243, "s": 4210, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 4256, "s": 4243, "text": " Nilay Mehta" }, { "code": null, "e": 4263, "s": 4256, "text": " Print" }, { "code": null, "e": 4274, "s": 4263, "text": " Add Notes" } ]
DSum() and DAvg() Functions MS Access - GeeksforGeeks
18 Sep, 2020 1. DSum() Function :In MS Access, the DSum() function is used to calculate the sum of a set of values in a specified set of records (a domain). The DSum functions return the sum of a set of values from a field that satisfy the criteria. The difference between DSum and Sum is that in DSum function, values are calculated before data is grouped and in the case of Sum function, the data is grouped before values in the field expression are evaluated. Syntax : DSum (expr, domain [, criteria]) Parameter : This method accepts three-parameter as mentioned above and described below : expr : It identifies the numeric field whose values to be totaled. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. In expr, the name of a field in a table, a control on a form, a constant, or a function can be included. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function. domain : It is A string expression identifying the set of records that constitutes the domain. It can be a table name or a query name for a query that does not require a parameter. criteria : It identifies a string expression used to restrict the range of data on which the DSum function is performed. It is optional. It is the WHERE clause to apply to the domain. Returns : It returns sum of all values in a specified set of records which satisfies the criteria. If no record satisfies the criteria argument or if domain contains no records, the DSum function returns a Null. Table – Product Details : Example-1 : Finding the sum of all product price. Select DSum("Product_Price", "Product Details") as Total_Price; Output : Example-2 : Finding the sum of product price for a given condition where the product id is less than 103. Select DSum("Product_Price", "Product Details", "Product_Id < 103") as Total_Price; Output : 2. DAvg() Function :In MS Access, the DAvg() function is used to calculate the average of a set of values in a specified set of records (a domain). The DAvg functions return the average of a set of values from a field that satisfy the criteria. The difference between DAvg and Avg is that in DAvg function, values are averaged before data is grouped and in the case of Avg function, the data is grouped before values in the field expression are averaged. Syntax : DAvg (expr, domain [, criteria]) Parameter : This method accepts three-parameter as mentioned above and described below : expr : It identifies the numeric field whose values to be averaged. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. In expr, the name of a field in a table, a control on a form, a constant, or a function can be included. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function. domain : It is A string expression identifying the set of records that constitutes the domain. It can be a table name or a query name for a query that does not require a parameter. criteria : It identifies a string expression used to restrict the range of data on which the DAvg function is performed. It is optional. It is the WHERE clause to apply to the domain. Returns : It returns average of all values in a specified set of records which satisfies the criteria. If no record satisfies the criteria argument DAvg function returns a Null. Table – Product Details : Example-1 : Finding the average of product price. Select DAvg("Product_Price", "Product Details") as Avg_Price; Output : Example-2 : Finding the average of product price for a given condition where the product id is less than 103. Select DAvg("Product_Price", "Product Details", "Product_Id < 103") as Avg_Price; Output : DBMS-SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Trigger | Student Database CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL | Views SQL Interview Questions SQL | GROUP BY Difference between DDL and DML in DBMS Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function What is Temporary Table in SQL?
[ { "code": null, "e": 24038, "s": 24010, "text": "\n18 Sep, 2020" }, { "code": null, "e": 24488, "s": 24038, "text": "1. DSum() Function :In MS Access, the DSum() function is used to calculate the sum of a set of values in a specified set of records (a domain). The DSum functions return the sum of a set of values from a field that satisfy the criteria. The difference between DSum and Sum is that in DSum function, values are calculated before data is grouped and in the case of Sum function, the data is grouped before values in the field expression are evaluated." }, { "code": null, "e": 24497, "s": 24488, "text": "Syntax :" }, { "code": null, "e": 24531, "s": 24497, "text": "DSum (expr, domain [, criteria])\n" }, { "code": null, "e": 24620, "s": 24531, "text": "Parameter : This method accepts three-parameter as mentioned above and described below :" }, { "code": null, "e": 25073, "s": 24620, "text": "expr : It identifies the numeric field whose values to be totaled. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. In expr, the name of a field in a table, a control on a form, a constant, or a function can be included. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function." }, { "code": null, "e": 25254, "s": 25073, "text": "domain : It is A string expression identifying the set of records that constitutes the domain. It can be a table name or a query name for a query that does not require a parameter." }, { "code": null, "e": 25438, "s": 25254, "text": "criteria : It identifies a string expression used to restrict the range of data on which the DSum function is performed. It is optional. It is the WHERE clause to apply to the domain." }, { "code": null, "e": 25650, "s": 25438, "text": "Returns : It returns sum of all values in a specified set of records which satisfies the criteria. If no record satisfies the criteria argument or if domain contains no records, the DSum function returns a Null." }, { "code": null, "e": 25676, "s": 25650, "text": "Table – Product Details :" }, { "code": null, "e": 25726, "s": 25676, "text": "Example-1 : Finding the sum of all product price." }, { "code": null, "e": 25791, "s": 25726, "text": "Select DSum(\"Product_Price\", \"Product Details\") as Total_Price;\n" }, { "code": null, "e": 25800, "s": 25791, "text": "Output :" }, { "code": null, "e": 25906, "s": 25800, "text": "Example-2 : Finding the sum of product price for a given condition where the product id is less than 103." }, { "code": null, "e": 25992, "s": 25906, "text": "Select DSum(\"Product_Price\", \"Product Details\", \"Product_Id < 103\") as Total_Price;\n" }, { "code": null, "e": 26001, "s": 25992, "text": "Output :" }, { "code": null, "e": 26456, "s": 26001, "text": "2. DAvg() Function :In MS Access, the DAvg() function is used to calculate the average of a set of values in a specified set of records (a domain). The DAvg functions return the average of a set of values from a field that satisfy the criteria. The difference between DAvg and Avg is that in DAvg function, values are averaged before data is grouped and in the case of Avg function, the data is grouped before values in the field expression are averaged." }, { "code": null, "e": 26465, "s": 26456, "text": "Syntax :" }, { "code": null, "e": 26499, "s": 26465, "text": "DAvg (expr, domain [, criteria])\n" }, { "code": null, "e": 26588, "s": 26499, "text": "Parameter : This method accepts three-parameter as mentioned above and described below :" }, { "code": null, "e": 27042, "s": 26588, "text": "expr : It identifies the numeric field whose values to be averaged. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. In expr, the name of a field in a table, a control on a form, a constant, or a function can be included. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function." }, { "code": null, "e": 27223, "s": 27042, "text": "domain : It is A string expression identifying the set of records that constitutes the domain. It can be a table name or a query name for a query that does not require a parameter." }, { "code": null, "e": 27407, "s": 27223, "text": "criteria : It identifies a string expression used to restrict the range of data on which the DAvg function is performed. It is optional. It is the WHERE clause to apply to the domain." }, { "code": null, "e": 27585, "s": 27407, "text": "Returns : It returns average of all values in a specified set of records which satisfies the criteria. If no record satisfies the criteria argument DAvg function returns a Null." }, { "code": null, "e": 27611, "s": 27585, "text": "Table – Product Details :" }, { "code": null, "e": 27661, "s": 27611, "text": "Example-1 : Finding the average of product price." }, { "code": null, "e": 27724, "s": 27661, "text": "Select DAvg(\"Product_Price\", \"Product Details\") as Avg_Price;\n" }, { "code": null, "e": 27733, "s": 27724, "text": "Output :" }, { "code": null, "e": 27843, "s": 27733, "text": "Example-2 : Finding the average of product price for a given condition where the product id is less than 103." }, { "code": null, "e": 27927, "s": 27843, "text": "Select DAvg(\"Product_Price\", \"Product Details\", \"Product_Id < 103\") as Avg_Price;\n" }, { "code": null, "e": 27936, "s": 27927, "text": "Output :" }, { "code": null, "e": 27945, "s": 27936, "text": "DBMS-SQL" }, { "code": null, "e": 27949, "s": 27945, "text": "SQL" }, { "code": null, "e": 27953, "s": 27949, "text": "SQL" }, { "code": null, "e": 28051, "s": 27953, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28082, "s": 28051, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 28093, "s": 28082, "text": "CTE in SQL" }, { "code": null, "e": 28159, "s": 28093, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28171, "s": 28159, "text": "SQL | Views" }, { "code": null, "e": 28195, "s": 28171, "text": "SQL Interview Questions" }, { "code": null, "e": 28210, "s": 28195, "text": "SQL | GROUP BY" }, { "code": null, "e": 28249, "s": 28210, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 28294, "s": 28249, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 28326, "s": 28294, "text": "MySQL | Group_CONCAT() Function" } ]
HTTP headers | Content-Security-Policy
16 Jul, 2021 The Content Security Policy response header field is a tool to implement defense in depth mechanism for protection of data from content injection vulnerabilities such as cross-scripting attacks. It provides a policy mechanism that allows developers to detect the flaws present in their application and reduce application privileges. It provides developer control over the application at a granular level to prevent various attacks and maintain content integrity. Syntax: Content Security Policy : directive directive-value ; directive directive-value The above has the directive and directive-value. Multiple policy directives can be used in a line separated by semi-colon. Directives with Examples: 1. Fetch Directives: These are used to control the point from which a certain resource can be accessed or loaded into the system. child-src: It controls the creation of nested browsing context and requests which populate the frame of a worker.Content-Security-Policy: child-src https://example.com/ Content-Security-Policy: child-src https://example.com/ default-src: It is used to serve as default source list of policy considering the value entered and serve as fallback for other fetch directives.Content-Security-Policy: default-src 'self' Content-Security-Policy: default-src 'self' frame-src: It restricts URLs loaded for nested browsing context.Content-Security-Policy: frame-src https://example.com/ Content-Security-Policy: frame-src https://example.com/ manifest-src: It controls the URLs from which various elements of a resource might be loaded.Content-Security-Policy: manifest-src https://example.com/ Content-Security-Policy: manifest-src https://example.com/ object-src: It is used restrict URLs which can load plugin content into application.Content-Security-Policy: object-src https://example.com/ Content-Security-Policy: object-src https://example.com/ connect-src: It is used to control URLs that can be loaded using scripting interfaces into applications.Content-Security-Policy: connect-src https://example.com/ Content-Security-Policy: connect-src https://example.com/ font-src: It controls URLs that can load fonts into application.Content-Security-Policy: font-src https://example.com/ Content-Security-Policy: font-src https://example.com/ img-src: It controls URLs that can load images into application.Content-Security-Policy: img-src https://example.com/ Content-Security-Policy: img-src https://example.com/ media-src: It controls URLs that can load audio, video and associated text track resources into application.Content-Security-Policy: media-src https://example.com/ Content-Security-Policy: media-src https://example.com/ style-src: It controls sources that can apply load and apply Stylesheet to an application. script-src: It controls sources that can implement JavaScript into application. Few fetch directives are experimental application programming interfaces such as prefetch-src, script-src-elem, script-src-attr, style-src-elem, style-src-attr and worker-src. 2.Document Directives: These directives control implementation of properties on all documents and worker environments which come under the governance of CSP. plugin-types: It limits the resources loaded for restricting the possibility to plugins being embedded into a document.Content-Security-Policy: plugin-types application/pdf Content-Security-Policy: plugin-types application/pdf base-uri: It controls the URLs that can be loaded into base element present in document. sandbox: The HTML sandbox policy can be applied by user agent through the specifications of this directive. 3.Navigation Directives contains form-action, frame-ancestors and navigate-to directives. The form-action directive controls URLs that can be used for form submission. The frame-ancestors directive restricts URLs which can embed the resource using frame, iframe, object, embed, or applet element. The navigate-to directive specifies the URLs to which document can traverse through any method. 4.Reporting Directives contains report-to which specifies the end point to send violation reports. The earlier used report-uri is now deprecated. Few more Examples: All the examples in the article have been taken from World Wide Web Consortium’s CSP Level 3 Draft. Content-Security-Policy: script-src https://cdn.example.com/scripts/; object-src 'none' Content-Security-Policy: script-src 'self'; report-to csp-reporting-endpoint Content-Security-Policy: prefetch-src https://example.com/ Content-Security-Policy: worker-src https://example.com/ Content-Security-Policy: navigate-to example.com Browser Compatibility: CSP Level 3 is provided partial support from versions Chrome 59+, Firefox 58+, and Edge 79+.CSP Level 2 is provided full support from versions Chrome 40+, Safari 10+, Edge 76+, and partial support from Firefox 31+ and Edge 15+.CSP Level 1 is provided full supports from versions Chrome 25+, Firefox 23+, Edge 12+, and Safari 7+. kalrap615 HTTP-headers Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jul, 2021" }, { "code": null, "e": 491, "s": 28, "text": "The Content Security Policy response header field is a tool to implement defense in depth mechanism for protection of data from content injection vulnerabilities such as cross-scripting attacks. It provides a policy mechanism that allows developers to detect the flaws present in their application and reduce application privileges. It provides developer control over the application at a granular level to prevent various attacks and maintain content integrity." }, { "code": null, "e": 499, "s": 491, "text": "Syntax:" }, { "code": null, "e": 579, "s": 499, "text": "Content Security Policy : directive directive-value ; directive directive-value" }, { "code": null, "e": 702, "s": 579, "text": "The above has the directive and directive-value. Multiple policy directives can be used in a line separated by semi-colon." }, { "code": null, "e": 728, "s": 702, "text": "Directives with Examples:" }, { "code": null, "e": 858, "s": 728, "text": "1. Fetch Directives: These are used to control the point from which a certain resource can be accessed or loaded into the system." }, { "code": null, "e": 1027, "s": 858, "text": "child-src: It controls the creation of nested browsing context and requests which populate the frame of a worker.Content-Security-Policy: child-src https://example.com/" }, { "code": null, "e": 1083, "s": 1027, "text": "Content-Security-Policy: child-src https://example.com/" }, { "code": null, "e": 1272, "s": 1083, "text": "default-src: It is used to serve as default source list of policy considering the value entered and serve as fallback for other fetch directives.Content-Security-Policy: default-src 'self'" }, { "code": null, "e": 1316, "s": 1272, "text": "Content-Security-Policy: default-src 'self'" }, { "code": null, "e": 1436, "s": 1316, "text": "frame-src: It restricts URLs loaded for nested browsing context.Content-Security-Policy: frame-src https://example.com/" }, { "code": null, "e": 1492, "s": 1436, "text": "Content-Security-Policy: frame-src https://example.com/" }, { "code": null, "e": 1644, "s": 1492, "text": "manifest-src: It controls the URLs from which various elements of a resource might be loaded.Content-Security-Policy: manifest-src https://example.com/" }, { "code": null, "e": 1703, "s": 1644, "text": "Content-Security-Policy: manifest-src https://example.com/" }, { "code": null, "e": 1844, "s": 1703, "text": "object-src: It is used restrict URLs which can load plugin content into application.Content-Security-Policy: object-src https://example.com/" }, { "code": null, "e": 1901, "s": 1844, "text": "Content-Security-Policy: object-src https://example.com/" }, { "code": null, "e": 2063, "s": 1901, "text": "connect-src: It is used to control URLs that can be loaded using scripting interfaces into applications.Content-Security-Policy: connect-src https://example.com/" }, { "code": null, "e": 2121, "s": 2063, "text": "Content-Security-Policy: connect-src https://example.com/" }, { "code": null, "e": 2240, "s": 2121, "text": "font-src: It controls URLs that can load fonts into application.Content-Security-Policy: font-src https://example.com/" }, { "code": null, "e": 2295, "s": 2240, "text": "Content-Security-Policy: font-src https://example.com/" }, { "code": null, "e": 2413, "s": 2295, "text": "img-src: It controls URLs that can load images into application.Content-Security-Policy: img-src https://example.com/" }, { "code": null, "e": 2467, "s": 2413, "text": "Content-Security-Policy: img-src https://example.com/" }, { "code": null, "e": 2631, "s": 2467, "text": "media-src: It controls URLs that can load audio, video and associated text track resources into application.Content-Security-Policy: media-src https://example.com/" }, { "code": null, "e": 2687, "s": 2631, "text": "Content-Security-Policy: media-src https://example.com/" }, { "code": null, "e": 2778, "s": 2687, "text": "style-src: It controls sources that can apply load and apply Stylesheet to an application." }, { "code": null, "e": 2858, "s": 2778, "text": "script-src: It controls sources that can implement JavaScript into application." }, { "code": null, "e": 3034, "s": 2858, "text": "Few fetch directives are experimental application programming interfaces such as prefetch-src, script-src-elem, script-src-attr, style-src-elem, style-src-attr and worker-src." }, { "code": null, "e": 3192, "s": 3034, "text": "2.Document Directives: These directives control implementation of properties on all documents and worker environments which come under the governance of CSP." }, { "code": null, "e": 3365, "s": 3192, "text": "plugin-types: It limits the resources loaded for restricting the possibility to plugins being embedded into a document.Content-Security-Policy: plugin-types application/pdf" }, { "code": null, "e": 3419, "s": 3365, "text": "Content-Security-Policy: plugin-types application/pdf" }, { "code": null, "e": 3508, "s": 3419, "text": "base-uri: It controls the URLs that can be loaded into base element present in document." }, { "code": null, "e": 3616, "s": 3508, "text": "sandbox: The HTML sandbox policy can be applied by user agent through the specifications of this directive." }, { "code": null, "e": 4009, "s": 3616, "text": "3.Navigation Directives contains form-action, frame-ancestors and navigate-to directives. The form-action directive controls URLs that can be used for form submission. The frame-ancestors directive restricts URLs which can embed the resource using frame, iframe, object, embed, or applet element. The navigate-to directive specifies the URLs to which document can traverse through any method." }, { "code": null, "e": 4155, "s": 4009, "text": "4.Reporting Directives contains report-to which specifies the end point to send violation reports. The earlier used report-uri is now deprecated." }, { "code": null, "e": 4174, "s": 4155, "text": "Few more Examples:" }, { "code": null, "e": 4274, "s": 4174, "text": "All the examples in the article have been taken from World Wide Web Consortium’s CSP Level 3 Draft." }, { "code": null, "e": 4605, "s": 4274, "text": "Content-Security-Policy: script-src https://cdn.example.com/scripts/; object-src 'none'\nContent-Security-Policy: script-src 'self'; report-to csp-reporting-endpoint\nContent-Security-Policy: prefetch-src https://example.com/\nContent-Security-Policy: worker-src https://example.com/\nContent-Security-Policy: navigate-to example.com\n" }, { "code": null, "e": 4628, "s": 4605, "text": "Browser Compatibility:" }, { "code": null, "e": 4957, "s": 4628, "text": "CSP Level 3 is provided partial support from versions Chrome 59+, Firefox 58+, and Edge 79+.CSP Level 2 is provided full support from versions Chrome 40+, Safari 10+, Edge 76+, and partial support from Firefox 31+ and Edge 15+.CSP Level 1 is provided full supports from versions Chrome 25+, Firefox 23+, Edge 12+, and Safari 7+." }, { "code": null, "e": 4967, "s": 4957, "text": "kalrap615" }, { "code": null, "e": 4980, "s": 4967, "text": "HTTP-headers" }, { "code": null, "e": 4987, "s": 4980, "text": "Picked" }, { "code": null, "e": 5004, "s": 4987, "text": "Web Technologies" } ]
C# | Count the total number of elements in the List
01 Feb, 2019 List class represents the list of objects which can be accessed by index. It comes under the System.Collection.Generic namespace. List class can be used to create a collection of different types like integers, strings etc. List class also provides the methods to search, sort, and manipulate lists. List.Count Property is used to get the total number of elements contained in the List. Properties: It is different from the arrays. A list can be resized dynamically but arrays cannot be. List class can accept null as a valid value for reference types and it also allows duplicate elements. If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element. Syntax: list_name.Count Below programs illustrate the use of Count property: Example 1: // C# code to get the number of// elements contained in Listusing System;using System.Collections.Generic; class Geeks { // Main Method public static void Main() { // Creating a List of integers List<int> firstlist = new List<int>(); // adding elements in firstlist for (int i = 4; i < 10; i++) { firstlist.Add(i * 2); } // To get the number of // elements in the List Console.WriteLine(firstlist.Count); }} Output: 6 Example 2: // C# code to get the number of// elements contained in Listusing System;using System.Collections.Generic; class Geeks { // Main Method public static void Main() { // Creating a List of integers List<int> firstlist = new List<int>(); // To get the number of // elements in the List Console.WriteLine(firstlist.Count); }} Output: 0 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.count?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Generic-List CSharp-Generic-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Feb, 2019" }, { "code": null, "e": 438, "s": 52, "text": "List class represents the list of objects which can be accessed by index. It comes under the System.Collection.Generic namespace. List class can be used to create a collection of different types like integers, strings etc. List class also provides the methods to search, sort, and manipulate lists. List.Count Property is used to get the total number of elements contained in the List." }, { "code": null, "e": 450, "s": 438, "text": "Properties:" }, { "code": null, "e": 539, "s": 450, "text": "It is different from the arrays. A list can be resized dynamically but arrays cannot be." }, { "code": null, "e": 642, "s": 539, "text": "List class can accept null as a valid value for reference types and it also allows duplicate elements." }, { "code": null, "e": 866, "s": 642, "text": "If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element." }, { "code": null, "e": 874, "s": 866, "text": "Syntax:" }, { "code": null, "e": 890, "s": 874, "text": "list_name.Count" }, { "code": null, "e": 943, "s": 890, "text": "Below programs illustrate the use of Count property:" }, { "code": null, "e": 954, "s": 943, "text": "Example 1:" }, { "code": "// C# code to get the number of// elements contained in Listusing System;using System.Collections.Generic; class Geeks { // Main Method public static void Main() { // Creating a List of integers List<int> firstlist = new List<int>(); // adding elements in firstlist for (int i = 4; i < 10; i++) { firstlist.Add(i * 2); } // To get the number of // elements in the List Console.WriteLine(firstlist.Count); }}", "e": 1450, "s": 954, "text": null }, { "code": null, "e": 1458, "s": 1450, "text": "Output:" }, { "code": null, "e": 1461, "s": 1458, "text": "6\n" }, { "code": null, "e": 1472, "s": 1461, "text": "Example 2:" }, { "code": "// C# code to get the number of// elements contained in Listusing System;using System.Collections.Generic; class Geeks { // Main Method public static void Main() { // Creating a List of integers List<int> firstlist = new List<int>(); // To get the number of // elements in the List Console.WriteLine(firstlist.Count); }}", "e": 1847, "s": 1472, "text": null }, { "code": null, "e": 1855, "s": 1847, "text": "Output:" }, { "code": null, "e": 1858, "s": 1855, "text": "0\n" }, { "code": null, "e": 1869, "s": 1858, "text": "Reference:" }, { "code": null, "e": 1977, "s": 1869, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.count?view=netframework-4.7.2" }, { "code": null, "e": 2006, "s": 1977, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 2026, "s": 2006, "text": "CSharp-Generic-List" }, { "code": null, "e": 2051, "s": 2026, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 2054, "s": 2051, "text": "C#" } ]
Django Basics
22 Apr, 2022 Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks.When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives you ready-made components to use. Django is a rapid web development framework that can be used to develop fully fleshed web applications in a short period of time. It’s very easy to switch database in Django framework. It has built-in admin interface which makes easy to work with it. Django is fully functional framework that requires nothing else. It has thousands of additional packages available. It is very scalable. For more visit When to Use Django? Comparison with other Development Stacks ? Django is based on MVT (Model-View-Template) architecture. MVT is a software design pattern for developing a web application. MVT Structure has the following three parts – Model: Model is going to act as the interface of your data. It is responsible for maintaining data. It is the logical data structure behind the entire application and is represented by a database (generally relational databases such as MySql, Postgres). View: The View is the user interface — what you see in your browser when you render a website. It is represented by HTML/CSS/Javascript and Jinja files. Template: A template consists of static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. To check more about Django’s architecture, visit Django Project MVT Structure Install python3 if not installed in your system ( according to configuration of your system and OS) from here . Try to download the latest version of python it’s python3.6.4 this time. Note- Installation of Django in Linux and Mac is similar, here I am showing it in windows for Linux and mac just open terminal in place of command prompt and go through the following commands. Install pip- Open command prompt and enter following command- python -m pip install -U pip Install virtual environment- Enter following command in cmd- pip install virtualenv Set Virtual environment- Setting up the virtual environment will allow you to edit the dependency which generally your system wouldn’t allow.Follow these steps to set up a virtual environment-Create a virtual environment by giving this command in cmd-virtualenv env_siteChange directory to env_site by this command-cd env_siteGo to Script directory inside env_site and activate virtual environment-cd Scriptsactivate Create a virtual environment by giving this command in cmd-virtualenv env_siteChange directory to env_site by this command-cd env_siteGo to Script directory inside env_site and activate virtual environment-cd Scriptsactivate Create a virtual environment by giving this command in cmd-virtualenv env_site virtualenv env_site Change directory to env_site by this command-cd env_site cd env_site Go to Script directory inside env_site and activate virtual environment-cd Scriptsactivate cd Scripts activate Install Django- Install django by giving following command-pip install django pip install django Lets’ check how to create a basic project using Django after you have installed it in your pc. To initiate a project of Django on Your PC, open Terminal and Enter the following commanddjango-admin startproject projectName django-admin startproject projectName A New Folder with name projectName will be created. To enter in the project using terminal enter commandcd projectName cd projectName Now run, Python manage.py runserver Now visit http://localhost:8000/, Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. This article will take you through how to create a basic app and add functionalities using that app. To create a basic app in your Django project you need to go to directory containing manage.py and from there enter the command :python manage.py startapp projectAppNow you can see your directory structure as under : python manage.py startapp projectApp Now you can see your directory structure as under : To consider the app in your project you need to specify your project name in INSTALLED_APPS list as follows in settings.py:# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projectApp'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projectApp'] So, we have finally created an app but to render the app using urls we need to include the app in our main project so that urls redirected to that app can be rendered. Let us explore it.Move to projectName-> projectName -> urls.py and add below code in the headerfrom django.urls import include Now in the list of URL patterns, you need to specify app name for including your app urls. Here is the code for it –from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # Enter the app name in following syntax for this to work path('', include("projectApp.urls")),] from django.urls import include Now in the list of URL patterns, you need to specify app name for including your app urls. Here is the code for it – from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # Enter the app name in following syntax for this to work path('', include("projectApp.urls")),] Now You can use the default MVT model to create URLs, models, views, etc. in your app and they will be automatically included in your main project. The main feature of Django Apps is independence, every app functions as an independent unit in supporting the main project. To know more about apps in Django, visit How to Create an App in Django ? rajeshsahu7683995090 Django-basics Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Apr, 2022" }, { "code": null, "e": 518, "s": 52, "text": "Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks.When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives you ready-made components to use." }, { "code": null, "e": 648, "s": 518, "text": "Django is a rapid web development framework that can be used to develop fully fleshed web applications in a short period of time." }, { "code": null, "e": 703, "s": 648, "text": "It’s very easy to switch database in Django framework." }, { "code": null, "e": 769, "s": 703, "text": "It has built-in admin interface which makes easy to work with it." }, { "code": null, "e": 834, "s": 769, "text": "Django is fully functional framework that requires nothing else." }, { "code": null, "e": 885, "s": 834, "text": "It has thousands of additional packages available." }, { "code": null, "e": 984, "s": 885, "text": "It is very scalable. For more visit When to Use Django? Comparison with other Development Stacks ?" }, { "code": null, "e": 1110, "s": 984, "text": "Django is based on MVT (Model-View-Template) architecture. MVT is a software design pattern for developing a web application." }, { "code": null, "e": 1156, "s": 1110, "text": "MVT Structure has the following three parts –" }, { "code": null, "e": 1410, "s": 1156, "text": "Model: Model is going to act as the interface of your data. It is responsible for maintaining data. It is the logical data structure behind the entire application and is represented by a database (generally relational databases such as MySql, Postgres)." }, { "code": null, "e": 1563, "s": 1410, "text": "View: The View is the user interface — what you see in your browser when you render a website. It is represented by HTML/CSS/Javascript and Jinja files." }, { "code": null, "e": 1716, "s": 1563, "text": "Template: A template consists of static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted." }, { "code": null, "e": 1794, "s": 1716, "text": "To check more about Django’s architecture, visit Django Project MVT Structure" }, { "code": null, "e": 1979, "s": 1794, "text": "Install python3 if not installed in your system ( according to configuration of your system and OS) from here . Try to download the latest version of python it’s python3.6.4 this time." }, { "code": null, "e": 2172, "s": 1979, "text": "Note- Installation of Django in Linux and Mac is similar, here I am showing it in windows for Linux and mac just open terminal in place of command prompt and go through the following commands." }, { "code": null, "e": 2234, "s": 2172, "text": "Install pip- Open command prompt and enter following command-" }, { "code": null, "e": 2263, "s": 2234, "text": "python -m pip install -U pip" }, { "code": null, "e": 2324, "s": 2263, "text": "Install virtual environment- Enter following command in cmd-" }, { "code": null, "e": 2347, "s": 2324, "text": "pip install virtualenv" }, { "code": null, "e": 2764, "s": 2347, "text": "Set Virtual environment- Setting up the virtual environment will allow you to edit the dependency which generally your system wouldn’t allow.Follow these steps to set up a virtual environment-Create a virtual environment by giving this command in cmd-virtualenv env_siteChange directory to env_site by this command-cd env_siteGo to Script directory inside env_site and activate virtual environment-cd Scriptsactivate" }, { "code": null, "e": 2989, "s": 2764, "text": "Create a virtual environment by giving this command in cmd-virtualenv env_siteChange directory to env_site by this command-cd env_siteGo to Script directory inside env_site and activate virtual environment-cd Scriptsactivate" }, { "code": null, "e": 3068, "s": 2989, "text": "Create a virtual environment by giving this command in cmd-virtualenv env_site" }, { "code": null, "e": 3088, "s": 3068, "text": "virtualenv env_site" }, { "code": null, "e": 3145, "s": 3088, "text": "Change directory to env_site by this command-cd env_site" }, { "code": null, "e": 3157, "s": 3145, "text": "cd env_site" }, { "code": null, "e": 3248, "s": 3157, "text": "Go to Script directory inside env_site and activate virtual environment-cd Scriptsactivate" }, { "code": null, "e": 3259, "s": 3248, "text": "cd Scripts" }, { "code": null, "e": 3268, "s": 3259, "text": "activate" }, { "code": null, "e": 3346, "s": 3268, "text": "Install Django- Install django by giving following command-pip install django" }, { "code": null, "e": 3365, "s": 3346, "text": "pip install django" }, { "code": null, "e": 3460, "s": 3365, "text": "Lets’ check how to create a basic project using Django after you have installed it in your pc." }, { "code": null, "e": 3587, "s": 3460, "text": "To initiate a project of Django on Your PC, open Terminal and Enter the following commanddjango-admin startproject projectName" }, { "code": null, "e": 3625, "s": 3587, "text": "django-admin startproject projectName" }, { "code": null, "e": 3744, "s": 3625, "text": "A New Folder with name projectName will be created. To enter in the project using terminal enter commandcd projectName" }, { "code": null, "e": 3759, "s": 3744, "text": "cd projectName" }, { "code": null, "e": 3768, "s": 3759, "text": "Now run," }, { "code": null, "e": 3795, "s": 3768, "text": "Python manage.py runserver" }, { "code": null, "e": 3829, "s": 3795, "text": "Now visit http://localhost:8000/," }, { "code": null, "e": 4080, "s": 3829, "text": "Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. This article will take you through how to create a basic app and add functionalities using that app." }, { "code": null, "e": 4296, "s": 4080, "text": "To create a basic app in your Django project you need to go to directory containing manage.py and from there enter the command :python manage.py startapp projectAppNow you can see your directory structure as under :" }, { "code": null, "e": 4333, "s": 4296, "text": "python manage.py startapp projectApp" }, { "code": null, "e": 4385, "s": 4333, "text": "Now you can see your directory structure as under :" }, { "code": null, "e": 4750, "s": 4385, "text": "To consider the app in your project you need to specify your project name in INSTALLED_APPS list as follows in settings.py:# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projectApp']" }, { "code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projectApp']", "e": 4992, "s": 4750, "text": null }, { "code": null, "e": 5629, "s": 4992, "text": "So, we have finally created an app but to render the app using urls we need to include the app in our main project so that urls redirected to that app can be rendered. Let us explore it.Move to projectName-> projectName -> urls.py and add below code in the headerfrom django.urls import include Now in the list of URL patterns, you need to specify app name for including your app urls. Here is the code for it –from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # Enter the app name in following syntax for this to work path('', include(\"projectApp.urls\")),]" }, { "code": null, "e": 5662, "s": 5629, "text": "from django.urls import include " }, { "code": null, "e": 5779, "s": 5662, "text": "Now in the list of URL patterns, you need to specify app name for including your app urls. Here is the code for it –" }, { "code": "from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # Enter the app name in following syntax for this to work path('', include(\"projectApp.urls\")),]", "e": 6005, "s": 5779, "text": null }, { "code": null, "e": 6153, "s": 6005, "text": "Now You can use the default MVT model to create URLs, models, views, etc. in your app and they will be automatically included in your main project." }, { "code": null, "e": 6351, "s": 6153, "text": "The main feature of Django Apps is independence, every app functions as an independent unit in supporting the main project. To know more about apps in Django, visit How to Create an App in Django ?" }, { "code": null, "e": 6374, "s": 6353, "text": "rajeshsahu7683995090" }, { "code": null, "e": 6388, "s": 6374, "text": "Django-basics" }, { "code": null, "e": 6402, "s": 6388, "text": "Python Django" }, { "code": null, "e": 6409, "s": 6402, "text": "Python" } ]
How to take HTML form data as text and send them to html2pdf ?
08 Jan, 2021 In order to convert the HTML form data into pdf, the main approach is to use the html2pdf() function from the html2pdf library. Approach: First, create a form with encryption type as text and add some input fields. After that we need to use html2pdf(element) function from html2pdf library. Provide an onclick() functionality on the Submit button in the form. The html2pdf(element) function takes an input which is the id of the tag or form that needs to be converted to pdf format. Example: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width,initial-scale=1.0"> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous" rel="stylesheet"> <!-- Html2Pdf --> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.8.1/html2pdf.bundle.min.js" integrity="sha512vDKWohFHe2vkVWXHp3tKvIxxXg0pJxeid5eo+UjdjME3DBFBn2F8yWOE0XmiFcFbXxrEOR1JriWEno5Ckpn15A==" crossorigin="anonymous"> </script> <style> .heading{ text-align: center; color: #2F8D46; } </style></head> <body> <h2 class="heading"> GeeksForGeeks </h2> <!-- Form encrypted as text --> <form id ="form-print" enctype="text/plain" class="form-control"> <label for="name"> <strong>Name: </strong> </label> <input class="form-control" type="text" id="name" name="Name" placeholder="Enter Name"> <br> <label for="age"> <strong>Enter Age: </strong> </label> <input class="form-control" type="text" id="age" name="Age" placeholder="Enter Age"> <br> <label for="subject"> <strong>Select Subject: </strong> </label> <select class="form-control" id="subject" name="subject"> <option value="Web"> Web development </option> <option value="App"> App development </option> <option value="Others"> Others </option> </select> <br> <label for="message"> <strong>Enter Message </strong> </label> <textarea class= "form-control" id="message" name="message" placeholder="Enter you message" style="height:100px"> </textarea> <br> <input type="button" class="btn btn-primary" onclick="GeneratePdf();" value="GeneratePdf"> </form> <script> // Function to GeneratePdf function GeneratePdf() { var element = document.getElementById('form-print'); html2pdf(element); } </script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"> </script></body> </html> Output: HomePage(index Page) The Pdf of the Html form There is much functionality of html2pdf library that you can explore in order to change the filename(of Pdf), its ratio and much more. To explore more refer to the documentation of html2pdf library. CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jan, 2021" }, { "code": null, "e": 156, "s": 28, "text": "In order to convert the HTML form data into pdf, the main approach is to use the html2pdf() function from the html2pdf library." }, { "code": null, "e": 511, "s": 156, "text": "Approach: First, create a form with encryption type as text and add some input fields. After that we need to use html2pdf(element) function from html2pdf library. Provide an onclick() functionality on the Submit button in the form. The html2pdf(element) function takes an input which is the id of the tag or form that needs to be converted to pdf format." }, { "code": null, "e": 520, "s": 511, "text": "Example:" }, { "code": null, "e": 525, "s": 520, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width,initial-scale=1.0\"> <!-- CSS only --> <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1\" crossorigin=\"anonymous\" rel=\"stylesheet\"> <!-- Html2Pdf --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.8.1/html2pdf.bundle.min.js\" integrity=\"sha512vDKWohFHe2vkVWXHp3tKvIxxXg0pJxeid5eo+UjdjME3DBFBn2F8yWOE0XmiFcFbXxrEOR1JriWEno5Ckpn15A==\" crossorigin=\"anonymous\"> </script> <style> .heading{ text-align: center; color: #2F8D46; } </style></head> <body> <h2 class=\"heading\"> GeeksForGeeks </h2> <!-- Form encrypted as text --> <form id =\"form-print\" enctype=\"text/plain\" class=\"form-control\"> <label for=\"name\"> <strong>Name: </strong> </label> <input class=\"form-control\" type=\"text\" id=\"name\" name=\"Name\" placeholder=\"Enter Name\"> <br> <label for=\"age\"> <strong>Enter Age: </strong> </label> <input class=\"form-control\" type=\"text\" id=\"age\" name=\"Age\" placeholder=\"Enter Age\"> <br> <label for=\"subject\"> <strong>Select Subject: </strong> </label> <select class=\"form-control\" id=\"subject\" name=\"subject\"> <option value=\"Web\"> Web development </option> <option value=\"App\"> App development </option> <option value=\"Others\"> Others </option> </select> <br> <label for=\"message\"> <strong>Enter Message </strong> </label> <textarea class= \"form-control\" id=\"message\" name=\"message\" placeholder=\"Enter you message\" style=\"height:100px\"> </textarea> <br> <input type=\"button\" class=\"btn btn-primary\" onclick=\"GeneratePdf();\" value=\"GeneratePdf\"> </form> <script> // Function to GeneratePdf function GeneratePdf() { var element = document.getElementById('form-print'); html2pdf(element); } </script> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW\" crossorigin=\"anonymous\"> </script></body> </html>", "e": 3202, "s": 525, "text": null }, { "code": null, "e": 3210, "s": 3202, "text": "Output:" }, { "code": null, "e": 3231, "s": 3210, "text": "HomePage(index Page)" }, { "code": null, "e": 3256, "s": 3231, "text": "The Pdf of the Html form" }, { "code": null, "e": 3455, "s": 3256, "text": "There is much functionality of html2pdf library that you can explore in order to change the filename(of Pdf), its ratio and much more. To explore more refer to the documentation of html2pdf library." }, { "code": null, "e": 3464, "s": 3455, "text": "CSS-Misc" }, { "code": null, "e": 3474, "s": 3464, "text": "HTML-Misc" }, { "code": null, "e": 3490, "s": 3474, "text": "JavaScript-Misc" }, { "code": null, "e": 3497, "s": 3490, "text": "Picked" }, { "code": null, "e": 3501, "s": 3497, "text": "CSS" }, { "code": null, "e": 3506, "s": 3501, "text": "HTML" }, { "code": null, "e": 3517, "s": 3506, "text": "JavaScript" }, { "code": null, "e": 3534, "s": 3517, "text": "Web Technologies" }, { "code": null, "e": 3539, "s": 3534, "text": "HTML" } ]
GWT - Custom Widgets
GWT provides three ways to create custom user interface elements. There are three general strategies to follow − Create a widget by extending Composite Class − This is the most common and easiest way to create custom widgets. Here you can use existing widgets to create composite view with custom properties. Create a widget by extending Composite Class − This is the most common and easiest way to create custom widgets. Here you can use existing widgets to create composite view with custom properties. Create a widget using GWT DOM API in JAVA − GWT basic widgets are created in this way. Still its a very complicated way to create custom widget and should be used cautiously. Create a widget using GWT DOM API in JAVA − GWT basic widgets are created in this way. Still its a very complicated way to create custom widget and should be used cautiously. Use JavaScript and wrap it in a widget using JSNI − This should generally only be done as a last resort. Considering the cross-browser implications of the native methods, it becomes very complicated and also becomes more difficult to debug. Use JavaScript and wrap it in a widget using JSNI − This should generally only be done as a last resort. Considering the cross-browser implications of the native methods, it becomes very complicated and also becomes more difficult to debug. This example will take you through simple steps to show creation of a Custom Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Basic Widgets chapter − Here we are going to create a custom widget by extending Composite class, which is the easiest way to build custom widgets. Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml. <?xml version = "1.0" encoding = "UTF-8"?> <module rename-to = 'helloworld'> <!-- Inherit the core Web Toolkit stuff. --> <inherits name = 'com.google.gwt.user.User'/> <!-- Inherit the default GWT style sheet. --> <inherits name = 'com.google.gwt.user.theme.clean.Clean'/> <!-- Specify the app entry point class. --> <entry-point class = 'com.tutorialspoint.client.HelloWorld'/> <!-- Specify the paths for translatable code --> <source path = 'client'/> <source path = 'shared'/> </module> Following is the content of the modified Style Sheet file war/HelloWorld.css. body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } Following is the content of the modified HTML host file war/HelloWorld.html. <html> <head> <title>Hello World</title> <link rel = "stylesheet" href = "HelloWorld.css"/> <script language = "javascript" src = "helloworld/helloworld.nocache.js"> </script> </head> <body> <h1>Custom Widget Demonstration</h1> <div id = "gwtContainer"></div> </body> </html> Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate creation of a Custom widget. package com.tutorialspoint.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; public class HelloWorld implements EntryPoint { /** * A composite of a TextBox and a CheckBox that optionally enables it. */ private static class OptionalTextBox extends Composite implements ClickHandler { private TextBox textBox = new TextBox(); private CheckBox checkBox = new CheckBox(); private boolean enabled = true; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Style this widget using .optionalTextWidget CSS class.<br/> * Style textbox using .optionalTextBox CSS class.<br/> * Style checkbox using .optionalCheckBox CSS class.<br/> * Constructs an OptionalTextBox with the given caption * on the check. * @param caption the caption to be displayed with the check box */ public OptionalTextBox(String caption) { // place the check above the text box using a vertical panel. HorizontalPanel panel = new HorizontalPanel(); // panel.setBorderWidth(1); panel.setSpacing(10); panel.add(checkBox); panel.add(textBox); // all composites must call initWidget() in their constructors. initWidget(panel); //set style name for entire widget setStyleName("optionalTextWidget"); //set style name for text box textBox.setStyleName("optionalTextBox"); //set style name for check box checkBox.setStyleName("optionalCheckBox"); textBox.setWidth("200"); // Set the check box's caption, and check it by default. checkBox.setText(caption); checkBox.setValue(enabled); checkBox.addClickHandler(this); enableTextBox(enabled,checkBox.getValue()); } public void onClick(ClickEvent event) { if (event.getSource() == checkBox) { // When the check box is clicked, //update the text box's enabled state. enableTextBox(enabled,checkBox.getValue()); } } private void enableTextBox(boolean enable,boolean isChecked){ enable = (enable && isChecked) || (!enable && !isChecked); textBox.setStyleDependentName("disabled", !enable); textBox.setEnabled(enable); } } public void onModuleLoad() { // Create an optional text box and add it to the root panel. OptionalTextBox otb = new OptionalTextBox( "Want to explain the solution?"); otb.setEnabled(true); RootPanel.get().add(otb); } } Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result − You can notice following points Creation of Custom Widget by extending Composite widget is pretty easy. Creation of Custom Widget by extending Composite widget is pretty easy. We've created a widget with GWT inbuilt widgets, TextBox and CheckBox thus using the concept of reusability. We've created a widget with GWT inbuilt widgets, TextBox and CheckBox thus using the concept of reusability. TextBox get disabled/enabled depending on state of checkbox. We've provided an API to enable/disable the control. TextBox get disabled/enabled depending on state of checkbox. We've provided an API to enable/disable the control. We've exposed internal widgets styles via documented CSS styles. We've exposed internal widgets styles via documented CSS styles. Print Add Notes Bookmark this page
[ { "code": null, "e": 2136, "s": 2023, "text": "GWT provides three ways to create custom user interface elements. There are three general strategies to follow −" }, { "code": null, "e": 2332, "s": 2136, "text": "Create a widget by extending Composite Class − This is the most common and easiest way to create custom widgets. Here you can use existing widgets to create composite view with custom properties." }, { "code": null, "e": 2528, "s": 2332, "text": "Create a widget by extending Composite Class − This is the most common and easiest way to create custom widgets. Here you can use existing widgets to create composite view with custom properties." }, { "code": null, "e": 2703, "s": 2528, "text": "Create a widget using GWT DOM API in JAVA − GWT basic widgets are created in this way. Still its a very complicated way to create custom widget and should be used cautiously." }, { "code": null, "e": 2878, "s": 2703, "text": "Create a widget using GWT DOM API in JAVA − GWT basic widgets are created in this way. Still its a very complicated way to create custom widget and should be used cautiously." }, { "code": null, "e": 3119, "s": 2878, "text": "Use JavaScript and wrap it in a widget using JSNI − This should generally only be done as a last resort. Considering the cross-browser implications of the native methods, it becomes very complicated and also becomes more difficult to debug." }, { "code": null, "e": 3360, "s": 3119, "text": "Use JavaScript and wrap it in a widget using JSNI − This should generally only be done as a last resort. Considering the cross-browser implications of the native methods, it becomes very complicated and also becomes more difficult to debug." }, { "code": null, "e": 3553, "s": 3360, "text": "This example will take you through simple steps to show creation of a Custom Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Basic Widgets chapter −" }, { "code": null, "e": 3677, "s": 3553, "text": "Here we are going to create a custom widget by extending Composite class, which is the easiest way to build custom widgets." }, { "code": null, "e": 3779, "s": 3677, "text": "Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml." }, { "code": null, "e": 4388, "s": 3779, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<module rename-to = 'helloworld'>\n <!-- Inherit the core Web Toolkit stuff. -->\n <inherits name = 'com.google.gwt.user.User'/>\n\n <!-- Inherit the default GWT style sheet. -->\n <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>\n\n <!-- Specify the app entry point class. -->\n <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>\n\n <!-- Specify the paths for translatable code -->\n <source path = 'client'/>\n <source path = 'shared'/>\n\n</module>" }, { "code": null, "e": 4466, "s": 4388, "text": "Following is the content of the modified Style Sheet file war/HelloWorld.css." }, { "code": null, "e": 4652, "s": 4466, "text": "body {\n text-align: center;\n font-family: verdana, sans-serif;\n}\n\nh1 {\n font-size: 2em;\n font-weight: bold;\n color: #777777;\n margin: 40px 0px 70px;\n text-align: center;\n}" }, { "code": null, "e": 4729, "s": 4652, "text": "Following is the content of the modified HTML host file war/HelloWorld.html." }, { "code": null, "e": 5054, "s": 4729, "text": "<html>\n <head>\n <title>Hello World</title>\n <link rel = \"stylesheet\" href = \"HelloWorld.css\"/>\n <script language = \"javascript\" src = \"helloworld/helloworld.nocache.js\">\n </script>\n </head>\n\n <body>\n <h1>Custom Widget Demonstration</h1>\n <div id = \"gwtContainer\"></div>\n </body>\n</html>" }, { "code": null, "e": 5188, "s": 5054, "text": "Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate creation of a Custom widget." }, { "code": null, "e": 8278, "s": 5188, "text": "package com.tutorialspoint.client;\n\nimport com.google.gwt.core.client.EntryPoint;\nimport com.google.gwt.event.dom.client.ClickEvent;\nimport com.google.gwt.event.dom.client.ClickHandler;\nimport com.google.gwt.user.client.ui.CheckBox;\nimport com.google.gwt.user.client.ui.Composite;\nimport com.google.gwt.user.client.ui.HorizontalPanel;\nimport com.google.gwt.user.client.ui.RootPanel;\nimport com.google.gwt.user.client.ui.TextBox;\n\npublic class HelloWorld implements EntryPoint {\n\n /**\n * A composite of a TextBox and a CheckBox that optionally enables it.\n */\n private static class OptionalTextBox extends Composite implements\n ClickHandler {\n\n private TextBox textBox = new TextBox();\n private CheckBox checkBox = new CheckBox();\n private boolean enabled = true;\n\n public boolean isEnabled() {\n return enabled;\n }\n\n public void setEnabled(boolean enabled) {\n this.enabled = enabled;\n }\n\n /**\n * Style this widget using .optionalTextWidget CSS class.<br/>\n * Style textbox using .optionalTextBox CSS class.<br/>\n * Style checkbox using .optionalCheckBox CSS class.<br/>\n * Constructs an OptionalTextBox with the given caption \n * on the check.\n * @param caption the caption to be displayed with the check box\n */\n public OptionalTextBox(String caption) {\n // place the check above the text box using a vertical panel.\n HorizontalPanel panel = new HorizontalPanel();\n // panel.setBorderWidth(1);\n panel.setSpacing(10);\n panel.add(checkBox);\n panel.add(textBox);\n\n // all composites must call initWidget() in their constructors.\n initWidget(panel);\n \n //set style name for entire widget\n setStyleName(\"optionalTextWidget\");\n \n //set style name for text box\n textBox.setStyleName(\"optionalTextBox\");\n \n //set style name for check box\n checkBox.setStyleName(\"optionalCheckBox\");\n textBox.setWidth(\"200\");\n \n // Set the check box's caption, and check it by default.\n checkBox.setText(caption);\n checkBox.setValue(enabled);\n checkBox.addClickHandler(this);\n enableTextBox(enabled,checkBox.getValue());\n }\n\n public void onClick(ClickEvent event) {\n if (event.getSource() == checkBox) {\n // When the check box is clicked,\n //update the text box's enabled state.\n enableTextBox(enabled,checkBox.getValue());\n }\n }\n\n private void enableTextBox(boolean enable,boolean isChecked){\n enable = (enable && isChecked) || (!enable && !isChecked);\n textBox.setStyleDependentName(\"disabled\", !enable);\n textBox.setEnabled(enable);\t \n }\n }\n\n public void onModuleLoad() {\n // Create an optional text box and add it to the root panel.\n OptionalTextBox otb = new OptionalTextBox(\n \"Want to explain the solution?\");\n otb.setEnabled(true);\n RootPanel.get().add(otb);\n } \n} " }, { "code": null, "e": 8512, "s": 8278, "text": "Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −" }, { "code": null, "e": 8544, "s": 8512, "text": "You can notice following points" }, { "code": null, "e": 8616, "s": 8544, "text": "Creation of Custom Widget by extending Composite widget is pretty easy." }, { "code": null, "e": 8688, "s": 8616, "text": "Creation of Custom Widget by extending Composite widget is pretty easy." }, { "code": null, "e": 8797, "s": 8688, "text": "We've created a widget with GWT inbuilt widgets, TextBox and CheckBox thus using the concept of reusability." }, { "code": null, "e": 8906, "s": 8797, "text": "We've created a widget with GWT inbuilt widgets, TextBox and CheckBox thus using the concept of reusability." }, { "code": null, "e": 9020, "s": 8906, "text": "TextBox get disabled/enabled depending on state of checkbox. We've provided an API to enable/disable the control." }, { "code": null, "e": 9134, "s": 9020, "text": "TextBox get disabled/enabled depending on state of checkbox. We've provided an API to enable/disable the control." }, { "code": null, "e": 9199, "s": 9134, "text": "We've exposed internal widgets styles via documented CSS styles." }, { "code": null, "e": 9264, "s": 9199, "text": "We've exposed internal widgets styles via documented CSS styles." }, { "code": null, "e": 9271, "s": 9264, "text": " Print" }, { "code": null, "e": 9282, "s": 9271, "text": " Add Notes" } ]
How to make a case-insensitive query in MongoDB?
For a case-insensitive query, use regex in MongoDB. Let us create a collection with documents − > db.demo314.insertOne({"Name":"Chris brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50d742f8647eb59e562056") } > db.demo314.insertOne({"Name":"David Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50d743f8647eb59e562057") } > db.demo314.insertOne({"Name":"CHRIS BROWN"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50d744f8647eb59e562058") } > db.demo314.insertOne({"Name":"DAVID MILLER"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50d747f8647eb59e562059") } > db.demo314.insertOne({"Name":"chris brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50d749f8647eb59e56205a") } Display all documents from a collection with the help of find() method − > db.demo314.find(); This will produce the following output − { "_id" : ObjectId("5e50d742f8647eb59e562056"), "Name" : "Chris brown" } { "_id" : ObjectId("5e50d743f8647eb59e562057"), "Name" : "David Miller" } { "_id" : ObjectId("5e50d744f8647eb59e562058"), "Name" : "CHRIS BROWN" } { "_id" : ObjectId("5e50d747f8647eb59e562059"), "Name" : "DAVID MILLER" } { "_id" : ObjectId("5e50d749f8647eb59e56205a"), "Name" : "chris brown" } Following is the query to make a case-insensitive query. This displays “chris brown” name available in every possible case in the document − > db.demo314.find({"Name":/chris brown/i}); This will produce the following output − { "_id" : ObjectId("5e50d742f8647eb59e562056"), "Name" : "Chris brown" } { "_id" : ObjectId("5e50d744f8647eb59e562058"), "Name" : "CHRIS BROWN" } { "_id" : ObjectId("5e50d749f8647eb59e56205a"), "Name" : "chris brown" }
[ { "code": null, "e": 1158, "s": 1062, "text": "For a case-insensitive query, use regex in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 1825, "s": 1158, "text": "> db.demo314.insertOne({\"Name\":\"Chris brown\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e50d742f8647eb59e562056\")\n}\n> db.demo314.insertOne({\"Name\":\"David Miller\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e50d743f8647eb59e562057\")\n}\n> db.demo314.insertOne({\"Name\":\"CHRIS BROWN\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e50d744f8647eb59e562058\")\n}\n> db.demo314.insertOne({\"Name\":\"DAVID MILLER\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e50d747f8647eb59e562059\")\n}\n> db.demo314.insertOne({\"Name\":\"chris brown\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e50d749f8647eb59e56205a\")\n}" }, { "code": null, "e": 1898, "s": 1825, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1919, "s": 1898, "text": "> db.demo314.find();" }, { "code": null, "e": 1960, "s": 1919, "text": "This will produce the following output −" }, { "code": null, "e": 2327, "s": 1960, "text": "{ \"_id\" : ObjectId(\"5e50d742f8647eb59e562056\"), \"Name\" : \"Chris brown\" }\n{ \"_id\" : ObjectId(\"5e50d743f8647eb59e562057\"), \"Name\" : \"David Miller\" }\n{ \"_id\" : ObjectId(\"5e50d744f8647eb59e562058\"), \"Name\" : \"CHRIS BROWN\" }\n{ \"_id\" : ObjectId(\"5e50d747f8647eb59e562059\"), \"Name\" : \"DAVID MILLER\" }\n{ \"_id\" : ObjectId(\"5e50d749f8647eb59e56205a\"), \"Name\" : \"chris brown\" }" }, { "code": null, "e": 2468, "s": 2327, "text": "Following is the query to make a case-insensitive query. This displays “chris brown” name available in every possible case in the document −" }, { "code": null, "e": 2512, "s": 2468, "text": "> db.demo314.find({\"Name\":/chris brown/i});" }, { "code": null, "e": 2553, "s": 2512, "text": "This will produce the following output −" }, { "code": null, "e": 2772, "s": 2553, "text": "{ \"_id\" : ObjectId(\"5e50d742f8647eb59e562056\"), \"Name\" : \"Chris brown\" }\n{ \"_id\" : ObjectId(\"5e50d744f8647eb59e562058\"), \"Name\" : \"CHRIS BROWN\" }\n{ \"_id\" : ObjectId(\"5e50d749f8647eb59e56205a\"), \"Name\" : \"chris brown\" }" } ]
Adobe Interview | Set 13 (On Campus for Internship) - GeeksforGeeks
23 May, 2019 We had Adobe visit our campus recently. First they shortlisted students for an online test on the basis of CGPA. A few students even got direct offer. Online RoundThere were 8 questions in total. 5 MCQ, 2 Coding and 1 question was based on creativity.The MCQ’s were on heap, and probability. Finding the expectations and the running time complexities for heaps were the main focus of the MCQ’s.In the coding questions we had to write pseudocode, not actual C++ code. In the coding questions we had to write pseudocode, not actual C++ code. 1st question: There is a stream of incoming integers, how would you maintain its median using a minHeap and a maxHeap. 2nd question: You have the start time, end time and index number of racers in a race. You need to tell the rank of each racer. The rank is calculated as following: if racer B starts after racer A but finishes before racer A, then the rank of racer A increases by 1.Eg, Index Start Time End time 0 100 170 1 80 150 2 120 165 3 110 145 Output Index Rank 2 0 3 0 1 1 0 2I did it in O(n2), but I think there should be an O(nlogn) algorithm for this.The last creative question was:If the 3G wireless network and smartphone penetration in India reached as much as the cellular network penetration, what product would you design and i) how would it benefit the customers and ii) how would you profit? (Write-in roughly 200 words).I was shortlisted for the telephonic interview. Eg, Index Start Time End time 0 100 170 1 80 150 2 120 165 3 110 145 Output Index Rank 2 0 3 0 1 1 0 2 I did it in O(n2), but I think there should be an O(nlogn) algorithm for this. The last creative question was:If the 3G wireless network and smartphone penetration in India reached as much as the cellular network penetration, what product would you design and i) how would it benefit the customers and ii) how would you profit? (Write-in roughly 200 words). I was shortlisted for the telephonic interview. Telephonic InterviewI introduced myself, and my projects. He asked me some details of the projects that he found interesting. After this, he asked me algorithm questions.What is the running time for insertion, deletion, extracting min from a minHeap?What is the running time for insertion, deletion and searching an element in a sorted array and the same for an unsorted array?How would you determine if a coin is biased or not. Does the degree of biasity effect the number of experiments you have to perform? (Example: if the prob of heads is 0.6 in one case and 0.7 in another, then would you still perform the same number of experiments to decide if they are biased or different number of experiments). What is the running time for insertion, deletion, extracting min from a minHeap?What is the running time for insertion, deletion and searching an element in a sorted array and the same for an unsorted array?How would you determine if a coin is biased or not. Does the degree of biasity effect the number of experiments you have to perform? (Example: if the prob of heads is 0.6 in one case and 0.7 in another, then would you still perform the same number of experiments to decide if they are biased or different number of experiments). What is the running time for insertion, deletion, extracting min from a minHeap? What is the running time for insertion, deletion and searching an element in a sorted array and the same for an unsorted array? How would you determine if a coin is biased or not. Does the degree of biasity effect the number of experiments you have to perform? (Example: if the prob of heads is 0.6 in one case and 0.7 in another, then would you still perform the same number of experiments to decide if they are biased or different number of experiments). Thank you GeeksforGeeks. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Adobe Internship Interview Experiences Adobe Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Zoho Interview Experience (Off-Campus ) 2022 Resume Writing For Internship HashedIn by Deloitte Interview Experience for SDE Intern+FTE | (Off-Campus) 2022 Uber Internship Interview Experience | Off-Campus 2022 Amazon Interview Questions Commonly Asked Java Programming Interview Questions | Set 2 Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Zoho Interview | Set 3 (Off-Campus)
[ { "code": null, "e": 26207, "s": 26179, "text": "\n23 May, 2019" }, { "code": null, "e": 26358, "s": 26207, "text": "We had Adobe visit our campus recently. First they shortlisted students for an online test on the basis of CGPA. A few students even got direct offer." }, { "code": null, "e": 26674, "s": 26358, "text": "Online RoundThere were 8 questions in total. 5 MCQ, 2 Coding and 1 question was based on creativity.The MCQ’s were on heap, and probability. Finding the expectations and the running time complexities for heaps were the main focus of the MCQ’s.In the coding questions we had to write pseudocode, not actual C++ code." }, { "code": null, "e": 26747, "s": 26674, "text": "In the coding questions we had to write pseudocode, not actual C++ code." }, { "code": null, "e": 26866, "s": 26747, "text": "1st question: There is a stream of incoming integers, how would you maintain its median using a minHeap and a maxHeap." }, { "code": null, "e": 27739, "s": 26866, "text": "2nd question: You have the start time, end time and index number of racers in a race. You need to tell the rank of each racer. The rank is calculated as following: if racer B starts after racer A but finishes before racer A, then the rank of racer A increases by 1.Eg, \nIndex Start Time End time\n0 100 170\n1 80 150\n2 120 165\n3 110 145\n\nOutput\nIndex Rank\n2 0\n3 0\n1 1\n0 2I did it in O(n2), but I think there should be an O(nlogn) algorithm for this.The last creative question was:If the 3G wireless network and smartphone penetration in India reached as much as the cellular network penetration, what product would you design and i) how would it benefit the customers and ii) how would you profit? (Write-in roughly 200 words).I was shortlisted for the telephonic interview." }, { "code": null, "e": 27944, "s": 27739, "text": "Eg, \nIndex Start Time End time\n0 100 170\n1 80 150\n2 120 165\n3 110 145\n\nOutput\nIndex Rank\n2 0\n3 0\n1 1\n0 2" }, { "code": null, "e": 28023, "s": 27944, "text": "I did it in O(n2), but I think there should be an O(nlogn) algorithm for this." }, { "code": null, "e": 28302, "s": 28023, "text": "The last creative question was:If the 3G wireless network and smartphone penetration in India reached as much as the cellular network penetration, what product would you design and i) how would it benefit the customers and ii) how would you profit? (Write-in roughly 200 words)." }, { "code": null, "e": 28350, "s": 28302, "text": "I was shortlisted for the telephonic interview." }, { "code": null, "e": 29056, "s": 28350, "text": "Telephonic InterviewI introduced myself, and my projects. He asked me some details of the projects that he found interesting. After this, he asked me algorithm questions.What is the running time for insertion, deletion, extracting min from a minHeap?What is the running time for insertion, deletion and searching an element in a sorted array and the same for an unsorted array?How would you determine if a coin is biased or not. Does the degree of biasity effect the number of experiments you have to perform? (Example: if the prob of heads is 0.6 in one case and 0.7 in another, then would you still perform the same number of experiments to decide if they are biased or different number of experiments)." }, { "code": null, "e": 29592, "s": 29056, "text": "What is the running time for insertion, deletion, extracting min from a minHeap?What is the running time for insertion, deletion and searching an element in a sorted array and the same for an unsorted array?How would you determine if a coin is biased or not. Does the degree of biasity effect the number of experiments you have to perform? (Example: if the prob of heads is 0.6 in one case and 0.7 in another, then would you still perform the same number of experiments to decide if they are biased or different number of experiments)." }, { "code": null, "e": 29673, "s": 29592, "text": "What is the running time for insertion, deletion, extracting min from a minHeap?" }, { "code": null, "e": 29801, "s": 29673, "text": "What is the running time for insertion, deletion and searching an element in a sorted array and the same for an unsorted array?" }, { "code": null, "e": 30130, "s": 29801, "text": "How would you determine if a coin is biased or not. Does the degree of biasity effect the number of experiments you have to perform? (Example: if the prob of heads is 0.6 in one case and 0.7 in another, then would you still perform the same number of experiments to decide if they are biased or different number of experiments)." }, { "code": null, "e": 30155, "s": 30130, "text": "Thank you GeeksforGeeks." }, { "code": null, "e": 30376, "s": 30155, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 30382, "s": 30376, "text": "Adobe" }, { "code": null, "e": 30393, "s": 30382, "text": "Internship" }, { "code": null, "e": 30415, "s": 30393, "text": "Interview Experiences" }, { "code": null, "e": 30421, "s": 30415, "text": "Adobe" }, { "code": null, "e": 30519, "s": 30421, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30591, "s": 30519, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 30636, "s": 30591, "text": "Zoho Interview Experience (Off-Campus ) 2022" }, { "code": null, "e": 30666, "s": 30636, "text": "Resume Writing For Internship" }, { "code": null, "e": 30747, "s": 30666, "text": "HashedIn by Deloitte Interview Experience for SDE Intern+FTE | (Off-Campus) 2022" }, { "code": null, "e": 30802, "s": 30747, "text": "Uber Internship Interview Experience | Off-Campus 2022" }, { "code": null, "e": 30829, "s": 30802, "text": "Amazon Interview Questions" }, { "code": null, "e": 30889, "s": 30829, "text": "Commonly Asked Java Programming Interview Questions | Set 2" }, { "code": null, "e": 30940, "s": 30889, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 30982, "s": 30940, "text": "Amazon AWS Interview Experience for SDE-1" } ]
A Beginner’s Guide to Latent Dirichlet Allocation(LDA) | by Ria Kulshrestha | Towards Data Science
Topic modeling is a method for unsupervised classification of documents, similar to clustering on numeric data, which finds some natural groups of items (topics) even when we’re not sure what we’re looking for. A document can be a part of multiple topics, kind of like in fuzzy clustering(soft clustering) in which each data point belongs to more than one cluster. Topic modeling provides methods for automatically organizing, understanding, searching, and summarizing large electronic archives. It can help with the following: discovering the hidden themes in the collection. classifying the documents into the discovered themes. using the classification to organize/summarize/search the documents. For example, let’s say a document belongs to the topics food, dogs and health. So if a user queries “dog food”, they might find the above-mentioned document relevant because it covers those topics(among other topics). We are able to figure its relevance with respect to the query without even going through the entire document. Therefore, by annotating the document, based on the topics predicted by the modeling method, we are able to optimize our search process. It is one of the most popular topic modeling methods. Each document is made up of various words, and each topic also has various words belonging to it. The aim of LDA is to find topics a document belongs to, based on the words in it. Confused much? Here is an example to walk you through it. We have 5 documents each containing the words listed in front of them( ordered by frequency of occurrence). What we want to figure out are the words in different topics, as shown in the table below. Each row in the table represents a different topic and each column a different word in the corpus. Each cell contains the probability that the word(column) belongs to the topic(row). We can sort the words with respect to their probability score. The top x words are chosen from each topic to represent the topic. If x = 10, we’ll sort all the words in topic1 based on their score and take the top 10 words to represent the topic. This step may not always be necessary because if the corpus is small we can store all the words in sorted by their score. Alternatively, we can set a threshold on the score. All the words in a topic having a score above the threshold can be stored as its representative, in order of their scores. Let’s say we have 2 topics that can be classified as CAT_related and DOG_related. A topic has probabilities for each word, so words such as milk, meow, and kitten, will have a higher probability in the CAT_related topic than in the DOG_related one. The DOG_related topic, likewise, will have high probabilities for words such as puppy, bark, and bone. If we have a document containing the following sentences: “Dogs like to chew on bones and fetch sticks”. “Puppies drink milk.” “Both like to bark.” We can easily say it belongs to topic DOG_related because it contains words such as Dogs, bones, puppies, and bark. Even though it contains the word milk which belongs to the topic CAT_related, the document belongs to DOG_related as more words match with it. Each document is just a collection of words or a “bag of words”. Thus, the order of the words and the grammatical role of the words (subject, object, verbs, ...) are not considered in the model. Words like am/is/are/of/a/the/but/... don’t carry any information about the “topics” and therefore can be eliminated from the documents as a preprocessing step. In fact, we can eliminate words that occur in at least %80 ~ %90 of the documents, without losing any information.For example, if our corpus contains only medical documents, words like human, body, health, etc might be present in most of the documents and hence can be removed as they don’t add any specific information which would make the document stand out. We know beforehand how many topics we want. ‘k’ is pre-decided. All topic assignments except for the current word in question are correct, and then updating the assignment of the current word using our model of how documents are generated There are 2 parts in LDA: The words that belong to a document, that we already know. The words that belong to a topic or the probability of words belonging into a topic, that we need to calculate. Go through each document and randomly assign each word in the document to one of k topics (k is chosen beforehand). For each document d, go through each word w and compute : p(topic t | document d): the proportion of words in document d that are assigned to topic t. Tries to capture how many words belong to the topic t for a given document d. Excluding the current word.If a lot of words from d belongs to t, it is more probable that word w belongs to t.( #words in d with t +alpha/ #words in d with any topic+ k*alpha)p(word w| topic t): the proportion of assignments to topic t over all documents that come from this word w. Tries to capture how many documents are in topic t because of word w.LDA represents documents as a mixture of topics. Similarly, a topic is a mixture of words. If a word has high probability of being in a topic, all the documents having w will be more strongly associated with t as well. Similarly, if w is not very probable to be in t, the documents which contain the w will be having very low probability of being in t, because rest of the words in d will belong to some other topic and hence d will have a higher probability for those topic. So even if w gets added to t, it won’t be bringing many such documents to t. p(topic t | document d): the proportion of words in document d that are assigned to topic t. Tries to capture how many words belong to the topic t for a given document d. Excluding the current word.If a lot of words from d belongs to t, it is more probable that word w belongs to t.( #words in d with t +alpha/ #words in d with any topic+ k*alpha) p(word w| topic t): the proportion of assignments to topic t over all documents that come from this word w. Tries to capture how many documents are in topic t because of word w.LDA represents documents as a mixture of topics. Similarly, a topic is a mixture of words. If a word has high probability of being in a topic, all the documents having w will be more strongly associated with t as well. Similarly, if w is not very probable to be in t, the documents which contain the w will be having very low probability of being in t, because rest of the words in d will belong to some other topic and hence d will have a higher probability for those topic. So even if w gets added to t, it won’t be bringing many such documents to t. Update the probability for the word w belonging to topic t, as p(word w with topic t) = p(topic t | document d) * p(word w | topic t) Suppose you have various photographs(documents) with captions(words). You want to display them in a gallery so you decide to categorize the photographs on various themes(topics) based on which you will create different sections in your gallery. You decide to create k=2 sections in your album — nature and city. Naturally, the classification isn’t so clear as some photographs with city have trees and flowers while the nature ones might have some buildings in it. You, as a start, decide to assign the photographs which only have nature or city elements in them into their respective categories while you randomly assigned the rest. You notice that a lot of photographs in nature have the word tree in their captions. So you concluded that the word tree and topic nature must be closely related. Next, you pick the word building and check how many photographs are in nature because they have the word building in their caption. You don’t find many and now are less sure about building belonging to the topic nature and associate it more strongly with the topic city. You then pick a photograph which has the caption “The tree is in front of the building and behind a car” and see that it is in the category nature currently.You then chose the word tree, and calculate the first probability p(topic t | document d): other words in the caption are building and car, most photographs having captions with building or car in it are in city, so you get a low probability.Now the second probability p(word w| topic t): we know that a lot of photographs in nature have the word trees in it. So you get a high score here.You update the probability of tree belonging in nature by multiplying the two. You get a lower value than before for tree in topic nature because now you have seen that tree and words such as building/car in the same caption, implying that trees can also be found in cities. For the same reason, when you update the probability for tree belonging in topic city, you will notice that it will be greater than what it was before. After multiple iterations over all the photographs and for each topic, you will have accurate scores for each word with respect to each topic. Your guesses will keep getting better and better because you’ll conclude from the context that words such as buildings, sidewalk, subway appear together and hence must belong to the same topic, which we can easily guess is city. Words such as mountains, fields, beach which might not appear together in a lot of captions but they do appear often without city words and hence will have higher scores for nature. While words such as trees, flowers, dogs, sky will have almost the same probability of being in either as they occur in both topics. As for the photograph, you see that it has 1 word (with average probability) from category nature and 2 words (with high probability) from city, you conclude, it belongs to city more strongly than it does to nature and hence you decide to add it in city. The applications of LDA need not be restricted to Natural Language Processing. I recently implemented a paper where we use LDA( along with a Neural Networks) to extract the scene-specific context of an image. If you are interested in learning more about that please leave a comment or a message. If you are looking for an implementation of LDA, here is an amazing article on Towards Data Science which does it pretty well! See “A layman’s example” in Edwin Chen Blog to gain more intuition about LDA. Evaluation of an NLP model — latest benchmarks Understanding Attention In Deep Learning Transformers — the basic block for models such as Google’s BERT and OpenAI’s GPT. I‘m glad you made it till the end of this article.🎉I hope your reading experience was as enriching as the one I had writing this. 💖 Do check out my other articles here. If you want to reach out to me, my medium of choice would be Twitter.
[ { "code": null, "e": 383, "s": 172, "text": "Topic modeling is a method for unsupervised classification of documents, similar to clustering on numeric data, which finds some natural groups of items (topics) even when we’re not sure what we’re looking for." }, { "code": null, "e": 537, "s": 383, "text": "A document can be a part of multiple topics, kind of like in fuzzy clustering(soft clustering) in which each data point belongs to more than one cluster." }, { "code": null, "e": 700, "s": 537, "text": "Topic modeling provides methods for automatically organizing, understanding, searching, and summarizing large electronic archives. It can help with the following:" }, { "code": null, "e": 749, "s": 700, "text": "discovering the hidden themes in the collection." }, { "code": null, "e": 803, "s": 749, "text": "classifying the documents into the discovered themes." }, { "code": null, "e": 872, "s": 803, "text": "using the classification to organize/summarize/search the documents." }, { "code": null, "e": 1200, "s": 872, "text": "For example, let’s say a document belongs to the topics food, dogs and health. So if a user queries “dog food”, they might find the above-mentioned document relevant because it covers those topics(among other topics). We are able to figure its relevance with respect to the query without even going through the entire document." }, { "code": null, "e": 1337, "s": 1200, "text": "Therefore, by annotating the document, based on the topics predicted by the modeling method, we are able to optimize our search process." }, { "code": null, "e": 1629, "s": 1337, "text": "It is one of the most popular topic modeling methods. Each document is made up of various words, and each topic also has various words belonging to it. The aim of LDA is to find topics a document belongs to, based on the words in it. Confused much? Here is an example to walk you through it." }, { "code": null, "e": 1737, "s": 1629, "text": "We have 5 documents each containing the words listed in front of them( ordered by frequency of occurrence)." }, { "code": null, "e": 2011, "s": 1737, "text": "What we want to figure out are the words in different topics, as shown in the table below. Each row in the table represents a different topic and each column a different word in the corpus. Each cell contains the probability that the word(column) belongs to the topic(row)." }, { "code": null, "e": 2380, "s": 2011, "text": "We can sort the words with respect to their probability score. The top x words are chosen from each topic to represent the topic. If x = 10, we’ll sort all the words in topic1 based on their score and take the top 10 words to represent the topic. This step may not always be necessary because if the corpus is small we can store all the words in sorted by their score." }, { "code": null, "e": 2555, "s": 2380, "text": "Alternatively, we can set a threshold on the score. All the words in a topic having a score above the threshold can be stored as its representative, in order of their scores." }, { "code": null, "e": 2907, "s": 2555, "text": "Let’s say we have 2 topics that can be classified as CAT_related and DOG_related. A topic has probabilities for each word, so words such as milk, meow, and kitten, will have a higher probability in the CAT_related topic than in the DOG_related one. The DOG_related topic, likewise, will have high probabilities for words such as puppy, bark, and bone." }, { "code": null, "e": 2965, "s": 2907, "text": "If we have a document containing the following sentences:" }, { "code": null, "e": 3055, "s": 2965, "text": "“Dogs like to chew on bones and fetch sticks”. “Puppies drink milk.” “Both like to bark.”" }, { "code": null, "e": 3314, "s": 3055, "text": "We can easily say it belongs to topic DOG_related because it contains words such as Dogs, bones, puppies, and bark. Even though it contains the word milk which belongs to the topic CAT_related, the document belongs to DOG_related as more words match with it." }, { "code": null, "e": 3509, "s": 3314, "text": "Each document is just a collection of words or a “bag of words”. Thus, the order of the words and the grammatical role of the words (subject, object, verbs, ...) are not considered in the model." }, { "code": null, "e": 4031, "s": 3509, "text": "Words like am/is/are/of/a/the/but/... don’t carry any information about the “topics” and therefore can be eliminated from the documents as a preprocessing step. In fact, we can eliminate words that occur in at least %80 ~ %90 of the documents, without losing any information.For example, if our corpus contains only medical documents, words like human, body, health, etc might be present in most of the documents and hence can be removed as they don’t add any specific information which would make the document stand out." }, { "code": null, "e": 4095, "s": 4031, "text": "We know beforehand how many topics we want. ‘k’ is pre-decided." }, { "code": null, "e": 4270, "s": 4095, "text": "All topic assignments except for the current word in question are correct, and then updating the assignment of the current word using our model of how documents are generated" }, { "code": null, "e": 4296, "s": 4270, "text": "There are 2 parts in LDA:" }, { "code": null, "e": 4355, "s": 4296, "text": "The words that belong to a document, that we already know." }, { "code": null, "e": 4467, "s": 4355, "text": "The words that belong to a topic or the probability of words belonging into a topic, that we need to calculate." }, { "code": null, "e": 4583, "s": 4467, "text": "Go through each document and randomly assign each word in the document to one of k topics (k is chosen beforehand)." }, { "code": null, "e": 4641, "s": 4583, "text": "For each document d, go through each word w and compute :" }, { "code": null, "e": 5718, "s": 4641, "text": "p(topic t | document d): the proportion of words in document d that are assigned to topic t. Tries to capture how many words belong to the topic t for a given document d. Excluding the current word.If a lot of words from d belongs to t, it is more probable that word w belongs to t.( #words in d with t +alpha/ #words in d with any topic+ k*alpha)p(word w| topic t): the proportion of assignments to topic t over all documents that come from this word w. Tries to capture how many documents are in topic t because of word w.LDA represents documents as a mixture of topics. Similarly, a topic is a mixture of words. If a word has high probability of being in a topic, all the documents having w will be more strongly associated with t as well. Similarly, if w is not very probable to be in t, the documents which contain the w will be having very low probability of being in t, because rest of the words in d will belong to some other topic and hence d will have a higher probability for those topic. So even if w gets added to t, it won’t be bringing many such documents to t." }, { "code": null, "e": 6066, "s": 5718, "text": "p(topic t | document d): the proportion of words in document d that are assigned to topic t. Tries to capture how many words belong to the topic t for a given document d. Excluding the current word.If a lot of words from d belongs to t, it is more probable that word w belongs to t.( #words in d with t +alpha/ #words in d with any topic+ k*alpha)" }, { "code": null, "e": 6796, "s": 6066, "text": "p(word w| topic t): the proportion of assignments to topic t over all documents that come from this word w. Tries to capture how many documents are in topic t because of word w.LDA represents documents as a mixture of topics. Similarly, a topic is a mixture of words. If a word has high probability of being in a topic, all the documents having w will be more strongly associated with t as well. Similarly, if w is not very probable to be in t, the documents which contain the w will be having very low probability of being in t, because rest of the words in d will belong to some other topic and hence d will have a higher probability for those topic. So even if w gets added to t, it won’t be bringing many such documents to t." }, { "code": null, "e": 6859, "s": 6796, "text": "Update the probability for the word w belonging to topic t, as" }, { "code": null, "e": 6930, "s": 6859, "text": "p(word w with topic t) = p(topic t | document d) * p(word w | topic t)" }, { "code": null, "e": 7175, "s": 6930, "text": "Suppose you have various photographs(documents) with captions(words). You want to display them in a gallery so you decide to categorize the photographs on various themes(topics) based on which you will create different sections in your gallery." }, { "code": null, "e": 7564, "s": 7175, "text": "You decide to create k=2 sections in your album — nature and city. Naturally, the classification isn’t so clear as some photographs with city have trees and flowers while the nature ones might have some buildings in it. You, as a start, decide to assign the photographs which only have nature or city elements in them into their respective categories while you randomly assigned the rest." }, { "code": null, "e": 7727, "s": 7564, "text": "You notice that a lot of photographs in nature have the word tree in their captions. So you concluded that the word tree and topic nature must be closely related." }, { "code": null, "e": 7998, "s": 7727, "text": "Next, you pick the word building and check how many photographs are in nature because they have the word building in their caption. You don’t find many and now are less sure about building belonging to the topic nature and associate it more strongly with the topic city." }, { "code": null, "e": 8971, "s": 7998, "text": "You then pick a photograph which has the caption “The tree is in front of the building and behind a car” and see that it is in the category nature currently.You then chose the word tree, and calculate the first probability p(topic t | document d): other words in the caption are building and car, most photographs having captions with building or car in it are in city, so you get a low probability.Now the second probability p(word w| topic t): we know that a lot of photographs in nature have the word trees in it. So you get a high score here.You update the probability of tree belonging in nature by multiplying the two. You get a lower value than before for tree in topic nature because now you have seen that tree and words such as building/car in the same caption, implying that trees can also be found in cities. For the same reason, when you update the probability for tree belonging in topic city, you will notice that it will be greater than what it was before." }, { "code": null, "e": 9658, "s": 8971, "text": "After multiple iterations over all the photographs and for each topic, you will have accurate scores for each word with respect to each topic. Your guesses will keep getting better and better because you’ll conclude from the context that words such as buildings, sidewalk, subway appear together and hence must belong to the same topic, which we can easily guess is city. Words such as mountains, fields, beach which might not appear together in a lot of captions but they do appear often without city words and hence will have higher scores for nature. While words such as trees, flowers, dogs, sky will have almost the same probability of being in either as they occur in both topics." }, { "code": null, "e": 9913, "s": 9658, "text": "As for the photograph, you see that it has 1 word (with average probability) from category nature and 2 words (with high probability) from city, you conclude, it belongs to city more strongly than it does to nature and hence you decide to add it in city." }, { "code": null, "e": 10209, "s": 9913, "text": "The applications of LDA need not be restricted to Natural Language Processing. I recently implemented a paper where we use LDA( along with a Neural Networks) to extract the scene-specific context of an image. If you are interested in learning more about that please leave a comment or a message." }, { "code": null, "e": 10336, "s": 10209, "text": "If you are looking for an implementation of LDA, here is an amazing article on Towards Data Science which does it pretty well!" }, { "code": null, "e": 10414, "s": 10336, "text": "See “A layman’s example” in Edwin Chen Blog to gain more intuition about LDA." }, { "code": null, "e": 10461, "s": 10414, "text": "Evaluation of an NLP model — latest benchmarks" }, { "code": null, "e": 10502, "s": 10461, "text": "Understanding Attention In Deep Learning" }, { "code": null, "e": 10584, "s": 10502, "text": "Transformers — the basic block for models such as Google’s BERT and OpenAI’s GPT." }, { "code": null, "e": 10716, "s": 10584, "text": "I‘m glad you made it till the end of this article.🎉I hope your reading experience was as enriching as the one I had writing this. 💖" }, { "code": null, "e": 10753, "s": 10716, "text": "Do check out my other articles here." } ]
Lodash Introduction - GeeksforGeeks
10 Dec, 2021 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. It provides us with various inbuilt functions and uses a functional programming approach that makes coding in JavaScript easier to understand because instead of writing repetitive functions, tasks can be accomplished with a single line of code. It also makes it easier to work with objects in javascript if they require a lot of manipulation to be done upon them. Installation: It can be used directly using the CDN link or can be installed using npm or yarn. Method 1: We can directly use the Lodash file in the browser. Go to the official documentation and copy the lodash.min.js file CDN link and paste this link inside the head section. <script type = “text/JavaScript” src = “https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js”></script> Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <script type="text/JavaScript" src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"> </script></head> <body> <script> console.log(_.isNumber(100)); console.log(_.isNumber('GeeksforGeeks courses')); console.log(_.isNumber(78.43)); </script></body> </html> Output: true false true Method 2: We can install it by using npm. Make sure that you have installed Node.js and npm. npm install lodash If you are using yarn then you can use the following command: yarn install lodash Now in order to use Lodash, you need to require the code file. const _ = require("lodash"); Now let’s understand how to use Lodash with the help of the code example. Example: In this example, we will find whether the given value parameter is a number or not using one of the inbuilt methods in the lodash _.isNumber() method. index.js Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.isNumber() method console.log(_.isNumber(100)); console.log(_.isNumber('GeeksforGeeks courses')); console.log(_.isNumber(78.43)); Step to run the program: Save the above file with index.js and open the terminal and type the following command in order to compile and run the program. node index.js Output: true false true Advantages of Lodash: It provides us with various inbuilt functions for collections, arrays, to manipulate objects and other utilities methods which we can use directly instead of writing them from scratch. It keeps our code more short and clean that makes it easier to understand and modify later. We have to remember Lodash functions and that makes out the task of coding much simpler. It is easier to start and learn for tech newbies. Instead of writing repetitive functions, tasks can be accomplished with a single line of code. Disadvantages of Lodash: The firstmost disadvantage of Lodash is speed. Lodash methods take more time to execute than normal JavaScript functions. In JavaScript, we can chain many functions together as we want but in Lodash we can’t chain functions, we can only wrap them. JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React File uploading in React.js Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 37356, "s": 37328, "text": "\n10 Dec, 2021" }, { "code": null, "e": 37860, "s": 37356, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. It provides us with various inbuilt functions and uses a functional programming approach that makes coding in JavaScript easier to understand because instead of writing repetitive functions, tasks can be accomplished with a single line of code. It also makes it easier to work with objects in javascript if they require a lot of manipulation to be done upon them." }, { "code": null, "e": 37956, "s": 37860, "text": "Installation: It can be used directly using the CDN link or can be installed using npm or yarn." }, { "code": null, "e": 38137, "s": 37956, "text": "Method 1: We can directly use the Lodash file in the browser. Go to the official documentation and copy the lodash.min.js file CDN link and paste this link inside the head section." }, { "code": null, "e": 38246, "s": 38137, "text": "<script type = “text/JavaScript” src = “https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js”></script>" }, { "code": null, "e": 38255, "s": 38246, "text": "Example:" }, { "code": null, "e": 38260, "s": 38255, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <script type=\"text/JavaScript\" src=\"https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js\"> </script></head> <body> <script> console.log(_.isNumber(100)); console.log(_.isNumber('GeeksforGeeks courses')); console.log(_.isNumber(78.43)); </script></body> </html>", "e": 38683, "s": 38260, "text": null }, { "code": null, "e": 38691, "s": 38683, "text": "Output:" }, { "code": null, "e": 38707, "s": 38691, "text": "true\nfalse\ntrue" }, { "code": null, "e": 38800, "s": 38707, "text": "Method 2: We can install it by using npm. Make sure that you have installed Node.js and npm." }, { "code": null, "e": 38819, "s": 38800, "text": "npm install lodash" }, { "code": null, "e": 38881, "s": 38819, "text": "If you are using yarn then you can use the following command:" }, { "code": null, "e": 38901, "s": 38881, "text": "yarn install lodash" }, { "code": null, "e": 38964, "s": 38901, "text": "Now in order to use Lodash, you need to require the code file." }, { "code": null, "e": 38993, "s": 38964, "text": "const _ = require(\"lodash\");" }, { "code": null, "e": 39067, "s": 38993, "text": "Now let’s understand how to use Lodash with the help of the code example." }, { "code": null, "e": 39227, "s": 39067, "text": "Example: In this example, we will find whether the given value parameter is a number or not using one of the inbuilt methods in the lodash _.isNumber() method." }, { "code": null, "e": 39236, "s": 39227, "text": "index.js" }, { "code": null, "e": 39247, "s": 39236, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.isNumber() method console.log(_.isNumber(100)); console.log(_.isNumber('GeeksforGeeks courses')); console.log(_.isNumber(78.43));", "e": 39457, "s": 39247, "text": null }, { "code": null, "e": 39610, "s": 39457, "text": "Step to run the program: Save the above file with index.js and open the terminal and type the following command in order to compile and run the program." }, { "code": null, "e": 39624, "s": 39610, "text": "node index.js" }, { "code": null, "e": 39632, "s": 39624, "text": "Output:" }, { "code": null, "e": 39648, "s": 39632, "text": "true\nfalse\ntrue" }, { "code": null, "e": 39670, "s": 39648, "text": "Advantages of Lodash:" }, { "code": null, "e": 39855, "s": 39670, "text": "It provides us with various inbuilt functions for collections, arrays, to manipulate objects and other utilities methods which we can use directly instead of writing them from scratch." }, { "code": null, "e": 39947, "s": 39855, "text": "It keeps our code more short and clean that makes it easier to understand and modify later." }, { "code": null, "e": 40036, "s": 39947, "text": "We have to remember Lodash functions and that makes out the task of coding much simpler." }, { "code": null, "e": 40086, "s": 40036, "text": "It is easier to start and learn for tech newbies." }, { "code": null, "e": 40181, "s": 40086, "text": "Instead of writing repetitive functions, tasks can be accomplished with a single line of code." }, { "code": null, "e": 40206, "s": 40181, "text": "Disadvantages of Lodash:" }, { "code": null, "e": 40328, "s": 40206, "text": "The firstmost disadvantage of Lodash is speed. Lodash methods take more time to execute than normal JavaScript functions." }, { "code": null, "e": 40454, "s": 40328, "text": "In JavaScript, we can chain many functions together as we want but in Lodash we can’t chain functions, we can only wrap them." }, { "code": null, "e": 40472, "s": 40454, "text": "JavaScript-Lodash" }, { "code": null, "e": 40483, "s": 40472, "text": "JavaScript" }, { "code": null, "e": 40500, "s": 40483, "text": "Web Technologies" }, { "code": null, "e": 40598, "s": 40500, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40607, "s": 40598, "text": "Comments" }, { "code": null, "e": 40620, "s": 40607, "text": "Old Comments" }, { "code": null, "e": 40665, "s": 40620, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40734, "s": 40665, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 40795, "s": 40734, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 40867, "s": 40795, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 40894, "s": 40867, "text": "File uploading in React.js" }, { "code": null, "e": 40936, "s": 40894, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 40969, "s": 40936, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 41031, "s": 40969, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 41081, "s": 41031, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to place an image into a frame in Tkinter?
To place an image into a Tkinter frame, you can follow the steps given below − Import the required libraries and create an instance of tkinter frame. To open an image and place it inside the frame, we will use the Pillow (PIL) library. Import the required libraries and create an instance of tkinter frame. To open an image and place it inside the frame, we will use the Pillow (PIL) library. Set the size of the frame using geometry method. Set the size of the frame using geometry method. Create a frame and specify its height and width. Place the frame at the center of the window using place() method with anchor='center'. Create a frame and specify its height and width. Place the frame at the center of the window using place() method with anchor='center'. Open an image using ImageTk.PhotoImage(Image.open("image")) Open an image using ImageTk.PhotoImage(Image.open("image")) Next, create a label object inside the frame and pass the image inside the label. Next, create a label object inside the frame and pass the image inside the label. Finally, run the mainloop of the application window Finally, run the mainloop of the application window # Import required libraries from tkinter import * from PIL import ImageTk, Image # Create an instance of tkinter window win = Tk() # Define the geometry of the window win.geometry("700x500") frame = Frame(win, width=600, height=400) frame.pack() frame.place(anchor='center', relx=0.5, rely=0.5) # Create an object of tkinter ImageTk img = ImageTk.PhotoImage(Image.open("forest.jpg")) # Create a Label Widget to display the text or Image label = Label(frame, image = img) label.pack() win.mainloop() When we run the above code, it will display the following output −
[ { "code": null, "e": 1141, "s": 1062, "text": "To place an image into a Tkinter frame, you can follow the steps given below −" }, { "code": null, "e": 1298, "s": 1141, "text": "Import the required libraries and create an instance of tkinter frame. To open an image and place it inside the frame, we will use the Pillow (PIL) library." }, { "code": null, "e": 1455, "s": 1298, "text": "Import the required libraries and create an instance of tkinter frame. To open an image and place it inside the frame, we will use the Pillow (PIL) library." }, { "code": null, "e": 1504, "s": 1455, "text": "Set the size of the frame using geometry method." }, { "code": null, "e": 1553, "s": 1504, "text": "Set the size of the frame using geometry method." }, { "code": null, "e": 1689, "s": 1553, "text": "Create a frame and specify its height and width. Place the frame at the center of the window using place() method with anchor='center'." }, { "code": null, "e": 1825, "s": 1689, "text": "Create a frame and specify its height and width. Place the frame at the center of the window using place() method with anchor='center'." }, { "code": null, "e": 1885, "s": 1825, "text": "Open an image using ImageTk.PhotoImage(Image.open(\"image\"))" }, { "code": null, "e": 1945, "s": 1885, "text": "Open an image using ImageTk.PhotoImage(Image.open(\"image\"))" }, { "code": null, "e": 2027, "s": 1945, "text": "Next, create a label object inside the frame and pass the image inside the label." }, { "code": null, "e": 2109, "s": 2027, "text": "Next, create a label object inside the frame and pass the image inside the label." }, { "code": null, "e": 2161, "s": 2109, "text": "Finally, run the mainloop of the application window" }, { "code": null, "e": 2213, "s": 2161, "text": "Finally, run the mainloop of the application window" }, { "code": null, "e": 2718, "s": 2213, "text": "# Import required libraries\nfrom tkinter import *\nfrom PIL import ImageTk, Image\n\n# Create an instance of tkinter window\nwin = Tk()\n\n# Define the geometry of the window\nwin.geometry(\"700x500\")\n\nframe = Frame(win, width=600, height=400)\nframe.pack()\nframe.place(anchor='center', relx=0.5, rely=0.5)\n\n# Create an object of tkinter ImageTk\nimg = ImageTk.PhotoImage(Image.open(\"forest.jpg\"))\n\n# Create a Label Widget to display the text or Image\nlabel = Label(frame, image = img)\nlabel.pack()\n\nwin.mainloop()" }, { "code": null, "e": 2785, "s": 2718, "text": "When we run the above code, it will display the following output −" } ]
Step by step: build a data pipeline with Airflow | by Tony Xu | Towards Data Science
Each time we deploy our new software, we will check the log file twice a day to see whether there is an issue or exception in the following one or two weeks. One colleague asked me is there a way to monitor the errors and send alert automatically if a certain error occurs more than 3 times. I am following the Airflow course now, it’s a perfect use case to build a data pipeline with Airflow to monitor the exceptions. Airflow is an open-source workflow management platform, It started at Airbnb in October 2014 and later was made open-source, becoming an Apache Incubator project in March 2016. Airflow is designed under the principle of “configuration as code”. [1] In Airflow, a DAG — or a Directed Acyclic Graph — is a collection of all the tasks you want to run, organized in a way that reflects their relationships and dependencies.[2] Airflow uses Python language to create its workflow/DAG file, it’s quite convenient and powerful for the developer. Our log files are saved in the server, there are several log files. We can fetch them by the sftp command. After downloading all the log files into one local folder, we can use the grep command to extract all lines containing exceptions or errors. The following is an example of an error log: /usr/local/airflow/data/20200723/loginApp.log:140851:[[]] 23 Jul 2020/13:23:19,196 ERROR SessionId : u0UkvLFDNMsMIcbuOzo86Lq8OcU= [loginApp] dao.AbstractSoapDao - getNotificationStatus - service Exception: java.net.SocketTimeoutException: Read timed out Next, we need to parse the error message line by line and extract the fields. Like the above example, we want to know the file name, line number, date, time, session id, app name, module name, and error message. We will extract all this information into a database table, later on, we can use the SQL query to aggregate the information. If any type of error happens more than 3 times, it will trigger sending an email to the specified mailbox. The whole process is quite straightforward as following: Airflow provides a lot of useful operators. An operator is a single task, which provides a simple way to implement certain functionality. For example, BashOperator can execute a Bash script, command, or set of commands. SFTPOperator can access the server via an SSH session. Furthermore, Airflow allows parallelism amongst tasks, since an operator corresponds to a single task, which means all the operators can run in parallel. Airflow also provides a very simple way to define dependency and concurrency between tasks, we will talk about it later. Normally, Airflow is running in a docker container. Apache publishes Airflow images in Docker Hub. A more popular Airflow image is released by Puckel which is configurated well and ready to use. We can retrieve the docker file and all configuration files from Puckel’s Github repository. After installing Docker client and pulling the Puckel’s repository, run the following command line to start the Airflow server: docker-compose -f ./docker-compose-LocalExecutor.yml up -d When it’s the first time to run the script, it will download Puckel’s Airflow image and Postgres image from Docker Hub, then start two docker containers. Airflow has a nice UI, it can be accessed from http://localhost:8080. From the Airflow UI portal, it can trigger a DAG and show the status of the tasks currently running. Let’s start to create a DAG file. It’s pretty easy to create a new DAG. Firstly, we define some default arguments, then instantiate a DAG class with a DAG name monitor_errors, the DAG name will be shown in Airflow UI. The first step in the workflow is to download all the log files from the server. Airflow supports concurrency of running tasks. We create one downloading task for one log file, all the tasks can be running in parallel, and we add all the tasks into one list. SFTPOperator needs an SSH connection id, we will config it in the Airflow portal before running the workflow. After that, we can refresh the Airflow UI to load our DAG file. Now we can see our new DAG - monitor_errors - appearing on the list: Click the DAG name, it will show the graph view, we can see all the download tasks here: Before we trigger a DAG batch, we need to config the SSH connection, so that SFTPOperator can use this connection. Click the Admin menu then select Connections to create a new SSH connection. To access an SSH server without inputting a password, it needs to use the public key to log in. Assume the public key has already been put into server and the private key is located in /usr/local/airflow/.ssh/id_rsa. Leave Password field empty, and put the following JSON data into the Extra field. { "key_file": "/usr/local/airflow/.ssh/id_rsa", "timeout": "10", "compress": "false", "no_host_key_check": "false", "allow_host_key_change": "false"} Ok, let’s enable the DAG and trigger it, some tasks turn green which means they are in running state, the other tasks are remaining grey since they are in the queue. When all tasks finished, they are shown in dark green. Let’s check the files downloaded into the data/ folder. It will create the folder with the current date. Looks good. Next, we will extract all lines containing “exception” in the log files then write these lines into a file(errors.txt) in the same folder. grep command can search certain text in all the files in one folder and it also can include the file name and line number in the search result. Airflow checks the bash command return value as the task’s running result. grep command will return -1 if no exception is found. Airflow treats non-zero return value as a failure task, however, it’s not. No error means we’re all good. We check the errors.txt file generated by grep. If the file exists, no matter it’s empty or not, we will treat this task as a successful one. Refresh the DAG and trigger it again, the graph view will be updated as above. Let’s check the output file errors.txt in the folder. Next, we will parse the log line by line and extract the fields we are interested in. We use a PythonOperator to do this job using a regular expression. The extracted fields will be saved into a database for later on the queries. Airflow supports any type of database backend, it stores metadata information in the database, in this example, we will use Postgres DB as backend. We define a PostgresOperator to create a new table in the database, it will delete the table if it’s already existed. In a real scenario, we may append data into the database, but we shall be cautious if some tasks need to be rerun due to any reason, it may add duplicated data into the database. To use the Postgres database, we need to config the connection in the Airflow portal. We can modify the existing postgres_default connection, so we don’t need to specify connection id when using PostgresOperator or PostgresHook. Great, let’s trigger the DAG again. The tasks ran successfully, all the log data are parsed and stored in the database. Airflow provides a handy way to query the database. Choose “Ad Hoc Query” under the “Data Profiling” menu then type SQL query statement. Next, we can query the table and count the error of every type, we use another PythonOperator to query the database and generate two report files. One contains all the error records in the database, another is a statistics table to show all types of errors with occurrences in descending order. Ok, trigger the DAG again. Two report files are generated in the folder. In error_logs.csv, it contains all the exception records in the database. In error_stats.csv, it lists different types of errors with occurrences. At last step, we use a branch operator to check the top occurrences in the error list, if it exceeds the threshold, says 3 times, it will trigger to send an email, otherwise, end silently. We can define the threshold value in the Airflow Variables, then read the value from the code. So that we can change the threshold later without modifying the code. BranchPythonOperator returns the next task’s name, either to send an email or do nothing. We use the EmailOperator to send an email, it provides a convenient API to specify to, subject, body fields, and easy to add attachments. And we define an empty task by DummyOperator. To use the email operator, we need to add some configuration parameters in the YAML file. Here we define configurations for a Gmail account. You may put your password here or use App Password for your email client which provides better security. - AIRFLOW__SMTP__SMTP_HOST=smtp.gmail.com- AIRFLOW__SMTP__SMTP_PORT=587- AIRFLOW__SMTP__SMTP_USER=<your-email-id>@gmail.com- AIRFLOW__SMTP__SMTP_PASSWORD=<your-app-password>- AIRFLOW__SMTP__SMTP_MAIL_FROM=<your-email-id>@gmail.com So far, we create all the tasks in the workflow, we need to define the dependency among these tasks. Airflow provides a very intuitive way to describe dependencies. dl_tasks >> grep_exception >> create_table >> parse_log >> gen_reports >> check_threshold >> [send_email, dummy_op] Now, we finish all our coding part, let’s trigger the workflow again to see the whole process. In our case, there are two types of error, both of them exceeds the threshold, it will trigger sending the email at the end. Two reports are attached to the email. We change the threshold variable to 60 and run the workflow again. As you can see, it doesn’t trigger sending the email since the number of errors is less than 60. The workflow ends silently. Let’s go back to the DAG view. It lists all the active or inactive DAGs and the status of each DAG, in our example, you can see, our monitor_errors DAG has 4 successful runs, and in the last run, 15 tasks are successful and 1 task is skipped which is the last dummy_op task, it’s an expected result. Now our DAG is scheduled to run every day, we can change the scheduling time as we want, e.g. every 6 hours or at a specific time every day. Airflow is a powerful ETL tool, it’s been widely used in many tier-1 companies, like Airbnb, Google, Ubisoft, Walmart, etc. And it’s also supported in major cloud platforms, e.g. AWS, GCP, Azure. It plays a more and more important role in data engineering and data processing.
[ { "code": null, "e": 467, "s": 47, "text": "Each time we deploy our new software, we will check the log file twice a day to see whether there is an issue or exception in the following one or two weeks. One colleague asked me is there a way to monitor the errors and send alert automatically if a certain error occurs more than 3 times. I am following the Airflow course now, it’s a perfect use case to build a data pipeline with Airflow to monitor the exceptions." }, { "code": null, "e": 716, "s": 467, "text": "Airflow is an open-source workflow management platform, It started at Airbnb in October 2014 and later was made open-source, becoming an Apache Incubator project in March 2016. Airflow is designed under the principle of “configuration as code”. [1]" }, { "code": null, "e": 890, "s": 716, "text": "In Airflow, a DAG — or a Directed Acyclic Graph — is a collection of all the tasks you want to run, organized in a way that reflects their relationships and dependencies.[2]" }, { "code": null, "e": 1006, "s": 890, "text": "Airflow uses Python language to create its workflow/DAG file, it’s quite convenient and powerful for the developer." }, { "code": null, "e": 1299, "s": 1006, "text": "Our log files are saved in the server, there are several log files. We can fetch them by the sftp command. After downloading all the log files into one local folder, we can use the grep command to extract all lines containing exceptions or errors. The following is an example of an error log:" }, { "code": null, "e": 1553, "s": 1299, "text": "/usr/local/airflow/data/20200723/loginApp.log:140851:[[]] 23 Jul 2020/13:23:19,196 ERROR SessionId : u0UkvLFDNMsMIcbuOzo86Lq8OcU= [loginApp] dao.AbstractSoapDao - getNotificationStatus - service Exception: java.net.SocketTimeoutException: Read timed out" }, { "code": null, "e": 1997, "s": 1553, "text": "Next, we need to parse the error message line by line and extract the fields. Like the above example, we want to know the file name, line number, date, time, session id, app name, module name, and error message. We will extract all this information into a database table, later on, we can use the SQL query to aggregate the information. If any type of error happens more than 3 times, it will trigger sending an email to the specified mailbox." }, { "code": null, "e": 2054, "s": 1997, "text": "The whole process is quite straightforward as following:" }, { "code": null, "e": 2604, "s": 2054, "text": "Airflow provides a lot of useful operators. An operator is a single task, which provides a simple way to implement certain functionality. For example, BashOperator can execute a Bash script, command, or set of commands. SFTPOperator can access the server via an SSH session. Furthermore, Airflow allows parallelism amongst tasks, since an operator corresponds to a single task, which means all the operators can run in parallel. Airflow also provides a very simple way to define dependency and concurrency between tasks, we will talk about it later." }, { "code": null, "e": 2892, "s": 2604, "text": "Normally, Airflow is running in a docker container. Apache publishes Airflow images in Docker Hub. A more popular Airflow image is released by Puckel which is configurated well and ready to use. We can retrieve the docker file and all configuration files from Puckel’s Github repository." }, { "code": null, "e": 3020, "s": 2892, "text": "After installing Docker client and pulling the Puckel’s repository, run the following command line to start the Airflow server:" }, { "code": null, "e": 3079, "s": 3020, "text": "docker-compose -f ./docker-compose-LocalExecutor.yml up -d" }, { "code": null, "e": 3233, "s": 3079, "text": "When it’s the first time to run the script, it will download Puckel’s Airflow image and Postgres image from Docker Hub, then start two docker containers." }, { "code": null, "e": 3303, "s": 3233, "text": "Airflow has a nice UI, it can be accessed from http://localhost:8080." }, { "code": null, "e": 3404, "s": 3303, "text": "From the Airflow UI portal, it can trigger a DAG and show the status of the tasks currently running." }, { "code": null, "e": 3622, "s": 3404, "text": "Let’s start to create a DAG file. It’s pretty easy to create a new DAG. Firstly, we define some default arguments, then instantiate a DAG class with a DAG name monitor_errors, the DAG name will be shown in Airflow UI." }, { "code": null, "e": 3991, "s": 3622, "text": "The first step in the workflow is to download all the log files from the server. Airflow supports concurrency of running tasks. We create one downloading task for one log file, all the tasks can be running in parallel, and we add all the tasks into one list. SFTPOperator needs an SSH connection id, we will config it in the Airflow portal before running the workflow." }, { "code": null, "e": 4124, "s": 3991, "text": "After that, we can refresh the Airflow UI to load our DAG file. Now we can see our new DAG - monitor_errors - appearing on the list:" }, { "code": null, "e": 4213, "s": 4124, "text": "Click the DAG name, it will show the graph view, we can see all the download tasks here:" }, { "code": null, "e": 4405, "s": 4213, "text": "Before we trigger a DAG batch, we need to config the SSH connection, so that SFTPOperator can use this connection. Click the Admin menu then select Connections to create a new SSH connection." }, { "code": null, "e": 4704, "s": 4405, "text": "To access an SSH server without inputting a password, it needs to use the public key to log in. Assume the public key has already been put into server and the private key is located in /usr/local/airflow/.ssh/id_rsa. Leave Password field empty, and put the following JSON data into the Extra field." }, { "code": null, "e": 4859, "s": 4704, "text": "{ \"key_file\": \"/usr/local/airflow/.ssh/id_rsa\", \"timeout\": \"10\", \"compress\": \"false\", \"no_host_key_check\": \"false\", \"allow_host_key_change\": \"false\"}" }, { "code": null, "e": 5025, "s": 4859, "text": "Ok, let’s enable the DAG and trigger it, some tasks turn green which means they are in running state, the other tasks are remaining grey since they are in the queue." }, { "code": null, "e": 5185, "s": 5025, "text": "When all tasks finished, they are shown in dark green. Let’s check the files downloaded into the data/ folder. It will create the folder with the current date." }, { "code": null, "e": 5197, "s": 5185, "text": "Looks good." }, { "code": null, "e": 5480, "s": 5197, "text": "Next, we will extract all lines containing “exception” in the log files then write these lines into a file(errors.txt) in the same folder. grep command can search certain text in all the files in one folder and it also can include the file name and line number in the search result." }, { "code": null, "e": 5857, "s": 5480, "text": "Airflow checks the bash command return value as the task’s running result. grep command will return -1 if no exception is found. Airflow treats non-zero return value as a failure task, however, it’s not. No error means we’re all good. We check the errors.txt file generated by grep. If the file exists, no matter it’s empty or not, we will treat this task as a successful one." }, { "code": null, "e": 5990, "s": 5857, "text": "Refresh the DAG and trigger it again, the graph view will be updated as above. Let’s check the output file errors.txt in the folder." }, { "code": null, "e": 6143, "s": 5990, "text": "Next, we will parse the log line by line and extract the fields we are interested in. We use a PythonOperator to do this job using a regular expression." }, { "code": null, "e": 6368, "s": 6143, "text": "The extracted fields will be saved into a database for later on the queries. Airflow supports any type of database backend, it stores metadata information in the database, in this example, we will use Postgres DB as backend." }, { "code": null, "e": 6665, "s": 6368, "text": "We define a PostgresOperator to create a new table in the database, it will delete the table if it’s already existed. In a real scenario, we may append data into the database, but we shall be cautious if some tasks need to be rerun due to any reason, it may add duplicated data into the database." }, { "code": null, "e": 6894, "s": 6665, "text": "To use the Postgres database, we need to config the connection in the Airflow portal. We can modify the existing postgres_default connection, so we don’t need to specify connection id when using PostgresOperator or PostgresHook." }, { "code": null, "e": 6930, "s": 6894, "text": "Great, let’s trigger the DAG again." }, { "code": null, "e": 7151, "s": 6930, "text": "The tasks ran successfully, all the log data are parsed and stored in the database. Airflow provides a handy way to query the database. Choose “Ad Hoc Query” under the “Data Profiling” menu then type SQL query statement." }, { "code": null, "e": 7446, "s": 7151, "text": "Next, we can query the table and count the error of every type, we use another PythonOperator to query the database and generate two report files. One contains all the error records in the database, another is a statistics table to show all types of errors with occurrences in descending order." }, { "code": null, "e": 7473, "s": 7446, "text": "Ok, trigger the DAG again." }, { "code": null, "e": 7519, "s": 7473, "text": "Two report files are generated in the folder." }, { "code": null, "e": 7593, "s": 7519, "text": "In error_logs.csv, it contains all the exception records in the database." }, { "code": null, "e": 7666, "s": 7593, "text": "In error_stats.csv, it lists different types of errors with occurrences." }, { "code": null, "e": 8020, "s": 7666, "text": "At last step, we use a branch operator to check the top occurrences in the error list, if it exceeds the threshold, says 3 times, it will trigger to send an email, otherwise, end silently. We can define the threshold value in the Airflow Variables, then read the value from the code. So that we can change the threshold later without modifying the code." }, { "code": null, "e": 8294, "s": 8020, "text": "BranchPythonOperator returns the next task’s name, either to send an email or do nothing. We use the EmailOperator to send an email, it provides a convenient API to specify to, subject, body fields, and easy to add attachments. And we define an empty task by DummyOperator." }, { "code": null, "e": 8540, "s": 8294, "text": "To use the email operator, we need to add some configuration parameters in the YAML file. Here we define configurations for a Gmail account. You may put your password here or use App Password for your email client which provides better security." }, { "code": null, "e": 8771, "s": 8540, "text": "- AIRFLOW__SMTP__SMTP_HOST=smtp.gmail.com- AIRFLOW__SMTP__SMTP_PORT=587- AIRFLOW__SMTP__SMTP_USER=<your-email-id>@gmail.com- AIRFLOW__SMTP__SMTP_PASSWORD=<your-app-password>- AIRFLOW__SMTP__SMTP_MAIL_FROM=<your-email-id>@gmail.com" }, { "code": null, "e": 8936, "s": 8771, "text": "So far, we create all the tasks in the workflow, we need to define the dependency among these tasks. Airflow provides a very intuitive way to describe dependencies." }, { "code": null, "e": 9052, "s": 8936, "text": "dl_tasks >> grep_exception >> create_table >> parse_log >> gen_reports >> check_threshold >> [send_email, dummy_op]" }, { "code": null, "e": 9147, "s": 9052, "text": "Now, we finish all our coding part, let’s trigger the workflow again to see the whole process." }, { "code": null, "e": 9311, "s": 9147, "text": "In our case, there are two types of error, both of them exceeds the threshold, it will trigger sending the email at the end. Two reports are attached to the email." }, { "code": null, "e": 9378, "s": 9311, "text": "We change the threshold variable to 60 and run the workflow again." }, { "code": null, "e": 9503, "s": 9378, "text": "As you can see, it doesn’t trigger sending the email since the number of errors is less than 60. The workflow ends silently." }, { "code": null, "e": 9534, "s": 9503, "text": "Let’s go back to the DAG view." }, { "code": null, "e": 9803, "s": 9534, "text": "It lists all the active or inactive DAGs and the status of each DAG, in our example, you can see, our monitor_errors DAG has 4 successful runs, and in the last run, 15 tasks are successful and 1 task is skipped which is the last dummy_op task, it’s an expected result." }, { "code": null, "e": 9944, "s": 9803, "text": "Now our DAG is scheduled to run every day, we can change the scheduling time as we want, e.g. every 6 hours or at a specific time every day." } ]
Android | How to send data from one activity to second activity - GeeksforGeeks
06 Nov, 2021 Pre-requisites: Android App Development Fundamentals for Beginners Guide to Install and Set up Android Studio Android | Starting with first app/android project Android | Running your first Android app This article aims to tell and show about how to “Send the data from one activity to second activity using Intent”. In this Example, we have two activities, activity_first which is the source activity and activity_second which is the destination activity. We can send the data using putExtra() method from one activity and get the data from the second activity using getStringExtra() methods. Example: In this Example, one EditText is used to input the text. This text is sent to the second activity when the “Send” button is clicked. For this, Intent will start and the following methods will run: putExtra() method is used for send the data, data in key value pair key is variable name and value can be Int, String, Float etc. getStringExtra() method is for getting the data(key) which is send by above method. according the data type of value there are other methods like getIntExtra(), getFloatExtra() Step 1: Firstly create a new Android Application. This will create an XML file and a Java File. Please refer the pre-requisites to learn more about this step. Step 2: Open “activity_first_activity.xml” file and add the following widgets in a Relative Layout: A EditText to Input the message A Button to send the data Also, Assign the ID to each component along with other attributes as shown in the image and the code below. The assigned ID on a component helps that component to be easily found and used in the Java files. Syntax: android:id="@+id/id_name" Here the given IDs are as follows: Send Button: send_button_id input EditText: send_text_id This will make the UI of the Application. Step 3: Now, after the UI, this step will create the Backend of the App. For this, open the “first_activity.java” file and instantiate the components made in the XML file (EditText, send Button) using findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID. General Syntax: ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent); Syntax for components used: Button send_button= (Button)findViewById(R.id.send_button_id); send_text = (EditText) findViewById(R.id.send_text_id); Step 4: This step involves setting up the operations on the sending and received the data. These operations are as follows: 1. first Add the listener on the send button and this button will send the data. This is done as follows: send_button.setOnClickListener(new View.OnClickListener() {} after clicked this button following operation will be performed. 2. Now create the String type variable for store the value of EditText which is input by user. Get the value and convert it to string. This is done as follows: String str = send_text.getText().toString(); 3. Now create the Intent object First_activity.java class to Second_activity class. This is done as follows: Intent intent = new Intent(getApplicationContext(), Second_activity.class); where getApplicationContext() will fetch the current activity. 4. Put the value in putExtra method in key value pair then start the activity. This is done as follows: intent.putExtra(“message_key”, str); startActivity(intent); where “str” is the string value and the key is “message_key” this key will use to get the str value Step 5: Now we have to create a Second_Activity to receive the data. The steps to create the second activity is as follows: android project > File > new > Activity > Empty Activity Step 6: Now open your second xml file. Add TextView for display the receive messages. assign ID to Textview. Second Activity is shown below: Step 7: Now, open up your second activity java file and perform the following operation. 1. Define the TextView variable, use findViewById() to get the TextView as shown above. receiver_msg = (TextView) findViewById(R.id.received_value_id); 2. Now In second_activity.java file create the object of getTntent to receive the value in String type variable by getStringExtra method using message_key. Intent intent = getIntent(); String str = intent.getStringExtra(“message_key”); 3. The received value set in the TextView object of the second activity xml file receiver_msg.setText(str); Step 8: Now Run the app and operate as follows: When the app is opened, it displays a “Input” EditText. Enter the value for the send. click the send button then message will display on second screen. Below is the complete code for the Application. Filename: activity_first_activity.xml XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".first_activity"> <EditText android:id="@+id/send_text_id" android:layout_width="300dp" android:layout_height="wrap_content" android:textSize="25dp" android:hint="Input" android:textStyle="bold" android:layout_marginTop="20dp" android:layout_marginLeft="40dp"/> <Button android:id="@+id/send_button_id" android:layout_width="wrap_content" android:layout_height="40dp" android:text="send" android:textStyle="bold" android:layout_marginTop="150dp" android:layout_marginLeft="150dp"/> </RelativeLayout> Filename: First_Activity.java Java package org.geeksforgeeks.navedmalik.sendthedata; import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText; public class first_activity extends AppCompatActivity { // define the variable Button send_button; EditText send_text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first_activity); send_button = (Button)findViewById(R.id.send_button_id); send_text = (EditText)findViewById(R.id.send_text_id); // add the OnClickListener in sender button // after clicked this button following Instruction will run send_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // get the value which input by user in EditText // and convert it to string String str = send_text.getText().toString(); // Create the Intent object of this class Context() to Second_activity class Intent intent = new Intent(getApplicationContext(), Second_activity.class); // now by putExtra method put the value in key, value pair // key is message_key by this key we will receive the value, and put the string intent.putExtra("message_key", str); // start the Intent startActivity(intent); } }); }} Filename: activity_second_activity.xml XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="org.geeksforgeeks.navedmalik.sendthedata.Second_activity"> <TextView android:id="@+id/received_value_id" android:layout_width="300dp" android:layout_height="50dp" android:textStyle="bold" android:textSize="40dp" android:layout_marginTop="20dp" android:layout_marginLeft="40dp"/> </RelativeLayout> Filename: Second_Activity.java Java package org.geeksforgeeks.navedmalik.sendthedata; import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.TextView; public class Second_activity extends AppCompatActivity { TextView receiver_msg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second_activity); receiver_msg = (TextView)findViewById(R.id.received_value_id); // create the get Intent object Intent intent = getIntent(); // receive the value by getStringExtra() method // and key must be same which is send by first activity String str = intent.getStringExtra("message_key"); // display the string into textView receiver_msg.setText(str); }} Output: ManasChhabra2 kapoorsagar226 android 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 Stream In Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 25839, "s": 25811, "text": "\n06 Nov, 2021" }, { "code": null, "e": 25856, "s": 25839, "text": "Pre-requisites: " }, { "code": null, "e": 25907, "s": 25856, "text": "Android App Development Fundamentals for Beginners" }, { "code": null, "e": 25950, "s": 25907, "text": "Guide to Install and Set up Android Studio" }, { "code": null, "e": 26000, "s": 25950, "text": "Android | Starting with first app/android project" }, { "code": null, "e": 26041, "s": 26000, "text": "Android | Running your first Android app" }, { "code": null, "e": 26433, "s": 26041, "text": "This article aims to tell and show about how to “Send the data from one activity to second activity using Intent”. In this Example, we have two activities, activity_first which is the source activity and activity_second which is the destination activity. We can send the data using putExtra() method from one activity and get the data from the second activity using getStringExtra() methods." }, { "code": null, "e": 26442, "s": 26433, "text": "Example:" }, { "code": null, "e": 26639, "s": 26442, "text": "In this Example, one EditText is used to input the text. This text is sent to the second activity when the “Send” button is clicked. For this, Intent will start and the following methods will run:" }, { "code": null, "e": 26769, "s": 26639, "text": "putExtra() method is used for send the data, data in key value pair key is variable name and value can be Int, String, Float etc." }, { "code": null, "e": 26946, "s": 26769, "text": "getStringExtra() method is for getting the data(key) which is send by above method. according the data type of value there are other methods like getIntExtra(), getFloatExtra()" }, { "code": null, "e": 27105, "s": 26946, "text": "Step 1: Firstly create a new Android Application. This will create an XML file and a Java File. Please refer the pre-requisites to learn more about this step." }, { "code": null, "e": 27206, "s": 27105, "text": "Step 2: Open “activity_first_activity.xml” file and add the following widgets in a Relative Layout: " }, { "code": null, "e": 27238, "s": 27206, "text": "A EditText to Input the message" }, { "code": null, "e": 27264, "s": 27238, "text": "A Button to send the data" }, { "code": null, "e": 27471, "s": 27264, "text": "Also, Assign the ID to each component along with other attributes as shown in the image and the code below. The assigned ID on a component helps that component to be easily found and used in the Java files." }, { "code": null, "e": 27479, "s": 27471, "text": "Syntax:" }, { "code": null, "e": 27505, "s": 27479, "text": "android:id=\"@+id/id_name\"" }, { "code": null, "e": 27540, "s": 27505, "text": "Here the given IDs are as follows:" }, { "code": null, "e": 27568, "s": 27540, "text": "Send Button: send_button_id" }, { "code": null, "e": 27597, "s": 27568, "text": "input EditText: send_text_id" }, { "code": null, "e": 27639, "s": 27597, "text": "This will make the UI of the Application." }, { "code": null, "e": 27956, "s": 27639, "text": "Step 3: Now, after the UI, this step will create the Backend of the App. For this, open the “first_activity.java” file and instantiate the components made in the XML file (EditText, send Button) using findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID. " }, { "code": null, "e": 27973, "s": 27956, "text": "General Syntax: " }, { "code": null, "e": 28048, "s": 27973, "text": "ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);" }, { "code": null, "e": 28077, "s": 28048, "text": "Syntax for components used: " }, { "code": null, "e": 28198, "s": 28077, "text": "Button send_button= (Button)findViewById(R.id.send_button_id); send_text = (EditText) findViewById(R.id.send_text_id); " }, { "code": null, "e": 28323, "s": 28198, "text": "Step 4: This step involves setting up the operations on the sending and received the data. These operations are as follows: " }, { "code": null, "e": 28430, "s": 28323, "text": "1. first Add the listener on the send button and this button will send the data. This is done as follows: " }, { "code": null, "e": 28492, "s": 28430, "text": "send_button.setOnClickListener(new View.OnClickListener() {} " }, { "code": null, "e": 28558, "s": 28492, "text": "after clicked this button following operation will be performed. " }, { "code": null, "e": 28719, "s": 28558, "text": "2. Now create the String type variable for store the value of EditText which is input by user. Get the value and convert it to string. This is done as follows: " }, { "code": null, "e": 28764, "s": 28719, "text": "String str = send_text.getText().toString();" }, { "code": null, "e": 28874, "s": 28764, "text": "3. Now create the Intent object First_activity.java class to Second_activity class. This is done as follows: " }, { "code": null, "e": 28950, "s": 28874, "text": "Intent intent = new Intent(getApplicationContext(), Second_activity.class);" }, { "code": null, "e": 29013, "s": 28950, "text": "where getApplicationContext() will fetch the current activity." }, { "code": null, "e": 29118, "s": 29013, "text": "4. Put the value in putExtra method in key value pair then start the activity. This is done as follows: " }, { "code": null, "e": 29178, "s": 29118, "text": "intent.putExtra(“message_key”, str); startActivity(intent);" }, { "code": null, "e": 29279, "s": 29178, "text": "where “str” is the string value and the key is “message_key” this key will use to get the str value " }, { "code": null, "e": 29404, "s": 29279, "text": "Step 5: Now we have to create a Second_Activity to receive the data. The steps to create the second activity is as follows: " }, { "code": null, "e": 29461, "s": 29404, "text": "android project > File > new > Activity > Empty Activity" }, { "code": null, "e": 29602, "s": 29461, "text": "Step 6: Now open your second xml file. Add TextView for display the receive messages. assign ID to Textview. Second Activity is shown below:" }, { "code": null, "e": 29692, "s": 29602, "text": "Step 7: Now, open up your second activity java file and perform the following operation. " }, { "code": null, "e": 29781, "s": 29692, "text": "1. Define the TextView variable, use findViewById() to get the TextView as shown above. " }, { "code": null, "e": 29846, "s": 29781, "text": "receiver_msg = (TextView) findViewById(R.id.received_value_id); " }, { "code": null, "e": 30003, "s": 29846, "text": "2. Now In second_activity.java file create the object of getTntent to receive the value in String type variable by getStringExtra method using message_key. " }, { "code": null, "e": 30083, "s": 30003, "text": "Intent intent = getIntent(); String str = intent.getStringExtra(“message_key”);" }, { "code": null, "e": 30166, "s": 30083, "text": " 3. The received value set in the TextView object of the second activity xml file " }, { "code": null, "e": 30194, "s": 30166, "text": "receiver_msg.setText(str); " }, { "code": null, "e": 30243, "s": 30194, "text": "Step 8: Now Run the app and operate as follows: " }, { "code": null, "e": 30329, "s": 30243, "text": "When the app is opened, it displays a “Input” EditText. Enter the value for the send." }, { "code": null, "e": 30395, "s": 30329, "text": "click the send button then message will display on second screen." }, { "code": null, "e": 30443, "s": 30395, "text": "Below is the complete code for the Application." }, { "code": null, "e": 30481, "s": 30443, "text": "Filename: activity_first_activity.xml" }, { "code": null, "e": 30485, "s": 30481, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".first_activity\"> <EditText android:id=\"@+id/send_text_id\" android:layout_width=\"300dp\" android:layout_height=\"wrap_content\" android:textSize=\"25dp\" android:hint=\"Input\" android:textStyle=\"bold\" android:layout_marginTop=\"20dp\" android:layout_marginLeft=\"40dp\"/> <Button android:id=\"@+id/send_button_id\" android:layout_width=\"wrap_content\" android:layout_height=\"40dp\" android:text=\"send\" android:textStyle=\"bold\" android:layout_marginTop=\"150dp\" android:layout_marginLeft=\"150dp\"/> </RelativeLayout>", "e": 31415, "s": 30485, "text": null }, { "code": null, "e": 31445, "s": 31415, "text": "Filename: First_Activity.java" }, { "code": null, "e": 31450, "s": 31445, "text": "Java" }, { "code": "package org.geeksforgeeks.navedmalik.sendthedata; import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText; public class first_activity extends AppCompatActivity { // define the variable Button send_button; EditText send_text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first_activity); send_button = (Button)findViewById(R.id.send_button_id); send_text = (EditText)findViewById(R.id.send_text_id); // add the OnClickListener in sender button // after clicked this button following Instruction will run send_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // get the value which input by user in EditText // and convert it to string String str = send_text.getText().toString(); // Create the Intent object of this class Context() to Second_activity class Intent intent = new Intent(getApplicationContext(), Second_activity.class); // now by putExtra method put the value in key, value pair // key is message_key by this key we will receive the value, and put the string intent.putExtra(\"message_key\", str); // start the Intent startActivity(intent); } }); }}", "e": 33054, "s": 31450, "text": null }, { "code": null, "e": 33093, "s": 33054, "text": "Filename: activity_second_activity.xml" }, { "code": null, "e": 33097, "s": 33093, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"org.geeksforgeeks.navedmalik.sendthedata.Second_activity\"> <TextView android:id=\"@+id/received_value_id\" android:layout_width=\"300dp\" android:layout_height=\"50dp\" android:textStyle=\"bold\" android:textSize=\"40dp\" android:layout_marginTop=\"20dp\" android:layout_marginLeft=\"40dp\"/> </RelativeLayout>", "e": 33762, "s": 33097, "text": null }, { "code": null, "e": 33793, "s": 33762, "text": "Filename: Second_Activity.java" }, { "code": null, "e": 33798, "s": 33793, "text": "Java" }, { "code": "package org.geeksforgeeks.navedmalik.sendthedata; import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.TextView; public class Second_activity extends AppCompatActivity { TextView receiver_msg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second_activity); receiver_msg = (TextView)findViewById(R.id.received_value_id); // create the get Intent object Intent intent = getIntent(); // receive the value by getStringExtra() method // and key must be same which is send by first activity String str = intent.getStringExtra(\"message_key\"); // display the string into textView receiver_msg.setText(str); }}", "e": 34648, "s": 33798, "text": null }, { "code": null, "e": 34656, "s": 34648, "text": "Output:" }, { "code": null, "e": 34672, "s": 34658, "text": "ManasChhabra2" }, { "code": null, "e": 34687, "s": 34672, "text": "kapoorsagar226" }, { "code": null, "e": 34695, "s": 34687, "text": "android" }, { "code": null, "e": 34700, "s": 34695, "text": "Java" }, { "code": null, "e": 34705, "s": 34700, "text": "Java" }, { "code": null, "e": 34803, "s": 34705, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34854, "s": 34803, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 34869, "s": 34854, "text": "Stream In Java" }, { "code": null, "e": 34899, "s": 34869, "text": "HashMap in Java with Examples" }, { "code": null, "e": 34918, "s": 34899, "text": "Interfaces in Java" }, { "code": null, "e": 34949, "s": 34918, "text": "How to iterate any Map in Java" }, { "code": null, "e": 34981, "s": 34949, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 34999, "s": 34981, "text": "ArrayList in Java" }, { "code": null, "e": 35019, "s": 34999, "text": "Stack Class in Java" }, { "code": null, "e": 35043, "s": 35019, "text": "Singleton Class in Java" } ]
HTML | <spacer> tag - GeeksforGeeks
27 Aug, 2019 The HTML <spacer> tag is used to create some white-space. This tag is history in HTML5, there is no more support in HTML5 also this tag does not support by any major browsers.Syntax: <spacer type="" size=""> Attribute: type: This attribute holds the value for the type of space horizontal, vertical or block. size: This attribute holds a number of pixels for the horizontal or vertical type of spacer. height: This attribute holds the pixel number for block type spacer. width: This attribute holds the pixel number for block type spacer. align: This attribute holds the alignment of the block of white-space. Below example illustrate the HTML <spacer> tag:Example: <!DOCTYPE html><html> <head> <title>HTML <spacer> Tag</title> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2>HTML <spacer> tag</h2> <p>A Computer Science Portal <spacer type="block" width="50" /> for Geeks</p> </center></body> </html> Output: Supported Browsers: The <spacer> tag does not supported by major browsers: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Tags HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HTML Cheat Sheet - A Basic Guide to HTML REST API (Introduction) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) Remove elements from a JavaScript Array 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 Differences between Functional Components and Class Components in React
[ { "code": null, "e": 26275, "s": 26247, "text": "\n27 Aug, 2019" }, { "code": null, "e": 26458, "s": 26275, "text": "The HTML <spacer> tag is used to create some white-space. This tag is history in HTML5, there is no more support in HTML5 also this tag does not support by any major browsers.Syntax:" }, { "code": null, "e": 26483, "s": 26458, "text": "<spacer type=\"\" size=\"\">" }, { "code": null, "e": 26494, "s": 26483, "text": "Attribute:" }, { "code": null, "e": 26584, "s": 26494, "text": "type: This attribute holds the value for the type of space horizontal, vertical or block." }, { "code": null, "e": 26677, "s": 26584, "text": "size: This attribute holds a number of pixels for the horizontal or vertical type of spacer." }, { "code": null, "e": 26746, "s": 26677, "text": "height: This attribute holds the pixel number for block type spacer." }, { "code": null, "e": 26814, "s": 26746, "text": "width: This attribute holds the pixel number for block type spacer." }, { "code": null, "e": 26885, "s": 26814, "text": "align: This attribute holds the alignment of the block of white-space." }, { "code": null, "e": 26941, "s": 26885, "text": "Below example illustrate the HTML <spacer> tag:Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML <spacer> Tag</title> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2>HTML <spacer> tag</h2> <p>A Computer Science Portal <spacer type=\"block\" width=\"50\" /> for Geeks</p> </center></body> </html>", "e": 27294, "s": 26941, "text": null }, { "code": null, "e": 27302, "s": 27294, "text": "Output:" }, { "code": null, "e": 27377, "s": 27302, "text": "Supported Browsers: The <spacer> tag does not supported by major browsers:" }, { "code": null, "e": 27514, "s": 27377, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27524, "s": 27514, "text": "HTML-Tags" }, { "code": null, "e": 27529, "s": 27524, "text": "HTML" }, { "code": null, "e": 27546, "s": 27529, "text": "Web Technologies" }, { "code": null, "e": 27551, "s": 27546, "text": "HTML" }, { "code": null, "e": 27649, "s": 27551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27690, "s": 27649, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 27714, "s": 27690, "text": "REST API (Introduction)" }, { "code": null, "e": 27764, "s": 27714, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27814, "s": 27764, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 27851, "s": 27814, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27891, "s": 27851, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27936, "s": 27891, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27979, "s": 27936, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28040, "s": 27979, "text": "Difference between var, let and const keywords in JavaScript" } ]
Advances in few-shot learning: reproducing results in PyTorch | by Oscar Knagg | Towards Data Science
Few-shot learning is an exciting field of machine learning which aims to close the gap between machine and human in the challenging task of learning from few examples. In my previous post I provided a high level summary of three cutting edge papers in few-shot learning — I assume you’ve either read that, are already familiar with these papers or are in the process of reproducing them yourself. In this post I will guide you through my experience in reproducing the results of these papers on the Omniglot and miniImageNet datasets, including some of the pitfalls and stumbling blocks on the way. Each paper has its own section in which I provide a Github gist with PyTorch code to perform a single parameter update on the model described by the paper. To train the model just have to put that function inside a loop over the training data. Less interesting details such as dataset handling are omitted for brevity. Reproducibility is very important, it is the foundation of any field that claims to be scientific. This makes me believe that the prevalence of code-sharing and open-sourcing in machine learning is truly admirable. While publishing code alone is not reproducibility (as there may be implementation errors) it opens up researchers methods to public scrutiny and more importantly accelerates the research of others in the field. In light of this I’d like to thank the authors of these papers for sharing their code as well as any others who’ve open-sourced their implementations. For the full implementation please see my Github repo at https://github.com/oscarknagg/few-shot There are two image datasets on which few-shot learning algorithms are evaluated. The first is the Omniglot dataset, which contains 20 images each of roughly 1600 characters from 50 alphabets. These images are typically 28x28 grayscale which is one reason why this dataset is often called the transpose of MNIST. The second is the miniImageNet dataset, a subset of ImageNet intended to be a more challenging benchmark without being as cumbersome as the full ImageNet dataset. miniImageNet consists of 60,000, 84x84 RGB images with 600 images per class. In both cases the classes in the training and validation sets are disjoint. I did not use the same training and validation splits as the original papers as my goal is not to reproduce them down to their last minute detail. In Matching Networks Vinyals et al introduce the idea of a fully differentiable nearest neighbours classifier that is both trained and tested on few-shot tasks. The Matching Networks algorithm can be summarised as follows: First embed all samples (query and support set) using an encoder network (4 layer CNN in this case). This is performed by model.encode() (line 41).Optionally calculate full context embeddings (FCE). An LSTM takes the original embeddings as inputs and outputs modified embeddings, taking into account the support set. This is performed by model.f() and model.g() (lines 62 and 67).Calculate pairwise distances between query samples and support sets and normalise using softmax (lines 69 to 77)Calculate predictions by taking the weighted average of the support set labels with the normalised distance (lines 83–89) First embed all samples (query and support set) using an encoder network (4 layer CNN in this case). This is performed by model.encode() (line 41). Optionally calculate full context embeddings (FCE). An LSTM takes the original embeddings as inputs and outputs modified embeddings, taking into account the support set. This is performed by model.f() and model.g() (lines 62 and 67). Calculate pairwise distances between query samples and support sets and normalise using softmax (lines 69 to 77) Calculate predictions by taking the weighted average of the support set labels with the normalised distance (lines 83–89) Some things to note: In this example the x Tensor contains first the support set samples and then the query. For Omniglot it will have shape (n_support + n_query, 1, 28, 28) The math in the previous post is for one query sample but Matching Networks are in fact trained with a batch of query samples of size q_queries * k_way I was unable to reproduce the results of this paper using cosine distance but was successful when using l2 distance. I believe this is because cosine distance is bounded between -1 and 1 which then limits the amount that the attention function (a(x^, x_i) below) can point to a particular sample in the support set. Since cosine distance is bounded a(x^, x_i) will never be close to 1! In the case of 5-way classification the maximum possible value of a(x^, x_i) is exp(1)/ (exp(1) + 4*exp(-1)) ≈ 0.65. This led to very slow convergence when using cosine distance. I think it’s possible to reproduce the results using cosine distance with either longer training times, better hyperparameters or a heuristic like multiplying the cosine distance by a constant factor. Seeing as the choice of distance is not key to the paper and results are very good using l2 distance I decided to spare myself that debugging effort. In Prototypical Networks Snell et al use a compelling inductive bias motivated by the theory of Bregman divergences to achieve impressive few-shot performance. The Prototypical Network algorithm can be summarised as follows: Embed all query and support samples (line 36)Calculate class prototypes taking the mean of the embeddings of each class (line 48)Predictions are a softmax over the distances between the query samples and the class prototypes (line 63) Embed all query and support samples (line 36) Calculate class prototypes taking the mean of the embeddings of each class (line 48) Predictions are a softmax over the distances between the query samples and the class prototypes (line 63) I found this paper delightfully easy to reproduce as the authors provided the full set of hyperparameters. Hence I was easily able to achieve the stated performance to within ~0.2% on the Omniglot benchmark and within a few % on the miniImageNet benchmark without having to perform any tuning of my own. In MAML Finn et al introduce a powerful and broadly applicable meta-learning algorithm to learn a network initialisation that can quickly adapt to new tasks. This paper was the most difficult yet most rewarding to reproduce of the three in this article. The MAML algorithm can be summarised as follows: For each n-shot task in a meta-batch of tasks, create a new model using the weights of the base model AKA meta-learner (line 79)Update the weights of the new model using the loss from the samples in the task by stochastic gradient descent (lines 81–92)Calculate loss of the updated model on some more data from the same task (lines 94–97)If performing 1st order MAML update the meta-learner weights with the gradient of the loss from part 3. If performing 2nd order MAML calculate the derivative of this loss with respect to the original weights (lines 110+) For each n-shot task in a meta-batch of tasks, create a new model using the weights of the base model AKA meta-learner (line 79) Update the weights of the new model using the loss from the samples in the task by stochastic gradient descent (lines 81–92) Calculate loss of the updated model on some more data from the same task (lines 94–97) If performing 1st order MAML update the meta-learner weights with the gradient of the loss from part 3. If performing 2nd order MAML calculate the derivative of this loss with respect to the original weights (lines 110+) The biggest appeal of PyTorch is its autograd system. This is a piece of code-magic that records operations acting on torch.Tensor objects and dynamically builds the directed acyclic graph of these operations under the hood. Backpropagation is as simple as calling .backwards() on the final result. I had to learn a bit more about this system in order to calculate and apply parameter updates to the meta-learner, which I will now share with you. Typically when training a model in PyTorch you create an Optimizer object tied to the parameters of a particular model. from torch.optim import Adamopt = Adam(model.parameters(), lr=0.001) When opt.step() is called the optimiser reads the gradients on the model parameters and calculates an update to those parameters. However in 1st order MAML we’ re going to calculate the gradients using one model (the fast weights) and apply the update to a different model i.e. the meta-learner. A solution to this is to use an under-utilised bit of PyTorch functionality in the form of torch.Tensor.register_hook(hook). Register a hook function to a Tensor and this hook function will be called whenever a gradient with respect to this tensor is computed. For each parameter Tensor in the meta-learner I register a hook that simply replaces the gradient with the corresponding gradient on the fast weights (lines 111–129 in gist). This means that when opt.step() is called the gradients of the fast model will be used to update the meta-learner weights as desired. When making my first attempt at implementing MAML I instantiated a new model object (subclass of torch.nn.Module) and set the values of its weights equal to the meta-learner’s weights. However this makes it impossible to perform 2nd order MAML as the weights of the fast model are disconnected from the weights of the meta-learner in the eyes of torch.autograd. What this means is when I call optimiser.step() (line 140 in the gist) the autograd graph for the meta-learner weights is empty and no update is performed. # This didn't work, meta_learner weights remain unchangedmeta_learner = ModelClass()opt = Adam(meta_learner.parameters(), lr=0.001)task_losses = []for x, y in meta_batch: fast_model = ModelClass() # torch.autograd loses reference here! copy_weights(from=meta_learner, to=fast_model) task_losses.append(update_with_batch(x, y))meta_batch_loss = torch.stack(task_losses).mean()meta_batch_loss.backward()opt.step() The solution to this is functional_forward() (line 17) which is a slightly awkward hack that manually performs the same operations (convolution, max pooling, etc...) as the model class using torch.nn.functional. This also means that I have to manually perform a parameter update of the fast model. The consequence of this is that torch.autograd knows to backpropagate gradients to the original weights of the meta-learner. This leads to a spectacularly large autograd graph. However 2nd order MAML is a trickier beast than just that. When I first wrote my 2nd order MAML implementation I thought I had got everything to work miraculously on the first try. At least there were no exceptions right? Only after running a full set of Omniglot and miniImageNet experiments did I begin to doubt my work — the results were just too similar to 1st order MAML. This is typical of an unfortunate breed of silent ML bugs which don’t cause exceptions but only become visible in the final performance of a model. Hence I decided to buckle down and write a unit test that would confirm that I was truly performing a 2nd order update. Disclaimer: in the spirit of true test-driven development I should’ve written this test before running any experiments. It turns out I’m not perfect 😛. The test I decided on was to run the meta_gradient_step function on a dummy model and manually parse the autograd graph, counting the number of double backwards operations. This way I can be absolutely sure that I am performing a 2nd order update when desired. Conversely, I was able to test that my 1st order MAML implementation only performs a 1st order update with no double backwards operations. I finally located the bug to not applying the create_graph parameter in the inner training loop (line 86). I was, however, retaining the autograd graph of the loss on the query samples (line 97) but this was insufficient to perform a 2nd order update as the unrolled training graph was not created. Training time was quite long (over 24 hours for the 5-way, 5-shot miniImageNet experiment) but in the end I had fairly good success reproducing results. I hope that you’ve learnt something useful from this technical deep dive. If you have any questions feel free to let me know in the comments. If you want to dig in further check out the full implementation at https://github.com/oscarknagg/few-shot
[ { "code": null, "e": 569, "s": 172, "text": "Few-shot learning is an exciting field of machine learning which aims to close the gap between machine and human in the challenging task of learning from few examples. In my previous post I provided a high level summary of three cutting edge papers in few-shot learning — I assume you’ve either read that, are already familiar with these papers or are in the process of reproducing them yourself." }, { "code": null, "e": 1090, "s": 569, "text": "In this post I will guide you through my experience in reproducing the results of these papers on the Omniglot and miniImageNet datasets, including some of the pitfalls and stumbling blocks on the way. Each paper has its own section in which I provide a Github gist with PyTorch code to perform a single parameter update on the model described by the paper. To train the model just have to put that function inside a loop over the training data. Less interesting details such as dataset handling are omitted for brevity." }, { "code": null, "e": 1668, "s": 1090, "text": "Reproducibility is very important, it is the foundation of any field that claims to be scientific. This makes me believe that the prevalence of code-sharing and open-sourcing in machine learning is truly admirable. While publishing code alone is not reproducibility (as there may be implementation errors) it opens up researchers methods to public scrutiny and more importantly accelerates the research of others in the field. In light of this I’d like to thank the authors of these papers for sharing their code as well as any others who’ve open-sourced their implementations." }, { "code": null, "e": 1764, "s": 1668, "text": "For the full implementation please see my Github repo at https://github.com/oscarknagg/few-shot" }, { "code": null, "e": 2077, "s": 1764, "text": "There are two image datasets on which few-shot learning algorithms are evaluated. The first is the Omniglot dataset, which contains 20 images each of roughly 1600 characters from 50 alphabets. These images are typically 28x28 grayscale which is one reason why this dataset is often called the transpose of MNIST." }, { "code": null, "e": 2317, "s": 2077, "text": "The second is the miniImageNet dataset, a subset of ImageNet intended to be a more challenging benchmark without being as cumbersome as the full ImageNet dataset. miniImageNet consists of 60,000, 84x84 RGB images with 600 images per class." }, { "code": null, "e": 2540, "s": 2317, "text": "In both cases the classes in the training and validation sets are disjoint. I did not use the same training and validation splits as the original papers as my goal is not to reproduce them down to their last minute detail." }, { "code": null, "e": 2701, "s": 2540, "text": "In Matching Networks Vinyals et al introduce the idea of a fully differentiable nearest neighbours classifier that is both trained and tested on few-shot tasks." }, { "code": null, "e": 2763, "s": 2701, "text": "The Matching Networks algorithm can be summarised as follows:" }, { "code": null, "e": 3377, "s": 2763, "text": "First embed all samples (query and support set) using an encoder network (4 layer CNN in this case). This is performed by model.encode() (line 41).Optionally calculate full context embeddings (FCE). An LSTM takes the original embeddings as inputs and outputs modified embeddings, taking into account the support set. This is performed by model.f() and model.g() (lines 62 and 67).Calculate pairwise distances between query samples and support sets and normalise using softmax (lines 69 to 77)Calculate predictions by taking the weighted average of the support set labels with the normalised distance (lines 83–89)" }, { "code": null, "e": 3525, "s": 3377, "text": "First embed all samples (query and support set) using an encoder network (4 layer CNN in this case). This is performed by model.encode() (line 41)." }, { "code": null, "e": 3759, "s": 3525, "text": "Optionally calculate full context embeddings (FCE). An LSTM takes the original embeddings as inputs and outputs modified embeddings, taking into account the support set. This is performed by model.f() and model.g() (lines 62 and 67)." }, { "code": null, "e": 3872, "s": 3759, "text": "Calculate pairwise distances between query samples and support sets and normalise using softmax (lines 69 to 77)" }, { "code": null, "e": 3994, "s": 3872, "text": "Calculate predictions by taking the weighted average of the support set labels with the normalised distance (lines 83–89)" }, { "code": null, "e": 4015, "s": 3994, "text": "Some things to note:" }, { "code": null, "e": 4168, "s": 4015, "text": "In this example the x Tensor contains first the support set samples and then the query. For Omniglot it will have shape (n_support + n_query, 1, 28, 28)" }, { "code": null, "e": 4320, "s": 4168, "text": "The math in the previous post is for one query sample but Matching Networks are in fact trained with a batch of query samples of size q_queries * k_way" }, { "code": null, "e": 4885, "s": 4320, "text": "I was unable to reproduce the results of this paper using cosine distance but was successful when using l2 distance. I believe this is because cosine distance is bounded between -1 and 1 which then limits the amount that the attention function (a(x^, x_i) below) can point to a particular sample in the support set. Since cosine distance is bounded a(x^, x_i) will never be close to 1! In the case of 5-way classification the maximum possible value of a(x^, x_i) is exp(1)/ (exp(1) + 4*exp(-1)) ≈ 0.65. This led to very slow convergence when using cosine distance." }, { "code": null, "e": 5236, "s": 4885, "text": "I think it’s possible to reproduce the results using cosine distance with either longer training times, better hyperparameters or a heuristic like multiplying the cosine distance by a constant factor. Seeing as the choice of distance is not key to the paper and results are very good using l2 distance I decided to spare myself that debugging effort." }, { "code": null, "e": 5396, "s": 5236, "text": "In Prototypical Networks Snell et al use a compelling inductive bias motivated by the theory of Bregman divergences to achieve impressive few-shot performance." }, { "code": null, "e": 5461, "s": 5396, "text": "The Prototypical Network algorithm can be summarised as follows:" }, { "code": null, "e": 5696, "s": 5461, "text": "Embed all query and support samples (line 36)Calculate class prototypes taking the mean of the embeddings of each class (line 48)Predictions are a softmax over the distances between the query samples and the class prototypes (line 63)" }, { "code": null, "e": 5742, "s": 5696, "text": "Embed all query and support samples (line 36)" }, { "code": null, "e": 5827, "s": 5742, "text": "Calculate class prototypes taking the mean of the embeddings of each class (line 48)" }, { "code": null, "e": 5933, "s": 5827, "text": "Predictions are a softmax over the distances between the query samples and the class prototypes (line 63)" }, { "code": null, "e": 6237, "s": 5933, "text": "I found this paper delightfully easy to reproduce as the authors provided the full set of hyperparameters. Hence I was easily able to achieve the stated performance to within ~0.2% on the Omniglot benchmark and within a few % on the miniImageNet benchmark without having to perform any tuning of my own." }, { "code": null, "e": 6491, "s": 6237, "text": "In MAML Finn et al introduce a powerful and broadly applicable meta-learning algorithm to learn a network initialisation that can quickly adapt to new tasks. This paper was the most difficult yet most rewarding to reproduce of the three in this article." }, { "code": null, "e": 6540, "s": 6491, "text": "The MAML algorithm can be summarised as follows:" }, { "code": null, "e": 7099, "s": 6540, "text": "For each n-shot task in a meta-batch of tasks, create a new model using the weights of the base model AKA meta-learner (line 79)Update the weights of the new model using the loss from the samples in the task by stochastic gradient descent (lines 81–92)Calculate loss of the updated model on some more data from the same task (lines 94–97)If performing 1st order MAML update the meta-learner weights with the gradient of the loss from part 3. If performing 2nd order MAML calculate the derivative of this loss with respect to the original weights (lines 110+)" }, { "code": null, "e": 7228, "s": 7099, "text": "For each n-shot task in a meta-batch of tasks, create a new model using the weights of the base model AKA meta-learner (line 79)" }, { "code": null, "e": 7353, "s": 7228, "text": "Update the weights of the new model using the loss from the samples in the task by stochastic gradient descent (lines 81–92)" }, { "code": null, "e": 7440, "s": 7353, "text": "Calculate loss of the updated model on some more data from the same task (lines 94–97)" }, { "code": null, "e": 7661, "s": 7440, "text": "If performing 1st order MAML update the meta-learner weights with the gradient of the loss from part 3. If performing 2nd order MAML calculate the derivative of this loss with respect to the original weights (lines 110+)" }, { "code": null, "e": 8108, "s": 7661, "text": "The biggest appeal of PyTorch is its autograd system. This is a piece of code-magic that records operations acting on torch.Tensor objects and dynamically builds the directed acyclic graph of these operations under the hood. Backpropagation is as simple as calling .backwards() on the final result. I had to learn a bit more about this system in order to calculate and apply parameter updates to the meta-learner, which I will now share with you." }, { "code": null, "e": 8228, "s": 8108, "text": "Typically when training a model in PyTorch you create an Optimizer object tied to the parameters of a particular model." }, { "code": null, "e": 8297, "s": 8228, "text": "from torch.optim import Adamopt = Adam(model.parameters(), lr=0.001)" }, { "code": null, "e": 8593, "s": 8297, "text": "When opt.step() is called the optimiser reads the gradients on the model parameters and calculates an update to those parameters. However in 1st order MAML we’ re going to calculate the gradients using one model (the fast weights) and apply the update to a different model i.e. the meta-learner." }, { "code": null, "e": 9163, "s": 8593, "text": "A solution to this is to use an under-utilised bit of PyTorch functionality in the form of torch.Tensor.register_hook(hook). Register a hook function to a Tensor and this hook function will be called whenever a gradient with respect to this tensor is computed. For each parameter Tensor in the meta-learner I register a hook that simply replaces the gradient with the corresponding gradient on the fast weights (lines 111–129 in gist). This means that when opt.step() is called the gradients of the fast model will be used to update the meta-learner weights as desired." }, { "code": null, "e": 9681, "s": 9163, "text": "When making my first attempt at implementing MAML I instantiated a new model object (subclass of torch.nn.Module) and set the values of its weights equal to the meta-learner’s weights. However this makes it impossible to perform 2nd order MAML as the weights of the fast model are disconnected from the weights of the meta-learner in the eyes of torch.autograd. What this means is when I call optimiser.step() (line 140 in the gist) the autograd graph for the meta-learner weights is empty and no update is performed." }, { "code": null, "e": 10105, "s": 9681, "text": "# This didn't work, meta_learner weights remain unchangedmeta_learner = ModelClass()opt = Adam(meta_learner.parameters(), lr=0.001)task_losses = []for x, y in meta_batch: fast_model = ModelClass() # torch.autograd loses reference here! copy_weights(from=meta_learner, to=fast_model) task_losses.append(update_with_batch(x, y))meta_batch_loss = torch.stack(task_losses).mean()meta_batch_loss.backward()opt.step()" }, { "code": null, "e": 10580, "s": 10105, "text": "The solution to this is functional_forward() (line 17) which is a slightly awkward hack that manually performs the same operations (convolution, max pooling, etc...) as the model class using torch.nn.functional. This also means that I have to manually perform a parameter update of the fast model. The consequence of this is that torch.autograd knows to backpropagate gradients to the original weights of the meta-learner. This leads to a spectacularly large autograd graph." }, { "code": null, "e": 11105, "s": 10580, "text": "However 2nd order MAML is a trickier beast than just that. When I first wrote my 2nd order MAML implementation I thought I had got everything to work miraculously on the first try. At least there were no exceptions right? Only after running a full set of Omniglot and miniImageNet experiments did I begin to doubt my work — the results were just too similar to 1st order MAML. This is typical of an unfortunate breed of silent ML bugs which don’t cause exceptions but only become visible in the final performance of a model." }, { "code": null, "e": 11377, "s": 11105, "text": "Hence I decided to buckle down and write a unit test that would confirm that I was truly performing a 2nd order update. Disclaimer: in the spirit of true test-driven development I should’ve written this test before running any experiments. It turns out I’m not perfect 😛." }, { "code": null, "e": 11777, "s": 11377, "text": "The test I decided on was to run the meta_gradient_step function on a dummy model and manually parse the autograd graph, counting the number of double backwards operations. This way I can be absolutely sure that I am performing a 2nd order update when desired. Conversely, I was able to test that my 1st order MAML implementation only performs a 1st order update with no double backwards operations." }, { "code": null, "e": 12076, "s": 11777, "text": "I finally located the bug to not applying the create_graph parameter in the inner training loop (line 86). I was, however, retaining the autograd graph of the loss on the query samples (line 97) but this was insufficient to perform a 2nd order update as the unrolled training graph was not created." }, { "code": null, "e": 12229, "s": 12076, "text": "Training time was quite long (over 24 hours for the 5-way, 5-shot miniImageNet experiment) but in the end I had fairly good success reproducing results." }, { "code": null, "e": 12371, "s": 12229, "text": "I hope that you’ve learnt something useful from this technical deep dive. If you have any questions feel free to let me know in the comments." } ]
Tryit Editor v3.7
Tryit: HTML italic text
[]
The Simple Math behind 3 Decision Tree Splitting criterions | by Rahul Agarwal | Towards Data Science
Decision Trees are great and are useful for a variety of tasks. They form the backbone of most of the best performing models in the industry like XGboost and Lightgbm. But how do they work exactly? In fact, this is one of the most asked questions in ML/DS interviews. We generally know they work in a stepwise manner and have a tree structure where we split a node using some feature on some criterion. But how do these features get selected and how a particular threshold or value gets chosen for a feature? In this post, I will talk about three of the main splitting criteria used in Decision trees and why they work. This is something that has been written about repeatedly but never really well enough. According to Wikipedia, Gini impurity is a measure of how often a randomly chosen element from the set would be incorrectly labeled if it was randomly labeled according to the distribution of labels in the subset. In simple terms, Gini impurity is the measure of impurity in a node. Its formula is: where J is the number of classes present in the node and p is the distribution of the class in the node. So to understand the formula a little better, let us talk specifically about the binary case where we have nodes with only two classes. So in the below five examples of candidate nodes labelled A-E and with the distribution of positive and negative class shown, which is the ideal condition to be in? I reckon you would say A or E and you are right. What is the worst situation to be in? C, I suppose as the data is precisely 50:50 in that node. Now, this all looks good, intuitively. Gini Impurity gives us a way to quantify it. Let us calculate the Gini impurity for all five nodes separately and check the values. ✅ Gini Impurity works as expected. Maximum for Node C and the minimum for both A and E. We need to choose the node with Minimum Gini Impurity. We could also see the plot of Gini Impurity for the binary case to verify the above. ❓So how do we exactly use it in a Decision Tree? Suppose, we have the UCI Heart Disease data. The “target” field refers to the presence of heart disease in the patient. It is 0 (no presence) or 1. We now already have a measure in place(Gini Impurity) using which we can evaluate a split on a particular variable with a certain threshold(continuous) or value(categorical). For simplicity, let us start with a categorical variable — sex. If we split by Sex, our tree will look like below: Notice that we use Sex =0 and Sex!=0 so that this generalises well to categories with multiple levels. Our root node has 165 +ve examples and 138 -ve examples. And we get two child nodes when we split by sex. We already know how to calculate the impurity for a node. So we calculate the impurity of the left child as well as the right child. I_Left = 1 - (72/96)**2 - (24/96)**2I_Right = 1 - (93/207)**2 - (114/207)**2print("Left Node Impurity:",I_Left)print("Right Node Impurity:",I_Right)---------------------------------------------------------------Left Node Impurity: 0.375Right Node Impurity: 0.4948540222642302 We get two numbers here. We need to get a single number which provides the impurity of a single split. So what do we do? Should, we take an average? We can take an average, but what will happen if one node gets only one example and another node has all other examples? To mitigate the above, we take a weighted average of the two impurities weighted by the number of examples in the individual node. In code: gender_split_impurity = 96/(96+207)*I_Left + 207/(96+207)*I_Rightprint(gender_split_impurity)----------------------------------------------------------------0.45688047065576126 We can split by a continuous variable too. Let us try to split using cholesterol feature in the dataset. We chose a threshold of 250 and created a tree. I_Left = 1 - (58/126)**2 - (68/126)**2I_Right = 1 - (107/177)**2 - (70/177)**2print("Left Node Impurity:",I_Left)print("Right Node Impurity:",I_Right)---------------------------------------------------------------Left Node Impurity: 0.49685059208868737Right Node Impurity: 0.47815123368125373 Just by looking at both the impurities close to 0.5, we can infer that it is not a good split. Still, we calculate our weighted Gini impurity as before: chol_split_impurity = 126/(126+177)*I_Left + 177/(126+177)*I_Rightprint(chol_split_impurity)---------------------------------------------------------------0.48592720450414695 Since the chol_split_impurity>gender_split_impurity, we split based on Gender. In reality, we evaluate a lot of different splits. With different threshold values for a continuous variable. And all the levels for categorical variables. And then choose the split which provides us with the lowest weighted impurity in the child nodes. Another very popular way to split nodes in the decision tree is Entropy. Entropy is the measure of Randomness in the system. The formula for Entropy is: where C is the number of classes present in the node and p is the distribution of the class in the node. So again talking about the binary case we talked about before. What is the value of Entropy for all the 5 cases from A-E? Entropy values work as expected. Maximum for Node C and the minimum for both A and E. We need to choose the node with Minimum Entropy. We could also see the plot of Entropy for the binary case to verify the above. So how do we exactly use Entropy in a Decision Tree? We are using the Heartrate example as before. We now already have a measure in place(Entropy) using which we can evaluate a split on an individual variable with a certain threshold(continuous) or value(categorical). For simplicity, let us start with a categorical variable — sex. If we split by Sex, our tree will look like below: We already know how to calculate the randomness for a node. So we calculate the randomness of the left child as well as the right child. E_Left = -(72/96)*np.log2(72/96) - (24/96)*np.log2(24/96)E_Right = -(93/207)*np.log2(93/207) - (114/207)*np.log2(114/207)print("Left Node Randomness:",E_Left)print("Right Node Randomness:",E_Right)---------------------------------------------------------------Left Node Randomness: 0.8112781244591328Right Node Randomness: 0.992563136012236 We get two numbers here. We need to get a single number which provides the Randomness of a single split. So what do we do? We again take a weighted average where we weight by the number of examples in the individual node. In code: gender_split_randomness = 96/(96+207)*E_Left + 207/(96+207)*E_Rightprint(gender_split_randomness)----------------------------------------------------------------0.9351263006686785 Again as before, we can split by a continuous variable too. Let us try to split using cholesterol feature in the dataset. We chose a threshold of 250 and create a tree. E_Left = -(58/126)*np.log2(58/126) - (68/126)*np.log2(68/126)E_Right = -(107/177)*np.log2(107/177) - (70/177)*np.log2(70/177)print("Left Node Randomness:",E_Left)print("Right Node Randomness:",E_Right)---------------------------------------------------------------Left Node Randomness: 0.9954515828457715Right Node Randomness: 0.9682452182690404 Just by looking at both the randomness close to 1, we can infer that it is not a good split. Still, we calculate our weighted Entropy as before: chol_split_randomness = 126/(126+177)*E_Left + 177/(126+177)*E_Rightprint(chol_split_randomness)---------------------------------------------------------------0.9795587560138196 Since the chol_split_randomness>gender_split_randomness, we split based on Gender. Precisely the same results we got from Gini. Gini Impurity and Entropy work pretty well for the classification scenario. But what about regression? In the case of regression, the most common split measure used is just the weighted variance of the nodes. It makes sense too: We want minimum variation in the nodes after the split. We want a regression task for this. So, we have the data for 50 startups, and we want to predict Profit. Let us try a split by a categorical variable ⇒State=Florida. If we split by State=FL, our tree will look like below: Overall Variance then is just the weighted sums of individual variances: overall_variance = 16/(16+34)*Var_Left + 34/(16+34)*Var_Rightprint(overall_variance)----------------------------------------------------------------1570582843 Again as before, we can split by a continuous variable too. Let us try to split using R&D spend feature in the dataset. We chose a threshold of 100000 and create a tree. Just by looking at this, we can see it is better than our previous split. So, we find the overall variance in this case: overall_variance = 14/(14+36)*419828105 + 36/(14+36)*774641406print(overall_variance)----------------------------------------------------------675293681.7199999 Since the overall_variance(R&D>=100000)< overall_variance(State==FL), we prefer a split based on R&D. If you want to learn more about Data Science, I would like to call out this excellent course by Andrew Ng. This was the one that got me started. Do check it out. Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz. Also, a small disclaimer — There might be some affiliate links in this post to relevant resources as sharing knowledge is never a bad idea.
[ { "code": null, "e": 340, "s": 172, "text": "Decision Trees are great and are useful for a variety of tasks. They form the backbone of most of the best performing models in the industry like XGboost and Lightgbm." }, { "code": null, "e": 440, "s": 340, "text": "But how do they work exactly? In fact, this is one of the most asked questions in ML/DS interviews." }, { "code": null, "e": 575, "s": 440, "text": "We generally know they work in a stepwise manner and have a tree structure where we split a node using some feature on some criterion." }, { "code": null, "e": 681, "s": 575, "text": "But how do these features get selected and how a particular threshold or value gets chosen for a feature?" }, { "code": null, "e": 879, "s": 681, "text": "In this post, I will talk about three of the main splitting criteria used in Decision trees and why they work. This is something that has been written about repeatedly but never really well enough." }, { "code": null, "e": 903, "s": 879, "text": "According to Wikipedia," }, { "code": null, "e": 1093, "s": 903, "text": "Gini impurity is a measure of how often a randomly chosen element from the set would be incorrectly labeled if it was randomly labeled according to the distribution of labels in the subset." }, { "code": null, "e": 1178, "s": 1093, "text": "In simple terms, Gini impurity is the measure of impurity in a node. Its formula is:" }, { "code": null, "e": 1283, "s": 1178, "text": "where J is the number of classes present in the node and p is the distribution of the class in the node." }, { "code": null, "e": 1419, "s": 1283, "text": "So to understand the formula a little better, let us talk specifically about the binary case where we have nodes with only two classes." }, { "code": null, "e": 1584, "s": 1419, "text": "So in the below five examples of candidate nodes labelled A-E and with the distribution of positive and negative class shown, which is the ideal condition to be in?" }, { "code": null, "e": 1729, "s": 1584, "text": "I reckon you would say A or E and you are right. What is the worst situation to be in? C, I suppose as the data is precisely 50:50 in that node." }, { "code": null, "e": 1813, "s": 1729, "text": "Now, this all looks good, intuitively. Gini Impurity gives us a way to quantify it." }, { "code": null, "e": 1900, "s": 1813, "text": "Let us calculate the Gini impurity for all five nodes separately and check the values." }, { "code": null, "e": 2043, "s": 1900, "text": "✅ Gini Impurity works as expected. Maximum for Node C and the minimum for both A and E. We need to choose the node with Minimum Gini Impurity." }, { "code": null, "e": 2128, "s": 2043, "text": "We could also see the plot of Gini Impurity for the binary case to verify the above." }, { "code": null, "e": 2177, "s": 2128, "text": "❓So how do we exactly use it in a Decision Tree?" }, { "code": null, "e": 2325, "s": 2177, "text": "Suppose, we have the UCI Heart Disease data. The “target” field refers to the presence of heart disease in the patient. It is 0 (no presence) or 1." }, { "code": null, "e": 2500, "s": 2325, "text": "We now already have a measure in place(Gini Impurity) using which we can evaluate a split on a particular variable with a certain threshold(continuous) or value(categorical)." }, { "code": null, "e": 2564, "s": 2500, "text": "For simplicity, let us start with a categorical variable — sex." }, { "code": null, "e": 2615, "s": 2564, "text": "If we split by Sex, our tree will look like below:" }, { "code": null, "e": 2824, "s": 2615, "text": "Notice that we use Sex =0 and Sex!=0 so that this generalises well to categories with multiple levels. Our root node has 165 +ve examples and 138 -ve examples. And we get two child nodes when we split by sex." }, { "code": null, "e": 2957, "s": 2824, "text": "We already know how to calculate the impurity for a node. So we calculate the impurity of the left child as well as the right child." }, { "code": null, "e": 3233, "s": 2957, "text": "I_Left = 1 - (72/96)**2 - (24/96)**2I_Right = 1 - (93/207)**2 - (114/207)**2print(\"Left Node Impurity:\",I_Left)print(\"Right Node Impurity:\",I_Right)---------------------------------------------------------------Left Node Impurity: 0.375Right Node Impurity: 0.4948540222642302" }, { "code": null, "e": 3502, "s": 3233, "text": "We get two numbers here. We need to get a single number which provides the impurity of a single split. So what do we do? Should, we take an average? We can take an average, but what will happen if one node gets only one example and another node has all other examples?" }, { "code": null, "e": 3642, "s": 3502, "text": "To mitigate the above, we take a weighted average of the two impurities weighted by the number of examples in the individual node. In code:" }, { "code": null, "e": 3819, "s": 3642, "text": "gender_split_impurity = 96/(96+207)*I_Left + 207/(96+207)*I_Rightprint(gender_split_impurity)----------------------------------------------------------------0.45688047065576126" }, { "code": null, "e": 3972, "s": 3819, "text": "We can split by a continuous variable too. Let us try to split using cholesterol feature in the dataset. We chose a threshold of 250 and created a tree." }, { "code": null, "e": 4265, "s": 3972, "text": "I_Left = 1 - (58/126)**2 - (68/126)**2I_Right = 1 - (107/177)**2 - (70/177)**2print(\"Left Node Impurity:\",I_Left)print(\"Right Node Impurity:\",I_Right)---------------------------------------------------------------Left Node Impurity: 0.49685059208868737Right Node Impurity: 0.47815123368125373" }, { "code": null, "e": 4418, "s": 4265, "text": "Just by looking at both the impurities close to 0.5, we can infer that it is not a good split. Still, we calculate our weighted Gini impurity as before:" }, { "code": null, "e": 4593, "s": 4418, "text": "chol_split_impurity = 126/(126+177)*I_Left + 177/(126+177)*I_Rightprint(chol_split_impurity)---------------------------------------------------------------0.48592720450414695" }, { "code": null, "e": 4672, "s": 4593, "text": "Since the chol_split_impurity>gender_split_impurity, we split based on Gender." }, { "code": null, "e": 4926, "s": 4672, "text": "In reality, we evaluate a lot of different splits. With different threshold values for a continuous variable. And all the levels for categorical variables. And then choose the split which provides us with the lowest weighted impurity in the child nodes." }, { "code": null, "e": 5079, "s": 4926, "text": "Another very popular way to split nodes in the decision tree is Entropy. Entropy is the measure of Randomness in the system. The formula for Entropy is:" }, { "code": null, "e": 5184, "s": 5079, "text": "where C is the number of classes present in the node and p is the distribution of the class in the node." }, { "code": null, "e": 5306, "s": 5184, "text": "So again talking about the binary case we talked about before. What is the value of Entropy for all the 5 cases from A-E?" }, { "code": null, "e": 5441, "s": 5306, "text": "Entropy values work as expected. Maximum for Node C and the minimum for both A and E. We need to choose the node with Minimum Entropy." }, { "code": null, "e": 5520, "s": 5441, "text": "We could also see the plot of Entropy for the binary case to verify the above." }, { "code": null, "e": 5573, "s": 5520, "text": "So how do we exactly use Entropy in a Decision Tree?" }, { "code": null, "e": 5789, "s": 5573, "text": "We are using the Heartrate example as before. We now already have a measure in place(Entropy) using which we can evaluate a split on an individual variable with a certain threshold(continuous) or value(categorical)." }, { "code": null, "e": 5853, "s": 5789, "text": "For simplicity, let us start with a categorical variable — sex." }, { "code": null, "e": 5904, "s": 5853, "text": "If we split by Sex, our tree will look like below:" }, { "code": null, "e": 6041, "s": 5904, "text": "We already know how to calculate the randomness for a node. So we calculate the randomness of the left child as well as the right child." }, { "code": null, "e": 6382, "s": 6041, "text": "E_Left = -(72/96)*np.log2(72/96) - (24/96)*np.log2(24/96)E_Right = -(93/207)*np.log2(93/207) - (114/207)*np.log2(114/207)print(\"Left Node Randomness:\",E_Left)print(\"Right Node Randomness:\",E_Right)---------------------------------------------------------------Left Node Randomness: 0.8112781244591328Right Node Randomness: 0.992563136012236" }, { "code": null, "e": 6613, "s": 6382, "text": "We get two numbers here. We need to get a single number which provides the Randomness of a single split. So what do we do? We again take a weighted average where we weight by the number of examples in the individual node. In code:" }, { "code": null, "e": 6793, "s": 6613, "text": "gender_split_randomness = 96/(96+207)*E_Left + 207/(96+207)*E_Rightprint(gender_split_randomness)----------------------------------------------------------------0.9351263006686785" }, { "code": null, "e": 6962, "s": 6793, "text": "Again as before, we can split by a continuous variable too. Let us try to split using cholesterol feature in the dataset. We chose a threshold of 250 and create a tree." }, { "code": null, "e": 7308, "s": 6962, "text": "E_Left = -(58/126)*np.log2(58/126) - (68/126)*np.log2(68/126)E_Right = -(107/177)*np.log2(107/177) - (70/177)*np.log2(70/177)print(\"Left Node Randomness:\",E_Left)print(\"Right Node Randomness:\",E_Right)---------------------------------------------------------------Left Node Randomness: 0.9954515828457715Right Node Randomness: 0.9682452182690404" }, { "code": null, "e": 7453, "s": 7308, "text": "Just by looking at both the randomness close to 1, we can infer that it is not a good split. Still, we calculate our weighted Entropy as before:" }, { "code": null, "e": 7631, "s": 7453, "text": "chol_split_randomness = 126/(126+177)*E_Left + 177/(126+177)*E_Rightprint(chol_split_randomness)---------------------------------------------------------------0.9795587560138196" }, { "code": null, "e": 7759, "s": 7631, "text": "Since the chol_split_randomness>gender_split_randomness, we split based on Gender. Precisely the same results we got from Gini." }, { "code": null, "e": 7835, "s": 7759, "text": "Gini Impurity and Entropy work pretty well for the classification scenario." }, { "code": null, "e": 7862, "s": 7835, "text": "But what about regression?" }, { "code": null, "e": 8044, "s": 7862, "text": "In the case of regression, the most common split measure used is just the weighted variance of the nodes. It makes sense too: We want minimum variation in the nodes after the split." }, { "code": null, "e": 8149, "s": 8044, "text": "We want a regression task for this. So, we have the data for 50 startups, and we want to predict Profit." }, { "code": null, "e": 8210, "s": 8149, "text": "Let us try a split by a categorical variable ⇒State=Florida." }, { "code": null, "e": 8266, "s": 8210, "text": "If we split by State=FL, our tree will look like below:" }, { "code": null, "e": 8339, "s": 8266, "text": "Overall Variance then is just the weighted sums of individual variances:" }, { "code": null, "e": 8498, "s": 8339, "text": "overall_variance = 16/(16+34)*Var_Left + 34/(16+34)*Var_Rightprint(overall_variance)----------------------------------------------------------------1570582843" }, { "code": null, "e": 8668, "s": 8498, "text": "Again as before, we can split by a continuous variable too. Let us try to split using R&D spend feature in the dataset. We chose a threshold of 100000 and create a tree." }, { "code": null, "e": 8789, "s": 8668, "text": "Just by looking at this, we can see it is better than our previous split. So, we find the overall variance in this case:" }, { "code": null, "e": 8950, "s": 8789, "text": "overall_variance = 14/(14+36)*419828105 + 36/(14+36)*774641406print(overall_variance)----------------------------------------------------------675293681.7199999" }, { "code": null, "e": 9052, "s": 8950, "text": "Since the overall_variance(R&D>=100000)< overall_variance(State==FL), we prefer a split based on R&D." }, { "code": null, "e": 9214, "s": 9052, "text": "If you want to learn more about Data Science, I would like to call out this excellent course by Andrew Ng. This was the one that got me started. Do check it out." }, { "code": null, "e": 9478, "s": 9214, "text": "Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz." } ]
ICC 2019 Cricket World Cup Prediction using Machine Learning | by Abhinav Sagar | Towards Data Science
Stuck behind the paywall? Click here to read the full story with my Friend Link! The 2019 ICC Men’s Cricket World Cup is ready to begin on Thursday (30th May). This 12th edition of the Cricket World Cup will run for almost one and a half month in England and Wales. The tournament will be contested by 10 teams who will be playing in a single round-robin group, with the top four at the end of the group phase progressing to the semi-finals. Predicting the future sounds like magic whether it be detecting in advance the intent of a potential customer to purchase your product or figuring out where the price of a stock is headed. If we can reliably predict the future of something, then we own a massive advantage. Machine learning has only served to amplify this magic and mystery. The main objective of sports prediction is to improve team performance and enhance the chances of winning the game. The value of a win takes on different forms like trickles down to the fans filling the stadium seats, television contracts, fan store merchandise, parking, concessions, sponsorships, enrollment and retention. Real world data is dirty. We can’t expect a nicely formatted and clean data as provided by Kaggle. Therefore, data pre-processing is so crucial that I can’t stress enough how important it is. It is the most important stage as it could occupy 40%-70% of the whole workflow, just to clean the data to be fed to your models. I scraped three scripts from Crickbuzz website comprising of rankings of teams as of May 2019, details of the fixtures of 2019 world cup and details of each team’s history in previous world cups. I stored the above piece of data in three separate csv files. For the fourth file, I grabbed odi data-set for matches played between 1975 and 2017 from Kaggle in another csv file. In this file, I removed all the data from 1975 to 2010. This was done as the results of the last few years should only matter for our predictions. Since I didn’t get the data for 2018 and 2019 so this model might not be that accurate but still I believe this gives a fairly good idea. Then I did manual cleaning of the data as per my needs to make a machine learning model out of it. Jupyter NotebookNumpyPandasSeabornMatplotlibScikit-learn Jupyter Notebook Numpy Pandas Seaborn Matplotlib Scikit-learn I followed the general machine learning workflow step-by-step: Data cleaning and formatting.Exploratory data analysis.Feature engineering and selection.Compare several machine learning models on a performance metric.Perform hyper-parameter tuning on the best model.Evaluate the best model on the testing set.Interpret the model results.Draw conclusions and document work. Data cleaning and formatting. Exploratory data analysis. Feature engineering and selection. Compare several machine learning models on a performance metric. Perform hyper-parameter tuning on the best model. Evaluate the best model on the testing set. Interpret the model results. Draw conclusions and document work. Without much ado, let’s get started with the code. The complete project on github can be found here. I started by importing all the libraries and dependencies. Then I loaded the csv file containing the details of each team’s history in previous world cups. I also loaded the csv file containing the results of matches played between 2010 and 2017. Next, let’s display the details of matches played by India. I continued by creating a column to display the details of matches played in 2010 and taking it as a reference for future work. After that, I merged the details of the teams participating this year with their past results. I deleted the columns like date of the match, margin of victory, and the ground on which the match was played. These features doesn’t look important for our prediction. This is probably the most important part in the machine learning workflow. Since the algorithm is totally dependent on how we feed data into it, feature engineering should be given topmost priority for every machine learning project. Feature engineering is the process of transforming raw data into features that better represent the underlying problem to the predictive models, resulting in improved model accuracy on unseen data. · Reduces Overfitting: Less redundant data means less opportunity to make decisions based on noise. · Improves Accuracy: Less misleading data means modeling accuracy improves. · Reduces Training Time: fewer data points reduce algorithm complexity and algorithms train faster. So continuing with the work, I created the model. If team-1 won the match, I assigned it label 1, else if team-2 won, I assigned it label 2. Then I converted team-1 and team-2 from categorical variables to continuous inputs using pandas function pd.get_dummies. This variable has only two answer choices: team 1 and team 2. It creates a new dataframe which consists of zeros and ones. The dataframe will have a one depending on the team of a particular game in this case. Also, I separated training and test sets with 70% and 30% in training and validation sets respectively. I used Logistic Regression, Support Vector Machines, Random Forests and K Nearest Neighbours for training the model. Random Forest outperformed all other algorithms with 70% training accuracy and 67.5% test accuracy. The random forest combines hundreds or thousands of decision trees, trains each one on a slightly different set of the observations, splitting nodes in each tree considering a limited number of the features. The final predictions of the random forest are made by averaging the predictions of each individual tree. RFs train each tree independently, using a random sample of the data. This randomness helps to make the model more robust than a single decision tree, and less likely to overfit on the training data. Training set accuracy: 0.700Test set accuracy: 0.675 The popularity of the Random Forest model is explained by its various advantages: Accurate and efficient when running on large databases Multiple trees reduce the variance and bias of a smaller set or single tree Resistant to overfitting Can handle thousands of input variables without variable deletion Can estimate what variables are important in classification Provides effective methods for estimating missing data Maintains accuracy when a large proportion of the data is missing Let’s continue. I added ICC rankings of teams giving priority to higher ranked team to win this year. Next, I added new columns with ranking position for each team and slicing the dataset for first 45 games since there are 45 league stage games in total. Then I added teams to new prediction dataset based on ranking position of each team. After that, I added scripts for getting dummy variables and added missing columns compared to model training dataset. Finally, the below code is for getting the results for each and every league stage match. For the results feel free to refer the corresponding jupyter notebook. So the four teams to march to the semi finals are New Zealand, India, England and South Africa. And then I created a function to repeat the above work. This is the final function to predict the winner of ICC Cricket World Cup 2019. I ran the function for semi-finals prediction. New Zealand and IndiaWinner: India South Africa and EnglandWinner: England Hence the two finalists are India and England which is quite evident as they are considered the favourites to win this year. Also, they are first and second ranked team in ICC rankings. Finally on running the main function. India and England Winner: England This article was written to show how Machine Learning could be used to calculate probabilities in a simulation and does not attempt to actually get the results right since the data used is not enough for it (or maybe the event itself is simply not predictable). Please, take this just as a tutorial, using World Cup matches just because it’s a cool and up to date subject. A much deeper approach should’ve been used to get better results and make them meaningful. Dataset — To improve dataset you could take 2018 and 2019 years into account by scraping them from the ESPN website and also possibly use the players' data to assess the quality of each team player.Trying more complex Machine Learning algorithms like Xgboost and fine-tuning the hyper parametersA confusion matrix would be great to analyse which games the model got wrong.We could ensemble that is we could try stacking more models together to improve the accuracy.Going even further and making a model based on player statistics. Dataset — To improve dataset you could take 2018 and 2019 years into account by scraping them from the ESPN website and also possibly use the players' data to assess the quality of each team player. Trying more complex Machine Learning algorithms like Xgboost and fine-tuning the hyper parameters A confusion matrix would be great to analyse which games the model got wrong. We could ensemble that is we could try stacking more models together to improve the accuracy. Going even further and making a model based on player statistics. towardsdatascience.com www.sciencedirect.com medium.com The corresponding project on github can be found here. github.com 15/7/2019 Update 1 — England has indeed won the world cup. If you want to keep updated with my latest articles and projects follow me on Medium. These are some of my contacts details: Personal Website Linkedin Medium Profile GitHub Kaggle Happy reading, happy learning and happy coding!
[ { "code": null, "e": 253, "s": 172, "text": "Stuck behind the paywall? Click here to read the full story with my Friend Link!" }, { "code": null, "e": 614, "s": 253, "text": "The 2019 ICC Men’s Cricket World Cup is ready to begin on Thursday (30th May). This 12th edition of the Cricket World Cup will run for almost one and a half month in England and Wales. The tournament will be contested by 10 teams who will be playing in a single round-robin group, with the top four at the end of the group phase progressing to the semi-finals." }, { "code": null, "e": 956, "s": 614, "text": "Predicting the future sounds like magic whether it be detecting in advance the intent of a potential customer to purchase your product or figuring out where the price of a stock is headed. If we can reliably predict the future of something, then we own a massive advantage. Machine learning has only served to amplify this magic and mystery." }, { "code": null, "e": 1281, "s": 956, "text": "The main objective of sports prediction is to improve team performance and enhance the chances of winning the game. The value of a win takes on different forms like trickles down to the fans filling the stadium seats, television contracts, fan store merchandise, parking, concessions, sponsorships, enrollment and retention." }, { "code": null, "e": 1603, "s": 1281, "text": "Real world data is dirty. We can’t expect a nicely formatted and clean data as provided by Kaggle. Therefore, data pre-processing is so crucial that I can’t stress enough how important it is. It is the most important stage as it could occupy 40%-70% of the whole workflow, just to clean the data to be fed to your models." }, { "code": null, "e": 2363, "s": 1603, "text": "I scraped three scripts from Crickbuzz website comprising of rankings of teams as of May 2019, details of the fixtures of 2019 world cup and details of each team’s history in previous world cups. I stored the above piece of data in three separate csv files. For the fourth file, I grabbed odi data-set for matches played between 1975 and 2017 from Kaggle in another csv file. In this file, I removed all the data from 1975 to 2010. This was done as the results of the last few years should only matter for our predictions. Since I didn’t get the data for 2018 and 2019 so this model might not be that accurate but still I believe this gives a fairly good idea. Then I did manual cleaning of the data as per my needs to make a machine learning model out of it." }, { "code": null, "e": 2420, "s": 2363, "text": "Jupyter NotebookNumpyPandasSeabornMatplotlibScikit-learn" }, { "code": null, "e": 2437, "s": 2420, "text": "Jupyter Notebook" }, { "code": null, "e": 2443, "s": 2437, "text": "Numpy" }, { "code": null, "e": 2450, "s": 2443, "text": "Pandas" }, { "code": null, "e": 2458, "s": 2450, "text": "Seaborn" }, { "code": null, "e": 2469, "s": 2458, "text": "Matplotlib" }, { "code": null, "e": 2482, "s": 2469, "text": "Scikit-learn" }, { "code": null, "e": 2545, "s": 2482, "text": "I followed the general machine learning workflow step-by-step:" }, { "code": null, "e": 2854, "s": 2545, "text": "Data cleaning and formatting.Exploratory data analysis.Feature engineering and selection.Compare several machine learning models on a performance metric.Perform hyper-parameter tuning on the best model.Evaluate the best model on the testing set.Interpret the model results.Draw conclusions and document work." }, { "code": null, "e": 2884, "s": 2854, "text": "Data cleaning and formatting." }, { "code": null, "e": 2911, "s": 2884, "text": "Exploratory data analysis." }, { "code": null, "e": 2946, "s": 2911, "text": "Feature engineering and selection." }, { "code": null, "e": 3011, "s": 2946, "text": "Compare several machine learning models on a performance metric." }, { "code": null, "e": 3061, "s": 3011, "text": "Perform hyper-parameter tuning on the best model." }, { "code": null, "e": 3105, "s": 3061, "text": "Evaluate the best model on the testing set." }, { "code": null, "e": 3134, "s": 3105, "text": "Interpret the model results." }, { "code": null, "e": 3170, "s": 3134, "text": "Draw conclusions and document work." }, { "code": null, "e": 3271, "s": 3170, "text": "Without much ado, let’s get started with the code. The complete project on github can be found here." }, { "code": null, "e": 3330, "s": 3271, "text": "I started by importing all the libraries and dependencies." }, { "code": null, "e": 3518, "s": 3330, "text": "Then I loaded the csv file containing the details of each team’s history in previous world cups. I also loaded the csv file containing the results of matches played between 2010 and 2017." }, { "code": null, "e": 3578, "s": 3518, "text": "Next, let’s display the details of matches played by India." }, { "code": null, "e": 3706, "s": 3578, "text": "I continued by creating a column to display the details of matches played in 2010 and taking it as a reference for future work." }, { "code": null, "e": 3801, "s": 3706, "text": "After that, I merged the details of the teams participating this year with their past results." }, { "code": null, "e": 3970, "s": 3801, "text": "I deleted the columns like date of the match, margin of victory, and the ground on which the match was played. These features doesn’t look important for our prediction." }, { "code": null, "e": 4204, "s": 3970, "text": "This is probably the most important part in the machine learning workflow. Since the algorithm is totally dependent on how we feed data into it, feature engineering should be given topmost priority for every machine learning project." }, { "code": null, "e": 4402, "s": 4204, "text": "Feature engineering is the process of transforming raw data into features that better represent the underlying problem to the predictive models, resulting in improved model accuracy on unseen data." }, { "code": null, "e": 4502, "s": 4402, "text": "· Reduces Overfitting: Less redundant data means less opportunity to make decisions based on noise." }, { "code": null, "e": 4578, "s": 4502, "text": "· Improves Accuracy: Less misleading data means modeling accuracy improves." }, { "code": null, "e": 4678, "s": 4578, "text": "· Reduces Training Time: fewer data points reduce algorithm complexity and algorithms train faster." }, { "code": null, "e": 4819, "s": 4678, "text": "So continuing with the work, I created the model. If team-1 won the match, I assigned it label 1, else if team-2 won, I assigned it label 2." }, { "code": null, "e": 5150, "s": 4819, "text": "Then I converted team-1 and team-2 from categorical variables to continuous inputs using pandas function pd.get_dummies. This variable has only two answer choices: team 1 and team 2. It creates a new dataframe which consists of zeros and ones. The dataframe will have a one depending on the team of a particular game in this case." }, { "code": null, "e": 5254, "s": 5150, "text": "Also, I separated training and test sets with 70% and 30% in training and validation sets respectively." }, { "code": null, "e": 5371, "s": 5254, "text": "I used Logistic Regression, Support Vector Machines, Random Forests and K Nearest Neighbours for training the model." }, { "code": null, "e": 5471, "s": 5371, "text": "Random Forest outperformed all other algorithms with 70% training accuracy and 67.5% test accuracy." }, { "code": null, "e": 5785, "s": 5471, "text": "The random forest combines hundreds or thousands of decision trees, trains each one on a slightly different set of the observations, splitting nodes in each tree considering a limited number of the features. The final predictions of the random forest are made by averaging the predictions of each individual tree." }, { "code": null, "e": 5985, "s": 5785, "text": "RFs train each tree independently, using a random sample of the data. This randomness helps to make the model more robust than a single decision tree, and less likely to overfit on the training data." }, { "code": null, "e": 6040, "s": 5985, "text": "Training set accuracy: 0.700Test set accuracy: 0.675" }, { "code": null, "e": 6122, "s": 6040, "text": "The popularity of the Random Forest model is explained by its various advantages:" }, { "code": null, "e": 6177, "s": 6122, "text": "Accurate and efficient when running on large databases" }, { "code": null, "e": 6253, "s": 6177, "text": "Multiple trees reduce the variance and bias of a smaller set or single tree" }, { "code": null, "e": 6278, "s": 6253, "text": "Resistant to overfitting" }, { "code": null, "e": 6344, "s": 6278, "text": "Can handle thousands of input variables without variable deletion" }, { "code": null, "e": 6404, "s": 6344, "text": "Can estimate what variables are important in classification" }, { "code": null, "e": 6459, "s": 6404, "text": "Provides effective methods for estimating missing data" }, { "code": null, "e": 6525, "s": 6459, "text": "Maintains accuracy when a large proportion of the data is missing" }, { "code": null, "e": 6627, "s": 6525, "text": "Let’s continue. I added ICC rankings of teams giving priority to higher ranked team to win this year." }, { "code": null, "e": 6780, "s": 6627, "text": "Next, I added new columns with ranking position for each team and slicing the dataset for first 45 games since there are 45 league stage games in total." }, { "code": null, "e": 6865, "s": 6780, "text": "Then I added teams to new prediction dataset based on ranking position of each team." }, { "code": null, "e": 6983, "s": 6865, "text": "After that, I added scripts for getting dummy variables and added missing columns compared to model training dataset." }, { "code": null, "e": 7073, "s": 6983, "text": "Finally, the below code is for getting the results for each and every league stage match." }, { "code": null, "e": 7240, "s": 7073, "text": "For the results feel free to refer the corresponding jupyter notebook. So the four teams to march to the semi finals are New Zealand, India, England and South Africa." }, { "code": null, "e": 7376, "s": 7240, "text": "And then I created a function to repeat the above work. This is the final function to predict the winner of ICC Cricket World Cup 2019." }, { "code": null, "e": 7423, "s": 7376, "text": "I ran the function for semi-finals prediction." }, { "code": null, "e": 7458, "s": 7423, "text": "New Zealand and IndiaWinner: India" }, { "code": null, "e": 7498, "s": 7458, "text": "South Africa and EnglandWinner: England" }, { "code": null, "e": 7684, "s": 7498, "text": "Hence the two finalists are India and England which is quite evident as they are considered the favourites to win this year. Also, they are first and second ranked team in ICC rankings." }, { "code": null, "e": 7722, "s": 7684, "text": "Finally on running the main function." }, { "code": null, "e": 7740, "s": 7722, "text": "India and England" }, { "code": null, "e": 7756, "s": 7740, "text": "Winner: England" }, { "code": null, "e": 8220, "s": 7756, "text": "This article was written to show how Machine Learning could be used to calculate probabilities in a simulation and does not attempt to actually get the results right since the data used is not enough for it (or maybe the event itself is simply not predictable). Please, take this just as a tutorial, using World Cup matches just because it’s a cool and up to date subject. A much deeper approach should’ve been used to get better results and make them meaningful." }, { "code": null, "e": 8751, "s": 8220, "text": "Dataset — To improve dataset you could take 2018 and 2019 years into account by scraping them from the ESPN website and also possibly use the players' data to assess the quality of each team player.Trying more complex Machine Learning algorithms like Xgboost and fine-tuning the hyper parametersA confusion matrix would be great to analyse which games the model got wrong.We could ensemble that is we could try stacking more models together to improve the accuracy.Going even further and making a model based on player statistics." }, { "code": null, "e": 8950, "s": 8751, "text": "Dataset — To improve dataset you could take 2018 and 2019 years into account by scraping them from the ESPN website and also possibly use the players' data to assess the quality of each team player." }, { "code": null, "e": 9048, "s": 8950, "text": "Trying more complex Machine Learning algorithms like Xgboost and fine-tuning the hyper parameters" }, { "code": null, "e": 9126, "s": 9048, "text": "A confusion matrix would be great to analyse which games the model got wrong." }, { "code": null, "e": 9220, "s": 9126, "text": "We could ensemble that is we could try stacking more models together to improve the accuracy." }, { "code": null, "e": 9286, "s": 9220, "text": "Going even further and making a model based on player statistics." }, { "code": null, "e": 9309, "s": 9286, "text": "towardsdatascience.com" }, { "code": null, "e": 9331, "s": 9309, "text": "www.sciencedirect.com" }, { "code": null, "e": 9342, "s": 9331, "text": "medium.com" }, { "code": null, "e": 9397, "s": 9342, "text": "The corresponding project on github can be found here." }, { "code": null, "e": 9408, "s": 9397, "text": "github.com" }, { "code": null, "e": 9467, "s": 9408, "text": "15/7/2019 Update 1 — England has indeed won the world cup." }, { "code": null, "e": 9592, "s": 9467, "text": "If you want to keep updated with my latest articles and projects follow me on Medium. These are some of my contacts details:" }, { "code": null, "e": 9609, "s": 9592, "text": "Personal Website" }, { "code": null, "e": 9618, "s": 9609, "text": "Linkedin" }, { "code": null, "e": 9633, "s": 9618, "text": "Medium Profile" }, { "code": null, "e": 9640, "s": 9633, "text": "GitHub" }, { "code": null, "e": 9647, "s": 9640, "text": "Kaggle" } ]
Boolean list initialization in Python
There are scenarios when we need to get a list containing only the Boolean values like true and false. In this article how to create list containing only Boolean values. We use range function giving it which is the number of values we want. Using a for loop we assign true or false today list as required. Live Demo res = [True for i in range(6)] # Result print("The list with binary elements is : \n" ,res) Running the above code gives us the following result − The list with binary elements is : [True, True, True, True, True, True] The * operator can repeat the same value required number of times. We use it to create a list with a Boolean value. Live Demo res = [False] * 6 # Result print("The list with binary elements is : \n" ,res) Running the above code gives us the following result − The list with binary elements is : [False, False, False, False, False, False] We can also use the byte array function which will give us 0 as default value. Live Demo res = list(bytearray(5)) # Result print("The list with binary elements is : \n" ,res) Running the above code gives us the following result − The list with binary elements is : [0, 0, 0, 0, 0]
[ { "code": null, "e": 1232, "s": 1062, "text": "There are scenarios when we need to get a list containing only the Boolean values like true and false. In this article how to create list containing only Boolean values." }, { "code": null, "e": 1368, "s": 1232, "text": "We use range function giving it which is the number of values we want. Using a for loop we assign true or false today list as required." }, { "code": null, "e": 1379, "s": 1368, "text": " Live Demo" }, { "code": null, "e": 1471, "s": 1379, "text": "res = [True for i in range(6)]\n# Result\nprint(\"The list with binary elements is : \\n\" ,res)" }, { "code": null, "e": 1526, "s": 1471, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1598, "s": 1526, "text": "The list with binary elements is :\n[True, True, True, True, True, True]" }, { "code": null, "e": 1714, "s": 1598, "text": "The * operator can repeat the same value required number of times. We use it to create a list with a Boolean value." }, { "code": null, "e": 1725, "s": 1714, "text": " Live Demo" }, { "code": null, "e": 1804, "s": 1725, "text": "res = [False] * 6\n# Result\nprint(\"The list with binary elements is : \\n\" ,res)" }, { "code": null, "e": 1859, "s": 1804, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1937, "s": 1859, "text": "The list with binary elements is :\n[False, False, False, False, False, False]" }, { "code": null, "e": 2016, "s": 1937, "text": "We can also use the byte array function which will give us 0 as default value." }, { "code": null, "e": 2027, "s": 2016, "text": " Live Demo" }, { "code": null, "e": 2113, "s": 2027, "text": "res = list(bytearray(5))\n# Result\nprint(\"The list with binary elements is : \\n\" ,res)" }, { "code": null, "e": 2168, "s": 2113, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2219, "s": 2168, "text": "The list with binary elements is :\n[0, 0, 0, 0, 0]" } ]
Compute pearson product-moment correlation coefficients of two given NumPy arrays - GeeksforGeeks
02 Sep, 2020 In NumPy, We can compute pearson product-moment correlation coefficients of two given arrays with the help of numpy.corrcoef() function. In this function, we will pass arrays as a parameter and it will return the pearson product-moment correlation coefficients of two given arrays. Syntax: numpy.corrcoef(x, y=None, rowvar=True, bias=, ddof=)Return: Pearson product-moment correlation coefficients Let’s see an example: Example 1: Python # import libraryimport numpy as np # create numpy 1d-arrayarray1 = np.array([0, 1, 2])array2 = np.array([3, 4, 5]) # pearson product-moment correlation# coefficients of the arraysrslt = np.corrcoef(array1, array2) print(rslt) Output [[1. 1.] [1. 1.]] Example 2: Python # import numpy libraryimport numpy as np # create a numpy 1d-arrayarray1 = np.array([ 2, 4, 8])array2 = np.array([ 3, 2,1]) # pearson product-moment correlation# coefficients of the arraysrslt2 = np.corrcoef(array1, array2) print(rslt2) Output [[ 1. -0.98198051] [-0.98198051 1. ]] Python numpy-program Python numpy-Statistics Functions Python-numpy 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 ? Selecting rows in pandas DataFrame based on conditions 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 | Get unique values from a list Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n02 Sep, 2020" }, { "code": null, "e": 24429, "s": 24292, "text": "In NumPy, We can compute pearson product-moment correlation coefficients of two given arrays with the help of numpy.corrcoef() function." }, { "code": null, "e": 24574, "s": 24429, "text": "In this function, we will pass arrays as a parameter and it will return the pearson product-moment correlation coefficients of two given arrays." }, { "code": null, "e": 24690, "s": 24574, "text": "Syntax: numpy.corrcoef(x, y=None, rowvar=True, bias=, ddof=)Return: Pearson product-moment correlation coefficients" }, { "code": null, "e": 24712, "s": 24690, "text": "Let’s see an example:" }, { "code": null, "e": 24723, "s": 24712, "text": "Example 1:" }, { "code": null, "e": 24730, "s": 24723, "text": "Python" }, { "code": "# import libraryimport numpy as np # create numpy 1d-arrayarray1 = np.array([0, 1, 2])array2 = np.array([3, 4, 5]) # pearson product-moment correlation# coefficients of the arraysrslt = np.corrcoef(array1, array2) print(rslt)", "e": 24959, "s": 24730, "text": null }, { "code": null, "e": 24966, "s": 24959, "text": "Output" }, { "code": null, "e": 24986, "s": 24966, "text": "[[1. 1.]\n [1. 1.]]\n" }, { "code": null, "e": 24997, "s": 24986, "text": "Example 2:" }, { "code": null, "e": 25004, "s": 24997, "text": "Python" }, { "code": "# import numpy libraryimport numpy as np # create a numpy 1d-arrayarray1 = np.array([ 2, 4, 8])array2 = np.array([ 3, 2,1]) # pearson product-moment correlation# coefficients of the arraysrslt2 = np.corrcoef(array1, array2) print(rslt2)", "e": 25246, "s": 25004, "text": null }, { "code": null, "e": 25253, "s": 25246, "text": "Output" }, { "code": null, "e": 25309, "s": 25253, "text": "[[ 1. -0.98198051]\n [-0.98198051 1. ]]\n" }, { "code": null, "e": 25330, "s": 25309, "text": "Python numpy-program" }, { "code": null, "e": 25364, "s": 25330, "text": "Python numpy-Statistics Functions" }, { "code": null, "e": 25377, "s": 25364, "text": "Python-numpy" }, { "code": null, "e": 25384, "s": 25377, "text": "Python" }, { "code": null, "e": 25482, "s": 25384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25491, "s": 25482, "text": "Comments" }, { "code": null, "e": 25504, "s": 25491, "text": "Old Comments" }, { "code": null, "e": 25536, "s": 25504, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25591, "s": 25536, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25647, "s": 25591, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25689, "s": 25647, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25731, "s": 25689, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25770, "s": 25731, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25792, "s": 25770, "text": "Defaultdict in Python" }, { "code": null, "e": 25813, "s": 25792, "text": "Python OOPs Concepts" }, { "code": null, "e": 25844, "s": 25813, "text": "Python | os.path.join() method" } ]
10 Essential Python Tips And Tricks For Programmers - GeeksforGeeks
Top 4 Advanced Project Ideas to Enhance Your AI Skills Top 10 Machine Learning Project Ideas That You Can Implement 5 Machine Learning Project Ideas for Beginners 7 Cool Python Project Ideas for Intermediate Developers 10 Interesting Python Cool Tricks 10 Essential Python Tips And Tricks For Programmers Amazing hacks of Python Python Input Methods for Competitive Programming Vulnerability in input() function – Python 2.x Python | Output using print() function Important differences between Python 2.x and Python 3.x with examples Python Keywords Keywords in Python | Set 2 Namespaces and Scope in Python Statement, Indentation and Comment in Python How to assign values to variables in Python and other languages How to print without newline in Python? Python end parameter in print() Python | sep parameter in print() Python | Output Formatting Python String format() Method f-strings in Python Enumerate() in Python Iterate over a list in Python Print lists in Python (4 Different Ways) Adding new column to existing DataFrame in Pandas Python map() function Taking input in Python How to get column names in Pandas dataframe Read JSON file using Python Top 4 Advanced Project Ideas to Enhance Your AI Skills Top 10 Machine Learning Project Ideas That You Can Implement 5 Machine Learning Project Ideas for Beginners 7 Cool Python Project Ideas for Intermediate Developers 10 Interesting Python Cool Tricks 10 Essential Python Tips And Tricks For Programmers Amazing hacks of Python Python Input Methods for Competitive Programming Vulnerability in input() function – Python 2.x Python | Output using print() function Important differences between Python 2.x and Python 3.x with examples Python Keywords Keywords in Python | Set 2 Namespaces and Scope in Python Statement, Indentation and Comment in Python How to assign values to variables in Python and other languages How to print without newline in Python? Python end parameter in print() Python | sep parameter in print() Python | Output Formatting Python String format() Method f-strings in Python Enumerate() in Python Iterate over a list in Python Print lists in Python (4 Different Ways) Adding new column to existing DataFrame in Pandas Python map() function Taking input in Python How to get column names in Pandas dataframe Read JSON file using Python Difficulty Level : Easy Python is one of the most preferred languages out there. Its brevity and high readability makes it so popular among all programmers.So here are few of the tips and tricks you can use to bring up your Python programming game. 1. In-Place Swapping Of Two Numbers. x, y = 10, 20print(x, y)x, y = y, xprint(x, y) 10 20 20 10 2. Reversing a string in Python a = "GeeksForGeeks"print("Reverse is", a[::-1]) Reverse is skeeGroFskeeG 3. Create a single string from all the elements in list a = ["Geeks", "For", "Geeks"]print(" ".join(a)) Geeks For Geeks 4. Chaining Of Comparison Operators. n = 10result = 1 < n < 20print(result)result = 1 > n <= 9print(result) True False 4. Print The File Path Of Imported Modules. import osimport socket print(os)print(socket) <module 'os' from '/usr/lib/python3.5/os.py'> <module 'socket' from '/usr/lib/python3.5/socket.py'> 5. Use Of Enums In Python. class MyName: Geeks, For, Geeks = range(3) print(MyName.Geeks)print(MyName.For)print(MyName.Geeks) 2 1 2 6. Return Multiple Values From Functions. def x(): return 1, 2, 3, 4a, b, c, d = x() print(a, b, c, d) 1 2 3 4 7. Find The Most Frequent Value In A List. test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]print(max(set(test), key = test.count)) 4 8. Check The Memory Usage Of An Object. import sysx = 1print(sys.getsizeof(x)) 28 9. Print string N times. n = 2a = "GeeksforGeeks"print(a * n) GeeksforGeeksGeeksforGeeks 10. Checking if two words are anagrams from collections import Counterdef is_anagram(str1, str2): return Counter(str1) == Counter(str2) # or without having to import anything def is_anagram(str1, str2): return sorted(str1) == sorted(str2) print(is_anagram('geek', 'eegk'))print(is_anagram('geek', 'peek')) True False References:1.10 Neat Python Tricks Beginners Should Know2.30 Essential Python Tips And Tricks For Programmers RobertoPreste python-basics python-list python-string Python Technical Scripter python-list 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 How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python sum() function in Python
[ { "code": null, "e": 22297, "s": 22242, "text": "Top 4 Advanced Project Ideas to Enhance Your AI Skills" }, { "code": null, "e": 22358, "s": 22297, "text": "Top 10 Machine Learning Project Ideas That You Can Implement" }, { "code": null, "e": 22405, "s": 22358, "text": "5 Machine Learning Project Ideas for Beginners" }, { "code": null, "e": 22461, "s": 22405, "text": "7 Cool Python Project Ideas for Intermediate Developers" }, { "code": null, "e": 22495, "s": 22461, "text": "10 Interesting Python Cool Tricks" }, { "code": null, "e": 22547, "s": 22495, "text": "10 Essential Python Tips And Tricks For Programmers" }, { "code": null, "e": 22571, "s": 22547, "text": "Amazing hacks of Python" }, { "code": null, "e": 22620, "s": 22571, "text": "Python Input Methods for Competitive Programming" }, { "code": null, "e": 22667, "s": 22620, "text": "Vulnerability in input() function – Python 2.x" }, { "code": null, "e": 22706, "s": 22667, "text": "Python | Output using print() function" }, { "code": null, "e": 22776, "s": 22706, "text": "Important differences between Python 2.x and Python 3.x with examples" }, { "code": null, "e": 22792, "s": 22776, "text": "Python Keywords" }, { "code": null, "e": 22819, "s": 22792, "text": "Keywords in Python | Set 2" }, { "code": null, "e": 22850, "s": 22819, "text": "Namespaces and Scope in Python" }, { "code": null, "e": 22895, "s": 22850, "text": "Statement, Indentation and Comment in Python" }, { "code": null, "e": 22959, "s": 22895, "text": "How to assign values to variables in Python and other languages" }, { "code": null, "e": 22999, "s": 22959, "text": "How to print without newline in Python?" }, { "code": null, "e": 23031, "s": 22999, "text": "Python end parameter in print()" }, { "code": null, "e": 23065, "s": 23031, "text": "Python | sep parameter in print()" }, { "code": null, "e": 23092, "s": 23065, "text": "Python | Output Formatting" }, { "code": null, "e": 23122, "s": 23092, "text": "Python String format() Method" }, { "code": null, "e": 23142, "s": 23122, "text": "f-strings in Python" }, { "code": null, "e": 23164, "s": 23142, "text": "Enumerate() in Python" }, { "code": null, "e": 23194, "s": 23164, "text": "Iterate over a list in Python" }, { "code": null, "e": 23235, "s": 23194, "text": "Print lists in Python (4 Different Ways)" }, { "code": null, "e": 23285, "s": 23235, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 23307, "s": 23285, "text": "Python map() function" }, { "code": null, "e": 23330, "s": 23307, "text": "Taking input in Python" }, { "code": null, "e": 23374, "s": 23330, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 23402, "s": 23374, "text": "Read JSON file using Python" }, { "code": null, "e": 23457, "s": 23402, "text": "Top 4 Advanced Project Ideas to Enhance Your AI Skills" }, { "code": null, "e": 23518, "s": 23457, "text": "Top 10 Machine Learning Project Ideas That You Can Implement" }, { "code": null, "e": 23565, "s": 23518, "text": "5 Machine Learning Project Ideas for Beginners" }, { "code": null, "e": 23621, "s": 23565, "text": "7 Cool Python Project Ideas for Intermediate Developers" }, { "code": null, "e": 23655, "s": 23621, "text": "10 Interesting Python Cool Tricks" }, { "code": null, "e": 23707, "s": 23655, "text": "10 Essential Python Tips And Tricks For Programmers" }, { "code": null, "e": 23731, "s": 23707, "text": "Amazing hacks of Python" }, { "code": null, "e": 23780, "s": 23731, "text": "Python Input Methods for Competitive Programming" }, { "code": null, "e": 23827, "s": 23780, "text": "Vulnerability in input() function – Python 2.x" }, { "code": null, "e": 23866, "s": 23827, "text": "Python | Output using print() function" }, { "code": null, "e": 23936, "s": 23866, "text": "Important differences between Python 2.x and Python 3.x with examples" }, { "code": null, "e": 23952, "s": 23936, "text": "Python Keywords" }, { "code": null, "e": 23979, "s": 23952, "text": "Keywords in Python | Set 2" }, { "code": null, "e": 24010, "s": 23979, "text": "Namespaces and Scope in Python" }, { "code": null, "e": 24055, "s": 24010, "text": "Statement, Indentation and Comment in Python" }, { "code": null, "e": 24119, "s": 24055, "text": "How to assign values to variables in Python and other languages" }, { "code": null, "e": 24159, "s": 24119, "text": "How to print without newline in Python?" }, { "code": null, "e": 24191, "s": 24159, "text": "Python end parameter in print()" }, { "code": null, "e": 24225, "s": 24191, "text": "Python | sep parameter in print()" }, { "code": null, "e": 24252, "s": 24225, "text": "Python | Output Formatting" }, { "code": null, "e": 24282, "s": 24252, "text": "Python String format() Method" }, { "code": null, "e": 24302, "s": 24282, "text": "f-strings in Python" }, { "code": null, "e": 24324, "s": 24302, "text": "Enumerate() in Python" }, { "code": null, "e": 24354, "s": 24324, "text": "Iterate over a list in Python" }, { "code": null, "e": 24395, "s": 24354, "text": "Print lists in Python (4 Different Ways)" }, { "code": null, "e": 24445, "s": 24395, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 24467, "s": 24445, "text": "Python map() function" }, { "code": null, "e": 24490, "s": 24467, "text": "Taking input in Python" }, { "code": null, "e": 24534, "s": 24490, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 24562, "s": 24534, "text": "Read JSON file using Python" }, { "code": null, "e": 24586, "s": 24562, "text": "Difficulty Level :\nEasy" }, { "code": null, "e": 24811, "s": 24586, "text": "Python is one of the most preferred languages out there. Its brevity and high readability makes it so popular among all programmers.So here are few of the tips and tricks you can use to bring up your Python programming game." }, { "code": null, "e": 24848, "s": 24811, "text": "1. In-Place Swapping Of Two Numbers." }, { "code": "x, y = 10, 20print(x, y)x, y = y, xprint(x, y)", "e": 24895, "s": 24848, "text": null }, { "code": null, "e": 24908, "s": 24895, "text": "10 20\n20 10\n" }, { "code": null, "e": 24940, "s": 24908, "text": "2. Reversing a string in Python" }, { "code": "a = \"GeeksForGeeks\"print(\"Reverse is\", a[::-1])", "e": 24988, "s": 24940, "text": null }, { "code": null, "e": 25014, "s": 24988, "text": "Reverse is skeeGroFskeeG\n" }, { "code": null, "e": 25070, "s": 25014, "text": "3. Create a single string from all the elements in list" }, { "code": "a = [\"Geeks\", \"For\", \"Geeks\"]print(\" \".join(a))", "e": 25118, "s": 25070, "text": null }, { "code": null, "e": 25135, "s": 25118, "text": "Geeks For Geeks\n" }, { "code": null, "e": 25172, "s": 25135, "text": "4. Chaining Of Comparison Operators." }, { "code": "n = 10result = 1 < n < 20print(result)result = 1 > n <= 9print(result)", "e": 25243, "s": 25172, "text": null }, { "code": null, "e": 25255, "s": 25243, "text": "True\nFalse\n" }, { "code": null, "e": 25299, "s": 25255, "text": "4. Print The File Path Of Imported Modules." }, { "code": "import osimport socket print(os)print(socket)", "e": 25346, "s": 25299, "text": null }, { "code": null, "e": 25447, "s": 25346, "text": "<module 'os' from '/usr/lib/python3.5/os.py'>\n<module 'socket' from '/usr/lib/python3.5/socket.py'>\n" }, { "code": null, "e": 25474, "s": 25447, "text": "5. Use Of Enums In Python." }, { "code": "class MyName: Geeks, For, Geeks = range(3) print(MyName.Geeks)print(MyName.For)print(MyName.Geeks)", "e": 25577, "s": 25474, "text": null }, { "code": null, "e": 25584, "s": 25577, "text": "2\n1\n2\n" }, { "code": null, "e": 25626, "s": 25584, "text": "6. Return Multiple Values From Functions." }, { "code": "def x(): return 1, 2, 3, 4a, b, c, d = x() print(a, b, c, d)", "e": 25691, "s": 25626, "text": null }, { "code": null, "e": 25700, "s": 25691, "text": "1 2 3 4\n" }, { "code": null, "e": 25743, "s": 25700, "text": "7. Find The Most Frequent Value In A List." }, { "code": "test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]print(max(set(test), key = test.count))", "e": 25823, "s": 25743, "text": null }, { "code": null, "e": 25826, "s": 25823, "text": "4\n" }, { "code": null, "e": 25866, "s": 25826, "text": "8. Check The Memory Usage Of An Object." }, { "code": "import sysx = 1print(sys.getsizeof(x))", "e": 25905, "s": 25866, "text": null }, { "code": null, "e": 25909, "s": 25905, "text": "28\n" }, { "code": null, "e": 25934, "s": 25909, "text": "9. Print string N times." }, { "code": "n = 2a = \"GeeksforGeeks\"print(a * n)", "e": 25971, "s": 25934, "text": null }, { "code": null, "e": 25999, "s": 25971, "text": "GeeksforGeeksGeeksforGeeks\n" }, { "code": null, "e": 26038, "s": 25999, "text": "10. Checking if two words are anagrams" }, { "code": "from collections import Counterdef is_anagram(str1, str2): return Counter(str1) == Counter(str2) # or without having to import anything def is_anagram(str1, str2): return sorted(str1) == sorted(str2) print(is_anagram('geek', 'eegk'))print(is_anagram('geek', 'peek')) ", "e": 26320, "s": 26038, "text": null }, { "code": null, "e": 26332, "s": 26320, "text": "True\nFalse\n" }, { "code": null, "e": 26442, "s": 26332, "text": "References:1.10 Neat Python Tricks Beginners Should Know2.30 Essential Python Tips And Tricks For Programmers" }, { "code": null, "e": 26456, "s": 26442, "text": "RobertoPreste" }, { "code": null, "e": 26470, "s": 26456, "text": "python-basics" }, { "code": null, "e": 26482, "s": 26470, "text": "python-list" }, { "code": null, "e": 26496, "s": 26482, "text": "python-string" }, { "code": null, "e": 26503, "s": 26496, "text": "Python" }, { "code": null, "e": 26522, "s": 26503, "text": "Technical Scripter" }, { "code": null, "e": 26534, "s": 26522, "text": "python-list" }, { "code": null, "e": 26632, "s": 26534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26641, "s": 26632, "text": "Comments" }, { "code": null, "e": 26654, "s": 26641, "text": "Old Comments" }, { "code": null, "e": 26672, "s": 26654, "text": "Python Dictionary" }, { "code": null, "e": 26707, "s": 26672, "text": "Read a file line by line in Python" }, { "code": null, "e": 26739, "s": 26707, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26781, "s": 26739, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26807, "s": 26781, "text": "Python String | replace()" }, { "code": null, "e": 26850, "s": 26807, "text": "Python program to convert a list to string" }, { "code": null, "e": 26887, "s": 26850, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26931, "s": 26887, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26960, "s": 26931, "text": "*args and **kwargs in Python" } ]
Introduction of Relational Algebra in DBMS - GeeksforGeeks
28 Jun, 2021 Relational Algebra is procedural query language, which takes Relation as input and generate relation as output. Relational algebra mainly provides theoretical foundation for relational databases and SQL. Operators in Relational Algebra Projection (π)Projection is used to project required column data from a relation. Example : R (A B C) ---------- 1 2 4 2 2 3 3 2 3 4 3 4 π (BC) B C ----- 2 4 2 3 3 4 Note: By Default projection removes duplicate data. Selection (σ)Selection is used to select required tuples of the relations. for the above relationσ (c>3)Rwill select the tuples which have c more than 3. Note: selection operator only selects the required tuples but does not display them. For displaying, data projection operator is used. For the above selected tuples, to display we need to use projection also. π (σ (c>3)R ) will show following tuples. A B C ------- 1 2 4 4 3 4 Union (U)Union operation in relational algebra is same as union operation in set theory, only constraint is for union of two relation both relation must have same set of Attributes. Set Difference (-)Set Difference in relational algebra is same set difference operation as in set theory with the constraint that both relation should have same set of attributes. Rename (ρ)Rename is a unary operation used for renaming attributes of a relation.ρ (a/b)R will rename the attribute ‘b’ of relation by ‘a’. Cross Product (X) Cross product between two relations let say A and B, so cross product between A X B will results all the attributes of A followed by each attribute of B. Each record of A will pairs with every record of B. below is the example A B (Name Age Sex ) (Id Course) ------------------ ------------- Ram 14 M 1 DS Sona 15 F 2 DBMS kim 20 M A X B Name Age Sex Id Course --------------------------------- Ram 14 M 1 DS Ram 14 M 2 DBMS Sona 15 F 1 DS Sona 15 F 2 DBMS Kim 20 M 1 DS Kim 20 M 2 DBMS Note: if A has ‘n’ tuples and B has ‘m’ tuples then A X B will have ‘n*m’ tuples. Natural Join (⋈) Natural join is a binary operator. Natural join between two or more relations will result set of all combination of tuples where they have equal common attribute. Let us see below example Emp Dep (Name Id Dept_name ) (Dept_name Manager) ------------------------ --------------------- A 120 IT Sale Y B 125 HR Prod Z C 110 Sale IT A D 111 IT Emp ⋈ Dep Name Id Dept_name Manager ------------------------------- A 120 IT A C 110 Sale Y D 111 IT A Conditional Join Conditional join works similar to natural join. In natural join, by default condition is equal between common attribute while in conditional join we can specify the any condition such as greater than, less than, not equal Let us see below example R S (ID Sex Marks) (ID Sex Marks) ------------------ -------------------- 1 F 45 10 M 20 2 F 55 11 M 22 3 F 60 12 M 59 Join between R And S with condition R.marks >= S.marks R.ID R.Sex R.Marks S.ID S.Sex S.Marks ----------------------------------------------- 1 F 45 10 M 20 1 F 45 11 M 22 2 F 55 10 M 20 2 F 55 11 M 22 3 F 60 10 M 20 3 F 60 11 M 22 3 F 60 12 M 59 In depth articles:Basic-operators-in-relational-algebra Extended Relational Algebra OperatorsFollowing are Previous Year Gate Questionhttps://www.geeksforgeeks.org/gate-gate-cs-2012-question-50/https://www.geeksforgeeks.org/gate-gate-cs-2012-question-43/ References:https://en.wikipedia.org/wiki/Relational_algebra Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above DBMS-Relational Algebra DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL | Join (Inner, Left, Right and Full Joins) SQL | WITH clause SQL query to find second highest salary? SQL Trigger | Student Database Difference between Clustered and Non-clustered index SQL | Views Difference between DDL and DML in DBMS CTE in SQL SQL Interview Questions Second Normal Form (2NF)
[ { "code": null, "e": 29624, "s": 29596, "text": "\n28 Jun, 2021" }, { "code": null, "e": 29828, "s": 29624, "text": "Relational Algebra is procedural query language, which takes Relation as input and generate relation as output. Relational algebra mainly provides theoretical foundation for relational databases and SQL." }, { "code": null, "e": 29860, "s": 29828, "text": "Operators in Relational Algebra" }, { "code": null, "e": 29942, "s": 29860, "text": "Projection (π)Projection is used to project required column data from a relation." }, { "code": null, "e": 29952, "s": 29942, "text": "Example :" }, { "code": null, "e": 30033, "s": 29952, "text": " R \n (A B C) \n ----------\n 1 2 4\n 2 2 3\n 3 2 3\n 4 3 4" }, { "code": null, "e": 30067, "s": 30033, "text": "π (BC) \nB C\n-----\n2 4\n2 3\n3 4" }, { "code": null, "e": 30119, "s": 30067, "text": "Note: By Default projection removes duplicate data." }, { "code": null, "e": 30196, "s": 30121, "text": "Selection (σ)Selection is used to select required tuples of the relations." }, { "code": null, "e": 30275, "s": 30196, "text": "for the above relationσ (c>3)Rwill select the tuples which have c more than 3." }, { "code": null, "e": 30410, "s": 30275, "text": "Note: selection operator only selects the required tuples but does not display them. For displaying, data projection operator is used." }, { "code": null, "e": 30484, "s": 30410, "text": "For the above selected tuples, to display we need to use projection also." }, { "code": null, "e": 30560, "s": 30484, "text": " π (σ (c>3)R ) will show following tuples.\n\nA B C\n-------\n1 2 4\n4 3 4" }, { "code": null, "e": 30744, "s": 30562, "text": "Union (U)Union operation in relational algebra is same as union operation in set theory, only constraint is for union of two relation both relation must have same set of Attributes." }, { "code": null, "e": 30926, "s": 30746, "text": "Set Difference (-)Set Difference in relational algebra is same set difference operation as in set theory with the constraint that both relation should have same set of attributes." }, { "code": null, "e": 31068, "s": 30928, "text": "Rename (ρ)Rename is a unary operation used for renaming attributes of a relation.ρ (a/b)R will rename the attribute ‘b’ of relation by ‘a’." }, { "code": null, "e": 31088, "s": 31070, "text": "Cross Product (X)" }, { "code": null, "e": 31294, "s": 31088, "text": "Cross product between two relations let say A and B, so cross product between A X B will results all the attributes of A followed by each attribute of B. Each record of A will pairs with every record of B." }, { "code": null, "e": 31315, "s": 31294, "text": "below is the example" }, { "code": null, "e": 31842, "s": 31315, "text": " A B\n (Name Age Sex ) (Id Course) \n ------------------ -------------\n Ram 14 M 1 DS\n Sona 15 F 2 DBMS\n kim 20 M\n\n A X B\n Name Age Sex Id Course\n---------------------------------\n Ram 14 M 1 DS\n Ram 14 M 2 DBMS\n Sona 15 F 1 DS\n Sona 15 F 2 DBMS\n Kim 20 M 1 DS\n Kim 20 M 2 DBMS" }, { "code": null, "e": 31924, "s": 31842, "text": "Note: if A has ‘n’ tuples and B has ‘m’ tuples then A X B will have ‘n*m’ tuples." }, { "code": null, "e": 31943, "s": 31926, "text": "Natural Join (⋈)" }, { "code": null, "e": 32106, "s": 31943, "text": "Natural join is a binary operator. Natural join between two or more relations will result set of all combination of tuples where they have equal common attribute." }, { "code": null, "e": 32131, "s": 32106, "text": "Let us see below example" }, { "code": null, "e": 32655, "s": 32131, "text": " \n Emp Dep\n (Name Id Dept_name ) (Dept_name Manager)\n ------------------------ --------------------- \n A 120 IT Sale Y\n B 125 HR Prod Z\n C 110 Sale IT A\n D 111 IT \n\n\nEmp ⋈ Dep\n\nName Id Dept_name Manager\n-------------------------------\nA 120 IT A \nC 110 Sale Y\nD 111 IT A" }, { "code": null, "e": 32674, "s": 32657, "text": "Conditional Join" }, { "code": null, "e": 32896, "s": 32674, "text": "Conditional join works similar to natural join. In natural join, by default condition is equal between common attribute while in conditional join we can specify the any condition such as greater than, less than, not equal" }, { "code": null, "e": 32921, "s": 32896, "text": "Let us see below example" }, { "code": null, "e": 33663, "s": 32921, "text": " R S\n (ID Sex Marks) (ID Sex Marks)\n ------------------ -------------------- \n 1 F 45 10 M 20\n 2 F 55 11 M 22\n 3 F 60 12 M 59\n \nJoin between R And S with condition R.marks >= S.marks\n\nR.ID R.Sex R.Marks S.ID S.Sex S.Marks\n-----------------------------------------------\n1 F 45 10 M 20\n1 F 45 11 M 22\n2 F 55 10 M 20\n2 F 55 11 M 22\n3 F 60 10 M 20\n3 F 60 11 M 22\n3 F 60 12 M 59" }, { "code": null, "e": 33959, "s": 33663, "text": "In depth articles:Basic-operators-in-relational-algebra Extended Relational Algebra OperatorsFollowing are Previous Year Gate Questionhttps://www.geeksforgeeks.org/gate-gate-cs-2012-question-50/https://www.geeksforgeeks.org/gate-gate-cs-2012-question-43/" }, { "code": null, "e": 34019, "s": 33959, "text": "References:https://en.wikipedia.org/wiki/Relational_algebra" }, { "code": null, "e": 34143, "s": 34019, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 34167, "s": 34143, "text": "DBMS-Relational Algebra" }, { "code": null, "e": 34172, "s": 34167, "text": "DBMS" }, { "code": null, "e": 34177, "s": 34172, "text": "DBMS" }, { "code": null, "e": 34275, "s": 34177, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34284, "s": 34275, "text": "Comments" }, { "code": null, "e": 34297, "s": 34284, "text": "Old Comments" }, { "code": null, "e": 34344, "s": 34297, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 34362, "s": 34344, "text": "SQL | WITH clause" }, { "code": null, "e": 34403, "s": 34362, "text": "SQL query to find second highest salary?" }, { "code": null, "e": 34434, "s": 34403, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 34487, "s": 34434, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 34499, "s": 34487, "text": "SQL | Views" }, { "code": null, "e": 34538, "s": 34499, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 34549, "s": 34538, "text": "CTE in SQL" }, { "code": null, "e": 34573, "s": 34549, "text": "SQL Interview Questions" } ]
JSON - Comparison with XML
JSON and XML are human readable formats and are language independent. They both have support for creation, reading and decoding in real world situations. We can compare JSON with XML, based on the following factors − XML is more verbose than JSON, so it is faster to write JSON for programmers. XML is used to describe the structured data, which doesn't include arrays whereas JSON include arrays. JavaScript's eval method parses JSON. When applied to JSON, eval returns the described object. Individual examples of XML and JSON − { "company": Volkswagen, "name": "Vento", "price": 800000 } <car> <company>Volkswagen</company> <name>Vento</name> <price>800000</price> </car> 20 Lectures 1 hours Laurence Svekis 16 Lectures 1 hours Laurence Svekis 10 Lectures 1 hours Laurence Svekis 23 Lectures 2.5 hours Laurence Svekis 9 Lectures 48 mins Nilay Mehta 18 Lectures 2.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 1997, "s": 1780, "text": "JSON and XML are human readable formats and are language independent. They both have support for creation, reading and decoding in real world situations. We can compare JSON with XML, based on the following factors −" }, { "code": null, "e": 2075, "s": 1997, "text": "XML is more verbose than JSON, so it is faster to write JSON for programmers." }, { "code": null, "e": 2178, "s": 2075, "text": "XML is used to describe the structured data, which doesn't include arrays whereas JSON include arrays." }, { "code": null, "e": 2273, "s": 2178, "text": "JavaScript's eval method parses JSON. When applied to JSON, eval returns the described object." }, { "code": null, "e": 2311, "s": 2273, "text": "Individual examples of XML and JSON −" }, { "code": null, "e": 2380, "s": 2311, "text": "{\n \"company\": Volkswagen,\n \"name\": \"Vento\",\n \"price\": 800000\n}" }, { "code": null, "e": 2473, "s": 2380, "text": "<car>\n <company>Volkswagen</company>\n <name>Vento</name>\n <price>800000</price>\n</car>" }, { "code": null, "e": 2506, "s": 2473, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 2523, "s": 2506, "text": " Laurence Svekis" }, { "code": null, "e": 2556, "s": 2523, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 2573, "s": 2556, "text": " Laurence Svekis" }, { "code": null, "e": 2606, "s": 2573, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 2623, "s": 2606, "text": " Laurence Svekis" }, { "code": null, "e": 2658, "s": 2623, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2675, "s": 2658, "text": " Laurence Svekis" }, { "code": null, "e": 2706, "s": 2675, "text": "\n 9 Lectures \n 48 mins\n" }, { "code": null, "e": 2719, "s": 2706, "text": " Nilay Mehta" }, { "code": null, "e": 2754, "s": 2719, "text": "\n 18 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2777, "s": 2754, "text": " Stone River ELearning" }, { "code": null, "e": 2784, "s": 2777, "text": " Print" }, { "code": null, "e": 2795, "s": 2784, "text": " Add Notes" } ]
Chocolate Distribution Problem | Practice | GeeksforGeeks
Given an array A[ ] of positive integers of size N, where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are M students, the task is to distribute chocolate packets among M students such that : 1. Each student gets exactly one packet. 2. The difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student is minimum. Example 1: Input: N = 8, M = 5 A = {3, 4, 1, 9, 56, 7, 9, 12} Output: 6 Explanation: The minimum difference between maximum chocolates and minimum chocolates is 9 - 3 = 6 by choosing following M packets : {3, 4, 9, 7, 9}. Example 2: Input: N = 7, M = 3 A = {7, 3, 2, 4, 9, 12, 56} Output: 2 Explanation: The minimum difference between maximum chocolates and minimum chocolates is 4 - 2 = 2 by choosing following M packets : {3, 2, 4}. Your Task: You don't need to take any input or print anything. Your task is to complete the function findMinDiff() which takes array A[ ], N and M as input parameters and returns the minimum possible difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student. Expected Time Complexity: O(N*Log(N)) Expected Auxiliary Space: O(1) Constraints: 1 ≤ T ≤ 100 1 ≤ N ≤ 105 1 ≤ Ai ≤ 109 1 ≤ M ≤ N 0 hunterxsameer5 hours ago class Solution{ public: long long findMinDiff(vector<long long> a, long long n, long long m) { sort(a.begin(),a.end()); long long int i=0, j=m-1, ans=INT_MAX; while(j<n) { ans=min(ans,a[j++]-a[i++]); } return ans; } }; 0 abhishekjune20165 hours ago long long findMinDiff(vector<long long> a, long long n, long long m){ //code sort(a.begin(),a.end()); long long mina=INT_MAX; for(long long i=0;i+m-1<n;i++) { if((a[i+m-1]-a[i])<mina) { mina=(a[i+m-1]-a[i]); } } return mina; } 0 rajkirangupta9916 hours ago JAVA SOLUTION: - class Solution{ public long findMinDiff (ArrayList<Integer> a, int n, int m) { Collections.sort(a); int min=Integer.MAX_VALUE; int j=m-1; int i=0; while(j<n) { min=Math.min(min,a.get(j)-a.get(i)); j++; i++; } return min; }} 0 apoorvposwal992 days ago Short C++ solution long long findMinDiff(vector<long long> a, long long n, long long m){ sort(a.begin(),a.end()); long long diff=INT_MAX; for(long long i=0,j=m-1;j<n;i++,j++){ diff=min(diff,a[j]-a[i]); } return diff; } 0 ritwikshivam642 days ago In python:def findMinDiff(self, A,N,M): # code here A.sort() low = 0 high = M-1 diff = max(A) while(high<N): diff = min(diff,A[high]-A[low]) low+=1 high+=1 return diff 0 aditichoudharyit192 days ago long long findMinDiff(vector<long long> a, long long n, long long m){ sort(a.begin(),a.end()); long long int ans = INT_MAX; int i=0; int j=0; int p = 0; int q = 0; long long int x = 0; while(j<n) { if(j-i+1 < m) j++; else if(j-i+1 == m) { p = a[i]; q = a[j]; x = q-p; ans = min(x,ans); i++;j++; } } return ans; //(o(nlogn)) complexity } +1 vrajeshmodi993 days ago long long findMinDiff(vector<long long> a, long long n, long long m){ sort(a.begin(), a.end()); int i=0,j=m-1; long long diff =a[j]-a[i]; while(j<n){ diff = min(diff,a[j]-a[i]); i++; j++; } return diff; } 0 dipanshusharma93133 days ago // java solution class Solution{ public long findMinDiff (ArrayList<Integer> a, int n, int m) { // your code here Collections.sort(a); int p = 0, q = m-1; long ans = Long.MAX_VALUE; while(q<=n-1){ int diff = a.get(q) - a.get(p); ans = Math.min(diff, ans); q++; p++; } return ans; }} 0 roboto7o32oo33 days ago Simple C++ Solution ✨ ✨ class Solution { public: long long findMinDiff(vector<long long> a, long long n, long long m){ sort(a.begin(), a.end()); long long result = a[m-1] - a[0]; for(int i=0; i<n-m+1; i++){ result = min(result, a[m-1+i]-a[i]); } return result; } }; 0 hayatunisha16 days ago //C++ easy solution //time taken 0.86/2.73 long long findMinDiff(vector<long long> a, long long n, long long m){ //code sort(a.begin(),a.end()); int mindiff = INT_MAX; int tempmin = 0; for(int i = 0,j = m-1;j<n;i++,j++){ tempmin = a[j]-a[i]; mindiff = min(mindiff,tempmin); } return mindiff; } 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. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems 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.
[ { "code": null, "e": 684, "s": 238, "text": "Given an array A[ ] of positive integers of size N, where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are M students, the task is to distribute chocolate packets among M students such that :\n1. Each student gets exactly one packet.\n2. The difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student is minimum." }, { "code": null, "e": 695, "s": 684, "text": "Example 1:" }, { "code": null, "e": 909, "s": 695, "text": "Input:\nN = 8, M = 5\nA = {3, 4, 1, 9, 56, 7, 9, 12}\nOutput: 6\nExplanation: The minimum difference between \nmaximum chocolates and minimum chocolates \nis 9 - 3 = 6 by choosing following M packets :\n{3, 4, 9, 7, 9}.\n" }, { "code": null, "e": 920, "s": 909, "text": "Example 2:" }, { "code": null, "e": 1122, "s": 920, "text": "Input:\nN = 7, M = 3\nA = {7, 3, 2, 4, 9, 12, 56}\nOutput: 2\nExplanation: The minimum difference between\nmaximum chocolates and minimum chocolates\nis 4 - 2 = 2 by choosing following M packets :\n{3, 2, 4}." }, { "code": null, "e": 1442, "s": 1122, "text": "Your Task:\nYou don't need to take any input or print anything. Your task is to complete the function findMinDiff() which takes array A[ ], N and M as input parameters and returns the minimum possible difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student." }, { "code": null, "e": 1511, "s": 1442, "text": "Expected Time Complexity: O(N*Log(N))\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1571, "s": 1511, "text": "Constraints:\n1 ≤ T ≤ 100\n1 ≤ N ≤ 105\n1 ≤ Ai ≤ 109\n1 ≤ M ≤ N" }, { "code": null, "e": 1573, "s": 1571, "text": "0" }, { "code": null, "e": 1598, "s": 1573, "text": "hunterxsameer5 hours ago" }, { "code": null, "e": 1896, "s": 1598, "text": "class Solution{\n public:\n long long findMinDiff(vector<long long> a, long long n, long long m)\n {\n sort(a.begin(),a.end());\n long long int i=0, j=m-1, ans=INT_MAX;\n while(j<n)\n {\n ans=min(ans,a[j++]-a[i++]);\n }\n return ans;\n } \n};" }, { "code": null, "e": 1898, "s": 1896, "text": "0" }, { "code": null, "e": 1926, "s": 1898, "text": "abhishekjune20165 hours ago" }, { "code": null, "e": 2203, "s": 1926, "text": "long long findMinDiff(vector<long long> a, long long n, long long m){ //code sort(a.begin(),a.end()); long long mina=INT_MAX; for(long long i=0;i+m-1<n;i++) { if((a[i+m-1]-a[i])<mina) { mina=(a[i+m-1]-a[i]); } } return mina; } " }, { "code": null, "e": 2205, "s": 2203, "text": "0" }, { "code": null, "e": 2233, "s": 2205, "text": "rajkirangupta9916 hours ago" }, { "code": null, "e": 2250, "s": 2233, "text": "JAVA SOLUTION: -" }, { "code": null, "e": 2560, "s": 2252, "text": "class Solution{ public long findMinDiff (ArrayList<Integer> a, int n, int m) { Collections.sort(a); int min=Integer.MAX_VALUE; int j=m-1; int i=0; while(j<n) { min=Math.min(min,a.get(j)-a.get(i)); j++; i++; } return min; }}" }, { "code": null, "e": 2562, "s": 2560, "text": "0" }, { "code": null, "e": 2587, "s": 2562, "text": "apoorvposwal992 days ago" }, { "code": null, "e": 2606, "s": 2587, "text": "Short C++ solution" }, { "code": null, "e": 2839, "s": 2606, "text": "long long findMinDiff(vector<long long> a, long long n, long long m){\n sort(a.begin(),a.end());\n long long diff=INT_MAX;\n for(long long i=0,j=m-1;j<n;i++,j++){\n diff=min(diff,a[j]-a[i]);\n }\n return diff;\n } " }, { "code": null, "e": 2841, "s": 2839, "text": "0" }, { "code": null, "e": 2866, "s": 2841, "text": "ritwikshivam642 days ago" }, { "code": null, "e": 2906, "s": 2866, "text": "In python:def findMinDiff(self, A,N,M):" }, { "code": null, "e": 3107, "s": 2906, "text": " # code here A.sort() low = 0 high = M-1 diff = max(A) while(high<N): diff = min(diff,A[high]-A[low]) low+=1 high+=1 return diff" }, { "code": null, "e": 3109, "s": 3107, "text": "0" }, { "code": null, "e": 3138, "s": 3109, "text": "aditichoudharyit192 days ago" }, { "code": null, "e": 3692, "s": 3138, "text": "long long findMinDiff(vector<long long> a, long long n, long long m){\n sort(a.begin(),a.end());\n long long int ans = INT_MAX;\n int i=0;\n int j=0;\n int p = 0;\n int q = 0;\n long long int x = 0;\n while(j<n)\n {\n if(j-i+1 < m)\n j++;\n else if(j-i+1 == m)\n {\n p = a[i];\n q = a[j];\n x = q-p;\n ans = min(x,ans);\n i++;j++;\n \n }\n }\n return ans;\n //(o(nlogn)) complexity\n \n } " }, { "code": null, "e": 3695, "s": 3692, "text": "+1" }, { "code": null, "e": 3719, "s": 3695, "text": "vrajeshmodi993 days ago" }, { "code": null, "e": 4012, "s": 3719, "text": "long long findMinDiff(vector<long long> a, long long n, long long m){\n sort(a.begin(), a.end());\n int i=0,j=m-1;\n long long diff =a[j]-a[i];\n while(j<n){\n diff = min(diff,a[j]-a[i]);\n i++;\n j++;\n }\n return diff;\n }" }, { "code": null, "e": 4014, "s": 4012, "text": "0" }, { "code": null, "e": 4043, "s": 4014, "text": "dipanshusharma93133 days ago" }, { "code": null, "e": 4060, "s": 4043, "text": "// java solution" }, { "code": null, "e": 4414, "s": 4060, "text": "class Solution{ public long findMinDiff (ArrayList<Integer> a, int n, int m) { // your code here Collections.sort(a); int p = 0, q = m-1; long ans = Long.MAX_VALUE; while(q<=n-1){ int diff = a.get(q) - a.get(p); ans = Math.min(diff, ans); q++; p++; } return ans; }}" }, { "code": null, "e": 4416, "s": 4414, "text": "0" }, { "code": null, "e": 4440, "s": 4416, "text": "roboto7o32oo33 days ago" }, { "code": null, "e": 4464, "s": 4440, "text": "Simple C++ Solution ✨ ✨" }, { "code": null, "e": 4793, "s": 4466, "text": "class Solution {\n public:\n long long findMinDiff(vector<long long> a, long long n, long long m){\n sort(a.begin(), a.end());\n long long result = a[m-1] - a[0];\n \n for(int i=0; i<n-m+1; i++){\n result = min(result, a[m-1+i]-a[i]);\n }\n \n return result;\n } \n};" }, { "code": null, "e": 4795, "s": 4793, "text": "0" }, { "code": null, "e": 4818, "s": 4795, "text": "hayatunisha16 days ago" }, { "code": null, "e": 4838, "s": 4818, "text": "//C++ easy solution" }, { "code": null, "e": 4861, "s": 4838, "text": "//time taken 0.86/2.73" }, { "code": null, "e": 5173, "s": 4861, "text": "long long findMinDiff(vector<long long> a, long long n, long long m){ //code sort(a.begin(),a.end()); int mindiff = INT_MAX; int tempmin = 0; for(int i = 0,j = m-1;j<n;i++,j++){ tempmin = a[j]-a[i]; mindiff = min(mindiff,tempmin); } return mindiff; } " }, { "code": null, "e": 5319, "s": 5173, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5355, "s": 5319, "text": " Login to access your submissions. " }, { "code": null, "e": 5365, "s": 5355, "text": "\nProblem\n" }, { "code": null, "e": 5375, "s": 5365, "text": "\nContest\n" }, { "code": null, "e": 5438, "s": 5375, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5623, "s": 5438, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 5907, "s": 5623, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 6053, "s": 5907, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 6130, "s": 6053, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 6171, "s": 6130, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 6199, "s": 6171, "text": "Disable browser extensions." }, { "code": null, "e": 6270, "s": 6199, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 6457, "s": 6270, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
How to convert jQuery to JavaScript ?
03 Aug, 2021 JavaScript is an object orient programming language designed to make web development easier and more attractive. In most cases, JavaScript is used to create responsive, interactive elements for web pages, enhancing the user experience. 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. Selection: In jQuery, to select any element, we simply use the $() sign, but in JavaScript, to select any element, we can use querySelector() or querySelectorAll(). Program:// jQuery to select all instances// of class "select"$(".select"); // JavaScript to select only the// first instance of class "select"document.querySelector(".select"); // To select all the instances// of class "select" document.querySelectorAll(".select"); // jQuery to select all instances// of class "select"$(".select"); // JavaScript to select only the// first instance of class "select"document.querySelector(".select"); // To select all the instances// of class "select" document.querySelectorAll(".select"); Some other examples of selectors: To select the entire html: In jQuery:$("html") $("html") In JavaScript:document.querySelector(selector) document.querySelector(selector) To select the entire html body: In jQuery:$("body") $("body") In JavaScript:document.body document.body Class manipulation: Program:// To add a class "class-name" to a <p> tag// jQuery:$p.addClass(class-name) // JavaScript:p.classList.add(class-name) // To add a class "class-name" to a <p> tag// jQuery:$p.addClass(class-name) // JavaScript:p.classList.add(class-name) Below some other examples of manipulation: To add a class to an html element: In jQuery:$element.addClass(class-name) $element.addClass(class-name) In JavaScript:element.classList.add(class-name) element.classList.add(class-name) To remove a class to an html element: In jQuery:$element.removeClass(class-name) $element.removeClass(class-name) In JavaScript:element.classList.remove(class-name) element.classList.remove(class-name) To toggle a class to an html element: In jQuery:$element.toggleClass(class-name) $element.toggleClass(class-name) In JavaScript:element.classList.toggle(class-name) element.classList.toggle(class-name) To check whether an html element contains a class: In jQuery:$element.hasClass(class-name) $element.hasClass(class-name) In JavaScript:element.classList.has(class-name) element.classList.has(class-name) Event Listeners Program:// To add an event on button click // jQuery:/* handle click event */ $(".button").click( function(event) { }); // JavaScript:/* handle click event */ document.querySelector(".button") .addEventListener("click", (event) => {}); // To add an event on button click // jQuery:/* handle click event */ $(".button").click( function(event) { }); // JavaScript:/* handle click event */ document.querySelector(".button") .addEventListener("click", (event) => {}); CSS Styling: Program:// To give a margin of 10px to all the div// jQuery:$div.css({ margin: "10px" }) // JavaScript:div.style.margin= "10px" // To give a margin of 10px to all the div// jQuery:$div.css({ margin: "10px" }) // JavaScript:div.style.margin= "10px" 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. JavaScript-Misc jQuery-Misc JavaScript JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Aug, 2021" }, { "code": null, "e": 289, "s": 53, "text": "JavaScript is an object orient programming language designed to make web development easier and more attractive. In most cases, JavaScript is used to create responsive, interactive elements for web pages, enhancing the user experience." }, { "code": null, "e": 463, "s": 289, "text": "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." }, { "code": null, "e": 628, "s": 463, "text": "Selection: In jQuery, to select any element, we simply use the $() sign, but in JavaScript, to select any element, we can use querySelector() or querySelectorAll()." }, { "code": null, "e": 897, "s": 628, "text": "Program:// jQuery to select all instances// of class \"select\"$(\".select\"); // JavaScript to select only the// first instance of class \"select\"document.querySelector(\".select\"); // To select all the instances// of class \"select\" document.querySelectorAll(\".select\");" }, { "code": "// jQuery to select all instances// of class \"select\"$(\".select\"); // JavaScript to select only the// first instance of class \"select\"document.querySelector(\".select\"); // To select all the instances// of class \"select\" document.querySelectorAll(\".select\");", "e": 1158, "s": 897, "text": null }, { "code": null, "e": 1192, "s": 1158, "text": "Some other examples of selectors:" }, { "code": null, "e": 1219, "s": 1192, "text": "To select the entire html:" }, { "code": null, "e": 1239, "s": 1219, "text": "In jQuery:$(\"html\")" }, { "code": null, "e": 1249, "s": 1239, "text": "$(\"html\")" }, { "code": null, "e": 1296, "s": 1249, "text": "In JavaScript:document.querySelector(selector)" }, { "code": null, "e": 1329, "s": 1296, "text": "document.querySelector(selector)" }, { "code": null, "e": 1361, "s": 1329, "text": "To select the entire html body:" }, { "code": null, "e": 1381, "s": 1361, "text": "In jQuery:$(\"body\")" }, { "code": null, "e": 1391, "s": 1381, "text": "$(\"body\")" }, { "code": null, "e": 1419, "s": 1391, "text": "In JavaScript:document.body" }, { "code": null, "e": 1433, "s": 1419, "text": "document.body" }, { "code": null, "e": 1453, "s": 1433, "text": "Class manipulation:" }, { "code": null, "e": 1582, "s": 1453, "text": "Program:// To add a class \"class-name\" to a <p> tag// jQuery:$p.addClass(class-name) // JavaScript:p.classList.add(class-name)" }, { "code": "// To add a class \"class-name\" to a <p> tag// jQuery:$p.addClass(class-name) // JavaScript:p.classList.add(class-name)", "e": 1703, "s": 1582, "text": null }, { "code": null, "e": 1746, "s": 1703, "text": "Below some other examples of manipulation:" }, { "code": null, "e": 1781, "s": 1746, "text": "To add a class to an html element:" }, { "code": null, "e": 1821, "s": 1781, "text": "In jQuery:$element.addClass(class-name)" }, { "code": null, "e": 1851, "s": 1821, "text": "$element.addClass(class-name)" }, { "code": null, "e": 1899, "s": 1851, "text": "In JavaScript:element.classList.add(class-name)" }, { "code": null, "e": 1933, "s": 1899, "text": "element.classList.add(class-name)" }, { "code": null, "e": 1971, "s": 1933, "text": "To remove a class to an html element:" }, { "code": null, "e": 2014, "s": 1971, "text": "In jQuery:$element.removeClass(class-name)" }, { "code": null, "e": 2047, "s": 2014, "text": "$element.removeClass(class-name)" }, { "code": null, "e": 2098, "s": 2047, "text": "In JavaScript:element.classList.remove(class-name)" }, { "code": null, "e": 2135, "s": 2098, "text": "element.classList.remove(class-name)" }, { "code": null, "e": 2173, "s": 2135, "text": "To toggle a class to an html element:" }, { "code": null, "e": 2216, "s": 2173, "text": "In jQuery:$element.toggleClass(class-name)" }, { "code": null, "e": 2249, "s": 2216, "text": "$element.toggleClass(class-name)" }, { "code": null, "e": 2300, "s": 2249, "text": "In JavaScript:element.classList.toggle(class-name)" }, { "code": null, "e": 2337, "s": 2300, "text": "element.classList.toggle(class-name)" }, { "code": null, "e": 2388, "s": 2337, "text": "To check whether an html element contains a class:" }, { "code": null, "e": 2428, "s": 2388, "text": "In jQuery:$element.hasClass(class-name)" }, { "code": null, "e": 2458, "s": 2428, "text": "$element.hasClass(class-name)" }, { "code": null, "e": 2506, "s": 2458, "text": "In JavaScript:element.classList.has(class-name)" }, { "code": null, "e": 2540, "s": 2506, "text": "element.classList.has(class-name)" }, { "code": null, "e": 2556, "s": 2540, "text": "Event Listeners" }, { "code": null, "e": 2800, "s": 2556, "text": "Program:// To add an event on button click // jQuery:/* handle click event */ $(\".button\").click( function(event) { }); // JavaScript:/* handle click event */ document.querySelector(\".button\") .addEventListener(\"click\", (event) => {});" }, { "code": "// To add an event on button click // jQuery:/* handle click event */ $(\".button\").click( function(event) { }); // JavaScript:/* handle click event */ document.querySelector(\".button\") .addEventListener(\"click\", (event) => {});", "e": 3036, "s": 2800, "text": null }, { "code": null, "e": 3049, "s": 3036, "text": "CSS Styling:" }, { "code": null, "e": 3179, "s": 3049, "text": "Program:// To give a margin of 10px to all the div// jQuery:$div.css({ margin: \"10px\" }) // JavaScript:div.style.margin= \"10px\"" }, { "code": "// To give a margin of 10px to all the div// jQuery:$div.css({ margin: \"10px\" }) // JavaScript:div.style.margin= \"10px\"", "e": 3301, "s": 3179, "text": null }, { "code": null, "e": 3569, "s": 3301, "text": "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." }, { "code": null, "e": 3585, "s": 3569, "text": "JavaScript-Misc" }, { "code": null, "e": 3597, "s": 3585, "text": "jQuery-Misc" }, { "code": null, "e": 3608, "s": 3597, "text": "JavaScript" }, { "code": null, "e": 3615, "s": 3608, "text": "JQuery" }, { "code": null, "e": 3632, "s": 3615, "text": "Web Technologies" }, { "code": null, "e": 3659, "s": 3632, "text": "Web technologies Questions" } ]
HTTP headers | Accept-Charset
07 Nov, 2019 The HTTP Accept-Charset is a request type header. This header is used to indicate what character set are acceptable for the response from the server. The accept-charset header specifies the character encodings which are accepted by the client and this header also allows a user-agent to specify the charsets it supports.With the help of content negotiation it selects the type of encoding and then uses it to inform the client of its choice with the Content-Type response header, which is usually present in charset= parameter. Our Web-Browser usually doesn’t send this header, as transmitting it would allow fingerprinting and the default value for each resource is usually correct. If this Header is not present, a user-agent would have to specify each charset parameter for each text/* media type it accepted, e.g. Accept: text/html;charset=US-ASCII, text/html;charset=UTF-8, text/plain; charset=US-ASCII,text/plain;charset=UTF-8 Note: When the server fails to serve any character encoding form this request, it will send back a 406 Not Acceptable error code so to avoid this and provide better user experience if no Accept-Charset header is present, the default is that any character set is acceptable. Syntax: This is the for single charset.Accept-Charset: <charset> Accept-Charset: <charset> This syntax works to select multiple character sets with quality value.Accept-Charset: <charset>, <charset> ;q= Accept-Charset: <charset>, <charset> ;q= Directives: This header accepts three directives as mentioned above and described below: <charset>: This directive holds the charset type, any character encoding name, like UTF-32 ,UTF-16 or iso-8859-15. *: This directive is used as a wildcard for any character not mentioned in anywhere in header. Note: This ;q= defines the factor weighting, value placed in an order of preference expressed using a relative quality value. Examples: In this example single value is on Accept-Charset headerAccept-Charset: iso-8859-5 Accept-Charset: iso-8859-5 In this example double value is Accept-Charset headerAccept-Charset: utf-8, iso-8859-1;q=0.7 Accept-Charset: utf-8, iso-8859-1;q=0.7 In this example double value is Accept-Charset header with the second one using “ * “ wildcard to select all encodingsAccept-Charset: utf-8, iso-8859-1;q=0.7, *;q=0.9 Accept-Charset: utf-8, iso-8859-1;q=0.7, *;q=0.9 Supported Browsers: The browsers are not compatible with HTTP Accept-Charset header. HTTP-headers Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Nov, 2019" }, { "code": null, "e": 846, "s": 28, "text": "The HTTP Accept-Charset is a request type header. This header is used to indicate what character set are acceptable for the response from the server. The accept-charset header specifies the character encodings which are accepted by the client and this header also allows a user-agent to specify the charsets it supports.With the help of content negotiation it selects the type of encoding and then uses it to inform the client of its choice with the Content-Type response header, which is usually present in charset= parameter. Our Web-Browser usually doesn’t send this header, as transmitting it would allow fingerprinting and the default value for each resource is usually correct. If this Header is not present, a user-agent would have to specify each charset parameter for each text/* media type it accepted, e.g." }, { "code": null, "e": 961, "s": 846, "text": "Accept: text/html;charset=US-ASCII, text/html;charset=UTF-8, text/plain;\ncharset=US-ASCII,text/plain;charset=UTF-8" }, { "code": null, "e": 1235, "s": 961, "text": "Note: When the server fails to serve any character encoding form this request, it will send back a 406 Not Acceptable error code so to avoid this and provide better user experience if no Accept-Charset header is present, the default is that any character set is acceptable." }, { "code": null, "e": 1243, "s": 1235, "text": "Syntax:" }, { "code": null, "e": 1300, "s": 1243, "text": "This is the for single charset.Accept-Charset: <charset>" }, { "code": null, "e": 1326, "s": 1300, "text": "Accept-Charset: <charset>" }, { "code": null, "e": 1440, "s": 1326, "text": "This syntax works to select multiple character sets with quality value.Accept-Charset: <charset>, <charset> ;q= " }, { "code": null, "e": 1483, "s": 1440, "text": "Accept-Charset: <charset>, <charset> ;q= " }, { "code": null, "e": 1572, "s": 1483, "text": "Directives: This header accepts three directives as mentioned above and described below:" }, { "code": null, "e": 1687, "s": 1572, "text": "<charset>: This directive holds the charset type, any character encoding name, like UTF-32 ,UTF-16 or iso-8859-15." }, { "code": null, "e": 1782, "s": 1687, "text": "*: This directive is used as a wildcard for any character not mentioned in anywhere in header." }, { "code": null, "e": 1908, "s": 1782, "text": "Note: This ;q= defines the factor weighting, value placed in an order of preference expressed using a relative quality value." }, { "code": null, "e": 1918, "s": 1908, "text": "Examples:" }, { "code": null, "e": 2001, "s": 1918, "text": "In this example single value is on Accept-Charset headerAccept-Charset: iso-8859-5" }, { "code": null, "e": 2028, "s": 2001, "text": "Accept-Charset: iso-8859-5" }, { "code": null, "e": 2121, "s": 2028, "text": "In this example double value is Accept-Charset headerAccept-Charset: utf-8, iso-8859-1;q=0.7" }, { "code": null, "e": 2161, "s": 2121, "text": "Accept-Charset: utf-8, iso-8859-1;q=0.7" }, { "code": null, "e": 2328, "s": 2161, "text": "In this example double value is Accept-Charset header with the second one using “ * “ wildcard to select all encodingsAccept-Charset: utf-8, iso-8859-1;q=0.7, *;q=0.9" }, { "code": null, "e": 2377, "s": 2328, "text": "Accept-Charset: utf-8, iso-8859-1;q=0.7, *;q=0.9" }, { "code": null, "e": 2462, "s": 2377, "text": "Supported Browsers: The browsers are not compatible with HTTP Accept-Charset header." }, { "code": null, "e": 2475, "s": 2462, "text": "HTTP-headers" }, { "code": null, "e": 2482, "s": 2475, "text": "Picked" }, { "code": null, "e": 2499, "s": 2482, "text": "Web Technologies" } ]
Replace all occurrences of X by Y for Q queries in given Array
10 Nov, 2021 Given an array arr[] and an 2D array query[][] consisting of queries. For each query q, replace all occurrences of query[i][0] in arr[], with query[i][1]. Examples: Input: arr[] = {2, 2, 5, 1} query = {{2, 4}, {5, 2}}Output: {4, 4, 2, 1}Explanation: Following are the operations performed in the given array according to the queries given.For first query {2, 4}, replace all occurrences of 2 in arr[] with 4. arr[] will be updated as arr[] = {4, 4, 5, 1}. For second query {5, 2}, replace all occurrences of 5 with 2. arr[] will be updated as arr[] = {4, 4, 2, 1}. Input: arr[] ={2, 2, 5}, query = {{4, 5}, {2, 5}, {1, 3}, {2, 4}}Output: {5, 5, 5} Naive Approach: (Brute-Force solution) Naive approach would be to iterate through all the queries of query, and for each query[i][0], find all of its occurrences in arr[], and replace it with query[i][1]. Time Complexity: O(N*Q), where N is the size of arr[] and Q is size of query[][]. Auxiliary Space: O(1) Efficient Approach: A better solution would be to use a Hashmap, that stores indexes of the element in the array. Follow the steps below to solve the given problem. Initialize a hashmap = {}, and fill it up with array element as key, and list indicating its position in the array. Iterate through each query q of query[][].If q[0] is present in the hashmap,If q[1] is present in the hashmap, then extend the value of q[0] to the value of q[1] key.Else, add the value to q[1] key with the value of q[0] key.Delete the key-value pair for q[0] from the hashmap. If q[0] is present in the hashmap,If q[1] is present in the hashmap, then extend the value of q[0] to the value of q[1] key.Else, add the value to q[1] key with the value of q[0] key.Delete the key-value pair for q[0] from the hashmap. If q[1] is present in the hashmap, then extend the value of q[0] to the value of q[1] key. Else, add the value to q[1] key with the value of q[0] key. Delete the key-value pair for q[0] from the hashmap. Now, create a new variable map = {}, from the values of the hashmap. Interchange the key-value pairs, so that map will contain key-value pairs as index, and key value of hashmap. Using this map, we can now update the original array arr, by updating values at each position of arr, with the value from map. Below is the implementation of the above approach: C++ Python3 Javascript // C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to replace all the// occurrences of a number with// another given number for Q queriesvoid update(vector<int>& A, int N, vector<vector<int> >& Q){ // Creating a hashmap map<int, vector<int> > hashmap; for (int i = 0; i < N; ++i) { hashmap[A[i]].push_back(i); } // Iterating with q in given queries for (auto q : Q) { if (hashmap.count(q[0])) { if (hashmap.count(q[1])) hashmap[q[1]].insert(hashmap[q[1]].end(), hashmap[q[0]].begin(), hashmap[q[0]].end()); else hashmap[q[1]] = hashmap[q[0]]; hashmap.erase(q[0]); } } // Creating map to store key value pairs map<int, int> new_map; for (auto it = hashmap.begin(); it != hashmap.end(); ++it) { for (auto index : it->second) new_map[index] = it->first; } // Updating the main array with final values for (auto it = new_map.begin(); it != new_map.end(); ++it) A[it->first] = it->second;} // Driver Codeint main(){ vector<int> arr = { 2, 2, 5, 1 }; int N = arr.size(); vector<vector<int> > query = { { 2, 4 }, { 5, 2 } }; update(arr, N, query); for (int i = 0; i < N; ++i) { cout << arr[i] << " "; } return 0;} // This code is contributed by rakeshsahni # Python program for above approach # Function to replace all the# occurrences of a number with# another given number for Q queriesdef update(A, N, Q): # Creating a hashmap hashmap = {a:[] for a in A} for i in range(N): hashmap[A[i]].append(i) # Iterating with q in given queries for q in Q: if q[0] in hashmap: if q[1] in hashmap: hashmap[q[1]].extend(hashmap[q[0]]) else: hashmap[q[1]] = hashmap[q[0]] del hashmap[q[0]] # Creating map to store key value pairs new_map = {} for key, value in hashmap.items(): for index in value: new_map[index] = key # Updating the main array with final values for key in new_map.keys(): A[key] = new_map[key] # Driver Codeif __name__ == '__main__': arr = [2, 2, 5, 1] N = len(arr) query = [[2, 4], [5, 2]] update(arr, N, query) print(arr) <script>// Javascript program for above approach // Function to replace all the// occurrences of a number with// another given number for Q queriesfunction update(A, N, Q){ // Creating a hashmap let hashmap = new Map(); for(let i = 0; i < N; i++){ if(hashmap.has(A[i])){ let temp = hashmap.get(A[i]) temp.push(i) hashmap.set(A[i], temp) }else{ hashmap.set(A[i], [i]) } } // Iterating with q in given queries for(q of Q){ if(hashmap.has(q[0])){ if (hashmap.has(q[1])){ let temp = hashmap.get(q[1]); temp = [...temp, ...hashmap.get(q[0])] hashmap.set(q[1], temp); } else{ hashmap.set(q[1], hashmap.get(q[0])) } hashmap.delete(q[0]) } } // Creating map to store key value pairs let new_map = new Map() for(x of hashmap) for(index of x[1]) new_map.set(index, x[0]) // Updating the main array with final values for(key of new_map.keys()) A[key] = new_map.get(key) document.write(`[ ${A}] `)} // Driver Codelet arr = [2, 2, 5, 1]let N = arr.lengthlet query = [[2, 4], [5, 2]]update(arr, N, query) // This code is contributed by gfgking.</script> [4, 4, 2, 1] Time Complexity: O(max(N, Q)), where N is size of arr[] and Q is size of query[][]. Auxiliary Space: O(N) rakeshsahni gfgking simmytarika5 array-range-queries Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Nov, 2021" }, { "code": null, "e": 207, "s": 52, "text": "Given an array arr[] and an 2D array query[][] consisting of queries. For each query q, replace all occurrences of query[i][0] in arr[], with query[i][1]." }, { "code": null, "e": 217, "s": 207, "text": "Examples:" }, { "code": null, "e": 617, "s": 217, "text": "Input: arr[] = {2, 2, 5, 1} query = {{2, 4}, {5, 2}}Output: {4, 4, 2, 1}Explanation: Following are the operations performed in the given array according to the queries given.For first query {2, 4}, replace all occurrences of 2 in arr[] with 4. arr[] will be updated as arr[] = {4, 4, 5, 1}. For second query {5, 2}, replace all occurrences of 5 with 2. arr[] will be updated as arr[] = {4, 4, 2, 1}." }, { "code": null, "e": 700, "s": 617, "text": "Input: arr[] ={2, 2, 5}, query = {{4, 5}, {2, 5}, {1, 3}, {2, 4}}Output: {5, 5, 5}" }, { "code": null, "e": 906, "s": 700, "text": "Naive Approach: (Brute-Force solution) Naive approach would be to iterate through all the queries of query, and for each query[i][0], find all of its occurrences in arr[], and replace it with query[i][1]. " }, { "code": null, "e": 1010, "s": 906, "text": "Time Complexity: O(N*Q), where N is the size of arr[] and Q is size of query[][]. Auxiliary Space: O(1)" }, { "code": null, "e": 1176, "s": 1010, "text": "Efficient Approach: A better solution would be to use a Hashmap, that stores indexes of the element in the array. Follow the steps below to solve the given problem. " }, { "code": null, "e": 1292, "s": 1176, "text": "Initialize a hashmap = {}, and fill it up with array element as key, and list indicating its position in the array." }, { "code": null, "e": 1570, "s": 1292, "text": "Iterate through each query q of query[][].If q[0] is present in the hashmap,If q[1] is present in the hashmap, then extend the value of q[0] to the value of q[1] key.Else, add the value to q[1] key with the value of q[0] key.Delete the key-value pair for q[0] from the hashmap." }, { "code": null, "e": 1806, "s": 1570, "text": "If q[0] is present in the hashmap,If q[1] is present in the hashmap, then extend the value of q[0] to the value of q[1] key.Else, add the value to q[1] key with the value of q[0] key.Delete the key-value pair for q[0] from the hashmap." }, { "code": null, "e": 1897, "s": 1806, "text": "If q[1] is present in the hashmap, then extend the value of q[0] to the value of q[1] key." }, { "code": null, "e": 1957, "s": 1897, "text": "Else, add the value to q[1] key with the value of q[0] key." }, { "code": null, "e": 2010, "s": 1957, "text": "Delete the key-value pair for q[0] from the hashmap." }, { "code": null, "e": 2079, "s": 2010, "text": "Now, create a new variable map = {}, from the values of the hashmap." }, { "code": null, "e": 2189, "s": 2079, "text": "Interchange the key-value pairs, so that map will contain key-value pairs as index, and key value of hashmap." }, { "code": null, "e": 2316, "s": 2189, "text": "Using this map, we can now update the original array arr, by updating values at each position of arr, with the value from map." }, { "code": null, "e": 2368, "s": 2316, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2372, "s": 2368, "text": "C++" }, { "code": null, "e": 2380, "s": 2372, "text": "Python3" }, { "code": null, "e": 2391, "s": 2380, "text": "Javascript" }, { "code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to replace all the// occurrences of a number with// another given number for Q queriesvoid update(vector<int>& A, int N, vector<vector<int> >& Q){ // Creating a hashmap map<int, vector<int> > hashmap; for (int i = 0; i < N; ++i) { hashmap[A[i]].push_back(i); } // Iterating with q in given queries for (auto q : Q) { if (hashmap.count(q[0])) { if (hashmap.count(q[1])) hashmap[q[1]].insert(hashmap[q[1]].end(), hashmap[q[0]].begin(), hashmap[q[0]].end()); else hashmap[q[1]] = hashmap[q[0]]; hashmap.erase(q[0]); } } // Creating map to store key value pairs map<int, int> new_map; for (auto it = hashmap.begin(); it != hashmap.end(); ++it) { for (auto index : it->second) new_map[index] = it->first; } // Updating the main array with final values for (auto it = new_map.begin(); it != new_map.end(); ++it) A[it->first] = it->second;} // Driver Codeint main(){ vector<int> arr = { 2, 2, 5, 1 }; int N = arr.size(); vector<vector<int> > query = { { 2, 4 }, { 5, 2 } }; update(arr, N, query); for (int i = 0; i < N; ++i) { cout << arr[i] << \" \"; } return 0;} // This code is contributed by rakeshsahni", "e": 3854, "s": 2391, "text": null }, { "code": "# Python program for above approach # Function to replace all the# occurrences of a number with# another given number for Q queriesdef update(A, N, Q): # Creating a hashmap hashmap = {a:[] for a in A} for i in range(N): hashmap[A[i]].append(i) # Iterating with q in given queries for q in Q: if q[0] in hashmap: if q[1] in hashmap: hashmap[q[1]].extend(hashmap[q[0]]) else: hashmap[q[1]] = hashmap[q[0]] del hashmap[q[0]] # Creating map to store key value pairs new_map = {} for key, value in hashmap.items(): for index in value: new_map[index] = key # Updating the main array with final values for key in new_map.keys(): A[key] = new_map[key] # Driver Codeif __name__ == '__main__': arr = [2, 2, 5, 1] N = len(arr) query = [[2, 4], [5, 2]] update(arr, N, query) print(arr)", "e": 4790, "s": 3854, "text": null }, { "code": "<script>// Javascript program for above approach // Function to replace all the// occurrences of a number with// another given number for Q queriesfunction update(A, N, Q){ // Creating a hashmap let hashmap = new Map(); for(let i = 0; i < N; i++){ if(hashmap.has(A[i])){ let temp = hashmap.get(A[i]) temp.push(i) hashmap.set(A[i], temp) }else{ hashmap.set(A[i], [i]) } } // Iterating with q in given queries for(q of Q){ if(hashmap.has(q[0])){ if (hashmap.has(q[1])){ let temp = hashmap.get(q[1]); temp = [...temp, ...hashmap.get(q[0])] hashmap.set(q[1], temp); } else{ hashmap.set(q[1], hashmap.get(q[0])) } hashmap.delete(q[0]) } } // Creating map to store key value pairs let new_map = new Map() for(x of hashmap) for(index of x[1]) new_map.set(index, x[0]) // Updating the main array with final values for(key of new_map.keys()) A[key] = new_map.get(key) document.write(`[ ${A}] `)} // Driver Codelet arr = [2, 2, 5, 1]let N = arr.lengthlet query = [[2, 4], [5, 2]]update(arr, N, query) // This code is contributed by gfgking.</script>", "e": 6124, "s": 4790, "text": null }, { "code": null, "e": 6137, "s": 6124, "text": "[4, 4, 2, 1]" }, { "code": null, "e": 6245, "s": 6139, "text": "Time Complexity: O(max(N, Q)), where N is size of arr[] and Q is size of query[][]. Auxiliary Space: O(N)" }, { "code": null, "e": 6257, "s": 6245, "text": "rakeshsahni" }, { "code": null, "e": 6265, "s": 6257, "text": "gfgking" }, { "code": null, "e": 6278, "s": 6265, "text": "simmytarika5" }, { "code": null, "e": 6298, "s": 6278, "text": "array-range-queries" }, { "code": null, "e": 6305, "s": 6298, "text": "Arrays" }, { "code": null, "e": 6318, "s": 6305, "text": "Mathematical" }, { "code": null, "e": 6325, "s": 6318, "text": "Arrays" }, { "code": null, "e": 6338, "s": 6325, "text": "Mathematical" } ]
Python | GUI Calendar using Tkinter
08 Jul, 2021 Prerequisites:Introduction to Tkinter Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to create a GUI Calendar application using Tkinter, with a step-by-step guide. To create a Tkinter : Importing the module – Tkinter Create the main window (container) Add any number of widgets to the main window. Apply the event Trigger on the widgets. The GUI would look like below: Let’s create a GUI-based Calendar application that can show the calendar with respect to the given year, given by the user. Below is the implementation : Python3 # import all methods and classes from the tkinter from tkinter import * # import calendar moduleimport calendar # Function for showing the calendar of the given yeardef showCal() : # Create a GUI window new_gui = Tk() # Set the background colour of GUI window new_gui.config(background = "white") # set the name of tkinter GUI window new_gui.title("CALENDAR") # Set the configuration of GUI window new_gui.geometry("550x600") # get method returns current text as string fetch_year = int(year_field.get()) # calendar method of calendar module return # the calendar of the given year . cal_content = calendar.calendar(fetch_year) # Create a label for showing the content of the calendar cal_year = Label(new_gui, text = cal_content, font = "Consolas 10 bold") # grid method is used for placing # the widgets at respective positions # in table like structure. cal_year.grid(row = 5, column = 1, padx = 20) # start the GUI new_gui.mainloop() # Driver Codeif __name__ == "__main__" : # Create a GUI window gui = Tk() # Set the background colour of GUI window gui.config(background = "white") # set the name of tkinter GUI window gui.title("CALENDAR") # Set the configuration of GUI window gui.geometry("250x140") # Create a CALENDAR : label with specified font and size cal = Label(gui, text = "CALENDAR", bg = "dark gray", font = ("times", 28, 'bold')) # Create a Enter Year : label year = Label(gui, text = "Enter Year", bg = "light green") # Create a text entry box for filling or typing the information. year_field = Entry(gui) # Create a Show Calendar Button and attached to showCal function Show = Button(gui, text = "Show Calendar", fg = "Black", bg = "Red", command = showCal) # Create a Exit Button and attached to exit function Exit = Button(gui, text = "Exit", fg = "Black", bg = "Red", command = exit) # grid method is used for placing # the widgets at respective positions # in table like structure. cal.grid(row = 1, column = 1) year.grid(row = 2, column = 1) year_field.grid(row = 3, column = 1) Show.grid(row = 4, column = 1) Exit.grid(row = 6, column = 1) # start the GUI gui.mainloop() Output : abhigoya simranarora5sos clintra Python Tkinter-exercises Python-gui Python-tkinter Technical Scripter 2019 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2021" }, { "code": null, "e": 90, "s": 52, "text": "Prerequisites:Introduction to Tkinter" }, { "code": null, "e": 440, "s": 90, "text": "Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to create a GUI Calendar application using Tkinter, with a step-by-step guide. " }, { "code": null, "e": 463, "s": 440, "text": "To create a Tkinter : " }, { "code": null, "e": 494, "s": 463, "text": "Importing the module – Tkinter" }, { "code": null, "e": 529, "s": 494, "text": "Create the main window (container)" }, { "code": null, "e": 575, "s": 529, "text": "Add any number of widgets to the main window." }, { "code": null, "e": 615, "s": 575, "text": "Apply the event Trigger on the widgets." }, { "code": null, "e": 646, "s": 615, "text": "The GUI would look like below:" }, { "code": null, "e": 771, "s": 646, "text": "Let’s create a GUI-based Calendar application that can show the calendar with respect to the given year, given by the user. " }, { "code": null, "e": 801, "s": 771, "text": "Below is the implementation :" }, { "code": null, "e": 809, "s": 801, "text": "Python3" }, { "code": "# import all methods and classes from the tkinter from tkinter import * # import calendar moduleimport calendar # Function for showing the calendar of the given yeardef showCal() : # Create a GUI window new_gui = Tk() # Set the background colour of GUI window new_gui.config(background = \"white\") # set the name of tkinter GUI window new_gui.title(\"CALENDAR\") # Set the configuration of GUI window new_gui.geometry(\"550x600\") # get method returns current text as string fetch_year = int(year_field.get()) # calendar method of calendar module return # the calendar of the given year . cal_content = calendar.calendar(fetch_year) # Create a label for showing the content of the calendar cal_year = Label(new_gui, text = cal_content, font = \"Consolas 10 bold\") # grid method is used for placing # the widgets at respective positions # in table like structure. cal_year.grid(row = 5, column = 1, padx = 20) # start the GUI new_gui.mainloop() # Driver Codeif __name__ == \"__main__\" : # Create a GUI window gui = Tk() # Set the background colour of GUI window gui.config(background = \"white\") # set the name of tkinter GUI window gui.title(\"CALENDAR\") # Set the configuration of GUI window gui.geometry(\"250x140\") # Create a CALENDAR : label with specified font and size cal = Label(gui, text = \"CALENDAR\", bg = \"dark gray\", font = (\"times\", 28, 'bold')) # Create a Enter Year : label year = Label(gui, text = \"Enter Year\", bg = \"light green\") # Create a text entry box for filling or typing the information. year_field = Entry(gui) # Create a Show Calendar Button and attached to showCal function Show = Button(gui, text = \"Show Calendar\", fg = \"Black\", bg = \"Red\", command = showCal) # Create a Exit Button and attached to exit function Exit = Button(gui, text = \"Exit\", fg = \"Black\", bg = \"Red\", command = exit) # grid method is used for placing # the widgets at respective positions # in table like structure. cal.grid(row = 1, column = 1) year.grid(row = 2, column = 1) year_field.grid(row = 3, column = 1) Show.grid(row = 4, column = 1) Exit.grid(row = 6, column = 1) # start the GUI gui.mainloop() ", "e": 3170, "s": 809, "text": null }, { "code": null, "e": 3180, "s": 3170, "text": "Output : " }, { "code": null, "e": 3189, "s": 3180, "text": "abhigoya" }, { "code": null, "e": 3205, "s": 3189, "text": "simranarora5sos" }, { "code": null, "e": 3213, "s": 3205, "text": "clintra" }, { "code": null, "e": 3238, "s": 3213, "text": "Python Tkinter-exercises" }, { "code": null, "e": 3249, "s": 3238, "text": "Python-gui" }, { "code": null, "e": 3264, "s": 3249, "text": "Python-tkinter" }, { "code": null, "e": 3288, "s": 3264, "text": "Technical Scripter 2019" }, { "code": null, "e": 3295, "s": 3288, "text": "Python" }, { "code": null, "e": 3314, "s": 3295, "text": "Technical Scripter" }, { "code": null, "e": 3412, "s": 3314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3430, "s": 3412, "text": "Python Dictionary" }, { "code": null, "e": 3472, "s": 3430, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3498, "s": 3472, "text": "Python String | replace()" }, { "code": null, "e": 3530, "s": 3498, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3559, "s": 3530, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3586, "s": 3559, "text": "Python Classes and Objects" }, { "code": null, "e": 3607, "s": 3586, "text": "Python OOPs Concepts" }, { "code": null, "e": 3643, "s": 3607, "text": "Convert integer to string in Python" }, { "code": null, "e": 3666, "s": 3643, "text": "Introduction To PYTHON" } ]
Flutter – Tabs
13 Jun, 2022 Tabs are exactly what you think it is. It’s part of the UI that navigates the user through different routes(ie, pages) when clicked upon. The use of tabs in applications is standard practice. Flutter provides a simple way to create tab layouts using the material library. In this article, exploring we will be exploring the same in detail. To better understand the concept of tabs and their functionality in a Flutter app, let’s build a simple app with 5 tabs by following the below steps: Design a TabController. Add tabs to the app. Add content in each tab. let’s discuss them in detail. The TabController as the name suggests controls the functioning of each tab by syncing the tabs and the contents with each other. The DefaultTabController widget is one of the simplest ways to create tabs in flutter. It is done as shown below: Dart DefaultTabController( // total 5 tabs length: 5, child:); A tab in Flutter can be created using a TabBar widget as shown below: Dart home: DefaultTabController( length: 5, child: Scaffold( appBar: AppBar( bottom: const TabBar( tabs: [ Tab(icon: Icon(Icons.music_note)), Tab(icon: Icon(Icons.music_video)), Tab(icon: Icon(Icons.camera_alt)), Tab(icon: Icon(Icons.grade)), Tab(icon: Icon(Icons.email)), ], ), //TabBar The TabBarView widget can be used to specify the contents of each tab. For the sake of simplicity we will display the icons in the tab as the content of the tab as shown below: Dart body: const TabBarView( children: [ Icon(Icons.music_note), Icon(Icons.music_video), Icon(Icons.camera_alt), Icon(Icons.grade), Icon(Icons.email), ], ), // TabBarView Complete source code is as follows: Dart import 'package:flutter/material.dart'; // function to trigger the app buildvoid main() { runApp(const TabBarDemo());} // class to build the appclass TabBarDemo extends StatelessWidget { const TabBarDemo({Key? key}) : super(key: key); // build the app @override Widget build(BuildContext context) { return MaterialApp( home: DefaultTabController( length: 5, child: Scaffold( appBar: AppBar( bottom: const TabBar( tabs: [ Tab(icon: Icon(Icons.music_note)), Tab(icon: Icon(Icons.music_video)), Tab(icon: Icon(Icons.camera_alt)), Tab(icon: Icon(Icons.grade)), Tab(icon: Icon(Icons.email)), ], ), // TabBar title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), // AppBar body: const TabBarView( children: [ Icon(Icons.music_note), Icon(Icons.music_video), Icon(Icons.camera_alt), Icon(Icons.grade), Icon(Icons.email), ], ), // TabBarView ), // Scaffold ), // DefaultTabController ); // MaterialApp }} Output: gaurivankudre ankit_kumar_ android Flutter Flutter UI-components Flutter-widgets Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Custom Bottom Navigation Bar Splash Screen in Flutter Flutter - Asset Image Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - Stack Widget Flutter - Search Bar
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 392, "s": 52, "text": "Tabs are exactly what you think it is. It’s part of the UI that navigates the user through different routes(ie, pages) when clicked upon. The use of tabs in applications is standard practice. Flutter provides a simple way to create tab layouts using the material library. In this article, exploring we will be exploring the same in detail." }, { "code": null, "e": 542, "s": 392, "text": "To better understand the concept of tabs and their functionality in a Flutter app, let’s build a simple app with 5 tabs by following the below steps:" }, { "code": null, "e": 566, "s": 542, "text": "Design a TabController." }, { "code": null, "e": 587, "s": 566, "text": "Add tabs to the app." }, { "code": null, "e": 612, "s": 587, "text": "Add content in each tab." }, { "code": null, "e": 642, "s": 612, "text": "let’s discuss them in detail." }, { "code": null, "e": 886, "s": 642, "text": "The TabController as the name suggests controls the functioning of each tab by syncing the tabs and the contents with each other. The DefaultTabController widget is one of the simplest ways to create tabs in flutter. It is done as shown below:" }, { "code": null, "e": 891, "s": 886, "text": "Dart" }, { "code": "DefaultTabController( // total 5 tabs length: 5, child:);", "e": 952, "s": 891, "text": null }, { "code": null, "e": 1022, "s": 952, "text": "A tab in Flutter can be created using a TabBar widget as shown below:" }, { "code": null, "e": 1027, "s": 1022, "text": "Dart" }, { "code": "home: DefaultTabController( length: 5, child: Scaffold( appBar: AppBar( bottom: const TabBar( tabs: [ Tab(icon: Icon(Icons.music_note)), Tab(icon: Icon(Icons.music_video)), Tab(icon: Icon(Icons.camera_alt)), Tab(icon: Icon(Icons.grade)), Tab(icon: Icon(Icons.email)), ], ), //TabBar", "e": 1384, "s": 1027, "text": null }, { "code": null, "e": 1561, "s": 1384, "text": "The TabBarView widget can be used to specify the contents of each tab. For the sake of simplicity we will display the icons in the tab as the content of the tab as shown below:" }, { "code": null, "e": 1566, "s": 1561, "text": "Dart" }, { "code": "body: const TabBarView( children: [ Icon(Icons.music_note), Icon(Icons.music_video), Icon(Icons.camera_alt), Icon(Icons.grade), Icon(Icons.email), ], ), // TabBarView", "e": 1813, "s": 1566, "text": null }, { "code": null, "e": 1850, "s": 1813, "text": "Complete source code is as follows: " }, { "code": null, "e": 1855, "s": 1850, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; // function to trigger the app buildvoid main() { runApp(const TabBarDemo());} // class to build the appclass TabBarDemo extends StatelessWidget { const TabBarDemo({Key? key}) : super(key: key); // build the app @override Widget build(BuildContext context) { return MaterialApp( home: DefaultTabController( length: 5, child: Scaffold( appBar: AppBar( bottom: const TabBar( tabs: [ Tab(icon: Icon(Icons.music_note)), Tab(icon: Icon(Icons.music_video)), Tab(icon: Icon(Icons.camera_alt)), Tab(icon: Icon(Icons.grade)), Tab(icon: Icon(Icons.email)), ], ), // TabBar title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), // AppBar body: const TabBarView( children: [ Icon(Icons.music_note), Icon(Icons.music_video), Icon(Icons.camera_alt), Icon(Icons.grade), Icon(Icons.email), ], ), // TabBarView ), // Scaffold ), // DefaultTabController ); // MaterialApp }}", "e": 3078, "s": 1855, "text": null }, { "code": null, "e": 3087, "s": 3078, "text": " Output:" }, { "code": null, "e": 3103, "s": 3089, "text": "gaurivankudre" }, { "code": null, "e": 3116, "s": 3103, "text": "ankit_kumar_" }, { "code": null, "e": 3124, "s": 3116, "text": "android" }, { "code": null, "e": 3132, "s": 3124, "text": "Flutter" }, { "code": null, "e": 3154, "s": 3132, "text": "Flutter UI-components" }, { "code": null, "e": 3170, "s": 3154, "text": "Flutter-widgets" }, { "code": null, "e": 3175, "s": 3170, "text": "Dart" }, { "code": null, "e": 3183, "s": 3175, "text": "Flutter" }, { "code": null, "e": 3281, "s": 3183, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3313, "s": 3281, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 3341, "s": 3313, "text": "Listview.builder in Flutter" }, { "code": null, "e": 3380, "s": 3341, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 3405, "s": 3380, "text": "Splash Screen in Flutter" }, { "code": null, "e": 3427, "s": 3405, "text": "Flutter - Asset Image" }, { "code": null, "e": 3459, "s": 3427, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 3498, "s": 3459, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 3524, "s": 3498, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 3547, "s": 3524, "text": "Flutter - Stack Widget" } ]
Python – Ways to remove multiple empty spaces from string List
30 Jun, 2022 Sometimes, while working with Python strings, we have a problem in which we need to perform the removal of empty spaces in Strings. The problem of filtering a single space is easier. But sometimes we are unaware of number of spaces. This has application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + strip() This is a way in which we can perform this task. In this, we strip the strings using strip(), it reduces to single space and then it can be tested for NULL value. Returns True if string is single space and hence helps in filtering. Python3 # Python3 code to demonstrate working of# Remove multiple empty spaces from string List# Using loop + strip() # initializing listtest_list = ['gfg', ' ', ' ', 'is', ' ', 'best'] # printing original listprint("The original list is : " + str(test_list)) # Remove multiple empty spaces from string List# Using loop + strip()res = []for ele in test_list: if ele.strip(): res.append(ele) # printing resultprint("List after filtering non-empty strings : " + str(res)) The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best'] List after filtering non-empty strings : ['gfg', 'is', 'best'] Method #2 : Using list comprehension + strip() The combination of above functions can also be used to perform this task. In this, we employ one-liner approach to perform this task instead of using loop. Python3 # Python3 code to demonstrate working of# Remove multiple empty spaces from string List# Using list comprehension + strip() # initializing listtest_list = ['gfg', ' ', ' ', 'is', ' ', 'best'] # printing original listprint("The original list is : " + str(test_list)) # Remove multiple empty spaces from string List# Using list comprehension + strip()res = [ele for ele in test_list if ele.strip()] # printing resultprint("List after filtering non-empty strings : " + str(res)) The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best'] List after filtering non-empty strings : ['gfg', 'is', 'best'] Method #3 : Using find() Python3 # Python3 code to demonstrate working of# Remove multiple empty spaces from string List# Using find() # initializing listtest_list = ['gfg', ' ', ' ', 'is', ' ', 'best'] # printing original listprint("The original list is : " + str(test_list)) # Remove multiple empty spaces from string List# Using find()res = []for ele in test_list: if ele.find(' ')==-1: res.append(ele) # printing resultprint("List after filtering non-empty strings : " + str(res)) The original list is : ['gfg', ' ', ' ', 'is', '\t\t ', 'best'] List after filtering non-empty strings : ['gfg', 'is', 'best'] kogantibhavya Python list-programs Python string-programs Python Python Programs 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() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2022" }, { "code": null, "e": 628, "s": 28, "text": "Sometimes, while working with Python strings, we have a problem in which we need to perform the removal of empty spaces in Strings. The problem of filtering a single space is easier. But sometimes we are unaware of number of spaces. This has application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + strip() This is a way in which we can perform this task. In this, we strip the strings using strip(), it reduces to single space and then it can be tested for NULL value. Returns True if string is single space and hence helps in filtering. " }, { "code": null, "e": 636, "s": 628, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Remove multiple empty spaces from string List# Using loop + strip() # initializing listtest_list = ['gfg', ' ', ' ', 'is', ' ', 'best'] # printing original listprint(\"The original list is : \" + str(test_list)) # Remove multiple empty spaces from string List# Using loop + strip()res = []for ele in test_list: if ele.strip(): res.append(ele) # printing resultprint(\"List after filtering non-empty strings : \" + str(res))", "e": 1125, "s": 636, "text": null }, { "code": null, "e": 1261, "s": 1125, "text": "The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best']\nList after filtering non-empty strings : ['gfg', 'is', 'best']" }, { "code": null, "e": 1467, "s": 1261, "text": " Method #2 : Using list comprehension + strip() The combination of above functions can also be used to perform this task. In this, we employ one-liner approach to perform this task instead of using loop. " }, { "code": null, "e": 1475, "s": 1467, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Remove multiple empty spaces from string List# Using list comprehension + strip() # initializing listtest_list = ['gfg', ' ', ' ', 'is', ' ', 'best'] # printing original listprint(\"The original list is : \" + str(test_list)) # Remove multiple empty spaces from string List# Using list comprehension + strip()res = [ele for ele in test_list if ele.strip()] # printing resultprint(\"List after filtering non-empty strings : \" + str(res))", "e": 1968, "s": 1475, "text": null }, { "code": null, "e": 2104, "s": 1968, "text": "The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best']\nList after filtering non-empty strings : ['gfg', 'is', 'best']" }, { "code": null, "e": 2129, "s": 2104, "text": "Method #3 : Using find()" }, { "code": null, "e": 2137, "s": 2129, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Remove multiple empty spaces from string List# Using find() # initializing listtest_list = ['gfg', ' ', ' ', 'is', ' ', 'best'] # printing original listprint(\"The original list is : \" + str(test_list)) # Remove multiple empty spaces from string List# Using find()res = []for ele in test_list: if ele.find(' ')==-1: res.append(ele) # printing resultprint(\"List after filtering non-empty strings : \" + str(res))", "e": 2611, "s": 2137, "text": null }, { "code": null, "e": 2738, "s": 2611, "text": "The original list is : ['gfg', ' ', ' ', 'is', '\\t\\t ', 'best']\nList after filtering non-empty strings : ['gfg', 'is', 'best']" }, { "code": null, "e": 2752, "s": 2738, "text": "kogantibhavya" }, { "code": null, "e": 2773, "s": 2752, "text": "Python list-programs" }, { "code": null, "e": 2796, "s": 2773, "text": "Python string-programs" }, { "code": null, "e": 2803, "s": 2796, "text": "Python" }, { "code": null, "e": 2819, "s": 2803, "text": "Python Programs" }, { "code": null, "e": 2917, "s": 2819, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2935, "s": 2917, "text": "Python Dictionary" }, { "code": null, "e": 2977, "s": 2935, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2999, "s": 2977, "text": "Enumerate() in Python" }, { "code": null, "e": 3034, "s": 2999, "text": "Read a file line by line in Python" }, { "code": null, "e": 3060, "s": 3034, "text": "Python String | replace()" }, { "code": null, "e": 3103, "s": 3060, "text": "Python program to convert a list to string" }, { "code": null, "e": 3125, "s": 3103, "text": "Defaultdict in Python" }, { "code": null, "e": 3164, "s": 3125, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3202, "s": 3164, "text": "Python | Convert a list to dictionary" } ]
How do I drop a primary key in MySQL?
To drop a primary key, use ALTER at first to alter the table. With that, use DROP to drop the key as in the below alter table yourTableName drop primary key; Let us first create a table − mysql> create table DemoTable -> ( -> StudentId int NOT NULL, -> StudentName varchar(20), -> StudentAge int, -> primary key(StudentId) -> ); Query OK, 0 rows affected (0.48 sec) Here is the query to check the description of table − mysql> desc DemoTable; This will produce the following output− +-------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+-------+ | StudentId | int(11) | NO | PRI | NULL | | | StudentName | varchar(20) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | +-------------+-------------+------+-----+---------+-------+ 3 rows in set (0.00 sec) Following is the query to drop a primary key in MySQL − mysql> alter table DemoTable drop primary key; Query OK, 0 rows affected (1.70 sec) Records: 0 Duplicates: 0 Warnings: 0 Let us check the table description once again − mysql> desc DemoTable; This will produce the following output − +-------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+-------+ | StudentId | int(11) | NO | | NULL | | | StudentName | varchar(20) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | +-------------+-------------+------+-----+---------+-------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1301, "s": 1187, "text": "To drop a primary key, use ALTER at first to alter the table. With that, use DROP to drop the key as in the below" }, { "code": null, "e": 1345, "s": 1301, "text": "alter table yourTableName drop primary key;" }, { "code": null, "e": 1375, "s": 1345, "text": "Let us first create a table −" }, { "code": null, "e": 1571, "s": 1375, "text": "mysql> create table DemoTable\n -> (\n -> StudentId int NOT NULL,\n -> StudentName varchar(20),\n -> StudentAge int,\n -> primary key(StudentId)\n -> );\nQuery OK, 0 rows affected (0.48 sec)" }, { "code": null, "e": 1625, "s": 1571, "text": "Here is the query to check the description of table −" }, { "code": null, "e": 1648, "s": 1625, "text": "mysql> desc DemoTable;" }, { "code": null, "e": 1688, "s": 1648, "text": "This will produce the following output−" }, { "code": null, "e": 2140, "s": 1688, "text": "+-------------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------+-------------+------+-----+---------+-------+\n| StudentId | int(11) | NO | PRI | NULL | |\n| StudentName | varchar(20) | YES | | NULL | |\n| StudentAge | int(11) | YES | | NULL | |\n+-------------+-------------+------+-----+---------+-------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2196, "s": 2140, "text": "Following is the query to drop a primary key in MySQL −" }, { "code": null, "e": 2317, "s": 2196, "text": "mysql> alter table DemoTable drop primary key;\nQuery OK, 0 rows affected (1.70 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2365, "s": 2317, "text": "Let us check the table description once again −" }, { "code": null, "e": 2388, "s": 2365, "text": "mysql> desc DemoTable;" }, { "code": null, "e": 2429, "s": 2388, "text": "This will produce the following output −" }, { "code": null, "e": 2881, "s": 2429, "text": "+-------------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------+-------------+------+-----+---------+-------+\n| StudentId | int(11) | NO | | NULL | |\n| StudentName | varchar(20) | YES | | NULL | |\n| StudentAge | int(11) | YES | | NULL | |\n+-------------+-------------+------+-----+---------+-------+\n3 rows in set (0.00 sec)" } ]
W3.CSS Containers and Panels
02 Mar, 2021 W3.CSS provides web developers with the two most useful classes i.e. container and panels. They are used to place content together with same font-color, background-color, font-size, font-family, etc. w3-container: This class is used to add 16px padding on both the left and right side of the element. It can be used with all the HTML5 container elements i.e. div, article, section, header, footer, etc. All the elements inside this class share the same font-size, font-color, padding, alignment, etc. Example: Using the w3-container class in the HTML page. HTML <!DOCTYPE html><html> <head> <!-- Adding W3.CSS file through external link --> <link rel="stylesheet" href= "https://www.w3schools.com/w3css/4/w3.css"> </head> <body> <!-- w3-container is used to add 16px padding to any HTML element --> <!-- w3-center is used to set the content of the element to the center. --> <div class="w3-container w3-center"> <!-- w3-text-green sets the text color to green. --> <!-- w3-xxlarge sets font size to 32px. --> <h2 class="w3-text-green w3-xxlarge"> Welcome To GFG </h2> </div> <!-- w3-pink sets the background color pink --> <div class="w3-container w3-pink"> <!-- w3-text-white sets the text color to white --> <p class="w3-text-white "> GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc. </p> </div></body> </html> Output: w3-panel: This class adds 16px padding on all sides i.e. top, right, bottom, left. It can also be used with all the HTML5 container elements i.e. div, article, section, header, footer, etc. All the elements inside this class share the same font-size, font-color, padding, alignment, etc. Example: Using the w3-panel class in the HTML page. HTML <!DOCTYPE html><html> <head> <!-- Adding W3.CSS file through external link --> <link rel="stylesheet" href= "https://www.w3schools.com/w3css/4/w3.css"> </head> <body> <!-- w3-container is used to add 16px padding to any HTML element. --> <!-- w3-center is used to set the content of the element to the center. --> <div class="w3-container w3-center"> <!-- w3-text-green sets the text color to green. --> <!-- w3-xxlarge sets font size to 32px. --> <h2 class="w3-text-green w3-xxlarge"> Welcome To GFG </h2> </div> <!-- w3-pink sets the background color pink --> <!-- w3-panel is used to 16px padding from all the direction --> <div class="w3-panel w3-pink"> <!-- w3-text-white sets the text colur to white. --> <p class="w3-text-white"> GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc. </p> </div></body> </html> Output: You can see that the gap between heading and paragraph is increased because we have w3-panel class. Note: If you use paragraph tag then automatically padding is added between the content and the division. You can use panels and containers to make styles like notes, quotes, alerts, cards and many more. W3.CSS CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Mar, 2021" }, { "code": null, "e": 228, "s": 28, "text": "W3.CSS provides web developers with the two most useful classes i.e. container and panels. They are used to place content together with same font-color, background-color, font-size, font-family, etc." }, { "code": null, "e": 529, "s": 228, "text": "w3-container: This class is used to add 16px padding on both the left and right side of the element. It can be used with all the HTML5 container elements i.e. div, article, section, header, footer, etc. All the elements inside this class share the same font-size, font-color, padding, alignment, etc." }, { "code": null, "e": 585, "s": 529, "text": "Example: Using the w3-container class in the HTML page." }, { "code": null, "e": 590, "s": 585, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Adding W3.CSS file through external link --> <link rel=\"stylesheet\" href= \"https://www.w3schools.com/w3css/4/w3.css\"> </head> <body> <!-- w3-container is used to add 16px padding to any HTML element --> <!-- w3-center is used to set the content of the element to the center. --> <div class=\"w3-container w3-center\"> <!-- w3-text-green sets the text color to green. --> <!-- w3-xxlarge sets font size to 32px. --> <h2 class=\"w3-text-green w3-xxlarge\"> Welcome To GFG </h2> </div> <!-- w3-pink sets the background color pink --> <div class=\"w3-container w3-pink\"> <!-- w3-text-white sets the text color to white --> <p class=\"w3-text-white \"> GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc. </p> </div></body> </html>", "e": 1666, "s": 590, "text": null }, { "code": null, "e": 1674, "s": 1666, "text": "Output:" }, { "code": null, "e": 1962, "s": 1674, "text": "w3-panel: This class adds 16px padding on all sides i.e. top, right, bottom, left. It can also be used with all the HTML5 container elements i.e. div, article, section, header, footer, etc. All the elements inside this class share the same font-size, font-color, padding, alignment, etc." }, { "code": null, "e": 2014, "s": 1962, "text": "Example: Using the w3-panel class in the HTML page." }, { "code": null, "e": 2019, "s": 2014, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Adding W3.CSS file through external link --> <link rel=\"stylesheet\" href= \"https://www.w3schools.com/w3css/4/w3.css\"> </head> <body> <!-- w3-container is used to add 16px padding to any HTML element. --> <!-- w3-center is used to set the content of the element to the center. --> <div class=\"w3-container w3-center\"> <!-- w3-text-green sets the text color to green. --> <!-- w3-xxlarge sets font size to 32px. --> <h2 class=\"w3-text-green w3-xxlarge\"> Welcome To GFG </h2> </div> <!-- w3-pink sets the background color pink --> <!-- w3-panel is used to 16px padding from all the direction --> <div class=\"w3-panel w3-pink\"> <!-- w3-text-white sets the text colur to white. --> <p class=\"w3-text-white\"> GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc. </p> </div></body> </html>", "e": 3168, "s": 2019, "text": null }, { "code": null, "e": 3176, "s": 3168, "text": "Output:" }, { "code": null, "e": 3276, "s": 3176, "text": "You can see that the gap between heading and paragraph is increased because we have w3-panel class." }, { "code": null, "e": 3282, "s": 3276, "text": "Note:" }, { "code": null, "e": 3381, "s": 3282, "text": "If you use paragraph tag then automatically padding is added between the content and the division." }, { "code": null, "e": 3479, "s": 3381, "text": "You can use panels and containers to make styles like notes, quotes, alerts, cards and many more." }, { "code": null, "e": 3486, "s": 3479, "text": "W3.CSS" }, { "code": null, "e": 3490, "s": 3486, "text": "CSS" }, { "code": null, "e": 3507, "s": 3490, "text": "Web Technologies" }, { "code": null, "e": 3605, "s": 3507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3644, "s": 3605, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3683, "s": 3644, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3722, "s": 3683, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3759, "s": 3722, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 3788, "s": 3759, "text": "Form validation using jQuery" }, { "code": null, "e": 3821, "s": 3788, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3882, "s": 3821, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3925, "s": 3882, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3997, "s": 3925, "text": "Differences between Functional Components and Class Components in React" } ]
How to embed Matplotlib charts in Tkinter GUI?
10 Jul, 2020 Prerequisite: Introduction to Tkinter | Introduction to Matplotlib When Matplotlib is used from Python shell, the plots are displayed in a default window. The plots can be embedded in many graphical user interfaces like wxpython, pygtk, or Tkinter. These various options available as a target for the output plot are referred to as ‘backends‘. There are various modules available in matplotlib.backend for choosing the backend. One such module is backend_tkagg which is useful for embedding plots in Tkinter. First, let us create a basic Tkinter application with the main window and one button which can be used to display the plot. Python3 # import all classes/methods# from the tkinter modulefrom tkinter import * # The main tkinter windowwindow = Tk() # setting the title and window.title('Plotting in Tkinter') # setting the dimensions of # the main windowwindow.geometry("500x500") # button that would displays the plotplot_button = Button(master = window, height = 2, width = 10, text = "Plot")# place the button# into the windowplot_button.pack() # run the guiwindow.mainloop() Output : First, we need to create the figure object using the Figure() class. Then, a Tkinter canvas(containing the figure) is created using FigureCanvasTkAgg() class. Matplotlib charts by default have a toolbar at the bottom. When working with Tkinter, however, this toolbar needs to be embedded in the canvas separately using the NavigationToolbar2Tk() class.In the implementation below, a simple graph for: is plotted. The plot function is bound to a button that displays the figure when pressed. Python3 from tkinter import * from matplotlib.figure import Figurefrom matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk) # plot function is created for # plotting the graph in # tkinter windowdef plot(): # the figure that will contain the plot fig = Figure(figsize = (5, 5), dpi = 100) # list of squares y = [i**2 for i in range(101)] # adding the subplot plot1 = fig.add_subplot(111) # plotting the graph plot1.plot(y) # creating the Tkinter canvas # containing the Matplotlib figure canvas = FigureCanvasTkAgg(fig, master = window) canvas.draw() # placing the canvas on the Tkinter window canvas.get_tk_widget().pack() # creating the Matplotlib toolbar toolbar = NavigationToolbar2Tk(canvas, window) toolbar.update() # placing the toolbar on the Tkinter window canvas.get_tk_widget().pack() # the main Tkinter windowwindow = Tk() # setting the title window.title('Plotting in Tkinter') # dimensions of the main windowwindow.geometry("500x500") # button that displays the plotplot_button = Button(master = window, command = plot, height = 2, width = 10, text = "Plot") # place the button # in main windowplot_button.pack() # run the guiwindow.mainloop() Output : Python-matplotlib Python-tkinter 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON Create a Pandas DataFrame from Lists
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Jul, 2020" }, { "code": null, "e": 119, "s": 52, "text": "Prerequisite: Introduction to Tkinter | Introduction to Matplotlib" }, { "code": null, "e": 561, "s": 119, "text": "When Matplotlib is used from Python shell, the plots are displayed in a default window. The plots can be embedded in many graphical user interfaces like wxpython, pygtk, or Tkinter. These various options available as a target for the output plot are referred to as ‘backends‘. There are various modules available in matplotlib.backend for choosing the backend. One such module is backend_tkagg which is useful for embedding plots in Tkinter." }, { "code": null, "e": 685, "s": 561, "text": "First, let us create a basic Tkinter application with the main window and one button which can be used to display the plot." }, { "code": null, "e": 693, "s": 685, "text": "Python3" }, { "code": "# import all classes/methods# from the tkinter modulefrom tkinter import * # The main tkinter windowwindow = Tk() # setting the title and window.title('Plotting in Tkinter') # setting the dimensions of # the main windowwindow.geometry(\"500x500\") # button that would displays the plotplot_button = Button(master = window, height = 2, width = 10, text = \"Plot\")# place the button# into the windowplot_button.pack() # run the guiwindow.mainloop()", "e": 1201, "s": 693, "text": null }, { "code": null, "e": 1214, "s": 1204, "text": " Output :" }, { "code": null, "e": 1619, "s": 1218, "text": "First, we need to create the figure object using the Figure() class. Then, a Tkinter canvas(containing the figure) is created using FigureCanvasTkAgg() class. Matplotlib charts by default have a toolbar at the bottom. When working with Tkinter, however, this toolbar needs to be embedded in the canvas separately using the NavigationToolbar2Tk() class.In the implementation below, a simple graph for:" }, { "code": null, "e": 1713, "s": 1623, "text": "is plotted. The plot function is bound to a button that displays the figure when pressed." }, { "code": null, "e": 1723, "s": 1715, "text": "Python3" }, { "code": "from tkinter import * from matplotlib.figure import Figurefrom matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk) # plot function is created for # plotting the graph in # tkinter windowdef plot(): # the figure that will contain the plot fig = Figure(figsize = (5, 5), dpi = 100) # list of squares y = [i**2 for i in range(101)] # adding the subplot plot1 = fig.add_subplot(111) # plotting the graph plot1.plot(y) # creating the Tkinter canvas # containing the Matplotlib figure canvas = FigureCanvasTkAgg(fig, master = window) canvas.draw() # placing the canvas on the Tkinter window canvas.get_tk_widget().pack() # creating the Matplotlib toolbar toolbar = NavigationToolbar2Tk(canvas, window) toolbar.update() # placing the toolbar on the Tkinter window canvas.get_tk_widget().pack() # the main Tkinter windowwindow = Tk() # setting the title window.title('Plotting in Tkinter') # dimensions of the main windowwindow.geometry(\"500x500\") # button that displays the plotplot_button = Button(master = window, command = plot, height = 2, width = 10, text = \"Plot\") # place the button # in main windowplot_button.pack() # run the guiwindow.mainloop()", "e": 3147, "s": 1723, "text": null }, { "code": null, "e": 3156, "s": 3147, "text": "Output :" }, { "code": null, "e": 3174, "s": 3156, "text": "Python-matplotlib" }, { "code": null, "e": 3189, "s": 3174, "text": "Python-tkinter" }, { "code": null, "e": 3196, "s": 3189, "text": "Python" }, { "code": null, "e": 3294, "s": 3196, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3312, "s": 3294, "text": "Python Dictionary" }, { "code": null, "e": 3354, "s": 3312, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3380, "s": 3354, "text": "Python String | replace()" }, { "code": null, "e": 3412, "s": 3380, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3441, "s": 3412, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3468, "s": 3441, "text": "Python Classes and Objects" }, { "code": null, "e": 3489, "s": 3468, "text": "Python OOPs Concepts" }, { "code": null, "e": 3525, "s": 3489, "text": "Convert integer to string in Python" }, { "code": null, "e": 3548, "s": 3525, "text": "Introduction To PYTHON" } ]
Difference between index.ejs and index.html
09 Apr, 2021 What is HTML? HTML (Hypertext Markup Language) is used to design the structure of a web page and its content. HTML is actually not technically programming languages like C++, JAVA, or python. It is a markup language, and it ultimately gives declarative instructions to the browser. When a web page is loaded, the browser first reads the HTML and constructs DOM (Document Object Model) tree from it. HTML consists of a series of elements. What is a Template Engine? A template engine is a tool that enables developers to write HTML markup using plain JavaScript. The template engine has its own defined syntax or tags that will either insert variables or run some programming logic at run time and generate final HTML before sending it to the browser for display. What is EJS? EJS simply stands for Embedded JavaScript. It is a simple template language or engine. EJS has its own defined syntax and tags. It offers an easier way to generate HTML dynamically. Relation between HTML and EJS: We actually define HTML in the EJS syntax and specify how and where various data will go on the page. Then the template engine combines these data and runs programming logic to generate the final HTML page. So, the task of EJS is to take your data and inserts it into the web page according to how you’ve defined the template and generate the final HTML. For example, you could have a table of dynamic data from a database, and you want EJS to generate the table of data according to your display rules. When to use HTML/ EJS? It varies according to your application. If you want to render a static page then go for an HTML file and if you want to render a dynamic page where your data coming from various sources then you must choose an EJS file. Difference between index.ejs and index.html: Example: Assume you have a web page to show employee’s salaries. If you create a static HTML file then you need to rewrite it every time when new employee added or salary changes. But, with EJS it becomes too easy to insert dynamic data into it. HTML Version Code: index.html <!DOCTYPE html><html> <head> <title>Employee Salary</title> <style> table { margin: 20% auto; border-collapse: collapse; border-spacing: 0; width: 20%; border: 1px solid #ddd; } th, td { text-align: left; padding: 16px; } tr:nth-child(even) { background-color: #d1d1d1; } </style></head> <body> <table> <tr> <th> Employee </th> <th> Salary </th> </tr> <tr> <td> Sayan Ghosh </td> <td> 37000 </td> </tr> <tr> <td> Susmita Sahoo </td> <td> 365000 </td> </tr> <tr> <td> Nabonita Santra </td> <td> 36000 </td> </tr> <tr> <td> Anchit Ghosh </td> <td> 30000 </td> </tr> </table></body> </html> Output: EJS Version Code: Step 1: First, create a NodeJS application and install the required modules like express.js and ejs modules. Note: Refer to https://www.geeksforgeeks.org/how-to-use-ejs-in-javascript/ to get started with EJS. Step 2: Create an index.js file which is our basic server with the following code. index.js var express = require('express');var app = express(); // Set EJS as templating engine app.set('view engine', 'ejs'); // Employees dataconst empSalary = [ { name: "Sayan Ghosh", salary: 37000 }, { name: "Susmita Sahoo", salary: 365000 }, { name: "Nabonita Santra", salary: 36000 }, { name: "Anchit Ghosh", salary: 30000 }] app.get('/employee/salary', (req, res) => { // Render method takes two parameter // first parameter is the ejs file to // render second parameter is an // object to send to the ejs file res.render('index.ejs', { empSalary: empSalary });}) // Server setupapp.listen(3000, function (req, res) { console.log("Connected on port:3000");}); Step 3: Create an index.ejs file and put it in the views folder with the following code. index.ejs <!DOCTYPE html><html><head> <title>Employee Salary</title> <style> table { margin: 20% auto; border-collapse: collapse; border-spacing: 0; width: 20%; border: 1px solid #ddd; } th, td { text-align: left; padding: 16px; } tr:nth-child(even) { background-color: #d1d1d1; } </style></head><body> <table> <tr> <th> Employee </th> <th> Salary </th> </tr> <% empSalary.forEach(emp => { %> <tr> <td> <%= emp.name %> <td> <%= emp.salary %> </tr> <% }); %> </table></body></html> Step 4: Run the server using the following command: node index.js Output: Now open your browser and go to http://localhost:3000/employee/salary, you will see the following output: EJS-Templating Language HTML-Questions HTML-Tags Picked Difference Between HTML Node.js Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Similarities and Difference between Java and C++ Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Apr, 2021" }, { "code": null, "e": 42, "s": 28, "text": "What is HTML?" }, { "code": null, "e": 466, "s": 42, "text": "HTML (Hypertext Markup Language) is used to design the structure of a web page and its content. HTML is actually not technically programming languages like C++, JAVA, or python. It is a markup language, and it ultimately gives declarative instructions to the browser. When a web page is loaded, the browser first reads the HTML and constructs DOM (Document Object Model) tree from it. HTML consists of a series of elements." }, { "code": null, "e": 494, "s": 466, "text": "What is a Template Engine? " }, { "code": null, "e": 793, "s": 494, "text": "A template engine is a tool that enables developers to write HTML markup using plain JavaScript. The template engine has its own defined syntax or tags that will either insert variables or run some programming logic at run time and generate final HTML before sending it to the browser for display. " }, { "code": null, "e": 808, "s": 795, "text": "What is EJS?" }, { "code": null, "e": 990, "s": 808, "text": "EJS simply stands for Embedded JavaScript. It is a simple template language or engine. EJS has its own defined syntax and tags. It offers an easier way to generate HTML dynamically." }, { "code": null, "e": 1021, "s": 990, "text": "Relation between HTML and EJS:" }, { "code": null, "e": 1378, "s": 1021, "text": "We actually define HTML in the EJS syntax and specify how and where various data will go on the page. Then the template engine combines these data and runs programming logic to generate the final HTML page. So, the task of EJS is to take your data and inserts it into the web page according to how you’ve defined the template and generate the final HTML. " }, { "code": null, "e": 1527, "s": 1378, "text": "For example, you could have a table of dynamic data from a database, and you want EJS to generate the table of data according to your display rules." }, { "code": null, "e": 1550, "s": 1527, "text": "When to use HTML/ EJS?" }, { "code": null, "e": 1771, "s": 1550, "text": "It varies according to your application. If you want to render a static page then go for an HTML file and if you want to render a dynamic page where your data coming from various sources then you must choose an EJS file." }, { "code": null, "e": 1816, "s": 1771, "text": "Difference between index.ejs and index.html:" }, { "code": null, "e": 2063, "s": 1816, "text": "Example: Assume you have a web page to show employee’s salaries. If you create a static HTML file then you need to rewrite it every time when new employee added or salary changes. But, with EJS it becomes too easy to insert dynamic data into it. " }, { "code": null, "e": 2082, "s": 2063, "text": "HTML Version Code:" }, { "code": null, "e": 2093, "s": 2082, "text": "index.html" }, { "code": "<!DOCTYPE html><html> <head> <title>Employee Salary</title> <style> table { margin: 20% auto; border-collapse: collapse; border-spacing: 0; width: 20%; border: 1px solid #ddd; } th, td { text-align: left; padding: 16px; } tr:nth-child(even) { background-color: #d1d1d1; } </style></head> <body> <table> <tr> <th> Employee </th> <th> Salary </th> </tr> <tr> <td> Sayan Ghosh </td> <td> 37000 </td> </tr> <tr> <td> Susmita Sahoo </td> <td> 365000 </td> </tr> <tr> <td> Nabonita Santra </td> <td> 36000 </td> </tr> <tr> <td> Anchit Ghosh </td> <td> 30000 </td> </tr> </table></body> </html>", "e": 3036, "s": 2093, "text": null }, { "code": null, "e": 3044, "s": 3036, "text": "Output:" }, { "code": null, "e": 3062, "s": 3044, "text": "EJS Version Code:" }, { "code": null, "e": 3171, "s": 3062, "text": "Step 1: First, create a NodeJS application and install the required modules like express.js and ejs modules." }, { "code": null, "e": 3271, "s": 3171, "text": "Note: Refer to https://www.geeksforgeeks.org/how-to-use-ejs-in-javascript/ to get started with EJS." }, { "code": null, "e": 3354, "s": 3271, "text": "Step 2: Create an index.js file which is our basic server with the following code." }, { "code": null, "e": 3363, "s": 3354, "text": "index.js" }, { "code": "var express = require('express');var app = express(); // Set EJS as templating engine app.set('view engine', 'ejs'); // Employees dataconst empSalary = [ { name: \"Sayan Ghosh\", salary: 37000 }, { name: \"Susmita Sahoo\", salary: 365000 }, { name: \"Nabonita Santra\", salary: 36000 }, { name: \"Anchit Ghosh\", salary: 30000 }] app.get('/employee/salary', (req, res) => { // Render method takes two parameter // first parameter is the ejs file to // render second parameter is an // object to send to the ejs file res.render('index.ejs', { empSalary: empSalary });}) // Server setupapp.listen(3000, function (req, res) { console.log(\"Connected on port:3000\");});", "e": 4126, "s": 3363, "text": null }, { "code": null, "e": 4215, "s": 4126, "text": "Step 3: Create an index.ejs file and put it in the views folder with the following code." }, { "code": null, "e": 4225, "s": 4215, "text": "index.ejs" }, { "code": "<!DOCTYPE html><html><head> <title>Employee Salary</title> <style> table { margin: 20% auto; border-collapse: collapse; border-spacing: 0; width: 20%; border: 1px solid #ddd; } th, td { text-align: left; padding: 16px; } tr:nth-child(even) { background-color: #d1d1d1; } </style></head><body> <table> <tr> <th> Employee </th> <th> Salary </th> </tr> <% empSalary.forEach(emp => { %> <tr> <td> <%= emp.name %> <td> <%= emp.salary %> </tr> <% }); %> </table></body></html>", "e": 4847, "s": 4225, "text": null }, { "code": null, "e": 4899, "s": 4847, "text": "Step 4: Run the server using the following command:" }, { "code": null, "e": 4913, "s": 4899, "text": "node index.js" }, { "code": null, "e": 5027, "s": 4913, "text": "Output: Now open your browser and go to http://localhost:3000/employee/salary, you will see the following output:" }, { "code": null, "e": 5051, "s": 5027, "text": "EJS-Templating Language" }, { "code": null, "e": 5066, "s": 5051, "text": "HTML-Questions" }, { "code": null, "e": 5076, "s": 5066, "text": "HTML-Tags" }, { "code": null, "e": 5083, "s": 5076, "text": "Picked" }, { "code": null, "e": 5102, "s": 5083, "text": "Difference Between" }, { "code": null, "e": 5107, "s": 5102, "text": "HTML" }, { "code": null, "e": 5115, "s": 5107, "text": "Node.js" }, { "code": null, "e": 5132, "s": 5115, "text": "Web Technologies" }, { "code": null, "e": 5137, "s": 5132, "text": "HTML" }, { "code": null, "e": 5235, "s": 5137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5296, "s": 5235, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5364, "s": 5296, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 5413, "s": 5364, "text": "Similarities and Difference between Java and C++" }, { "code": null, "e": 5468, "s": 5413, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 5534, "s": 5468, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 5582, "s": 5534, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 5644, "s": 5582, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5694, "s": 5644, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5718, "s": 5694, "text": "REST API (Introduction)" } ]
Exception Handling in Java - GeeksQuiz
30 Sep, 2018 Main.java:4: error: incompatible types throw 10; ^ required: Throwable found: int Main.java:6: error: unexpected type catch(int e) { ^ required: class found: int 2 errors Got the Test Exception Inside finally block Got the Test Exception Inside finally block Main.java:12: error: exception Derived has already been caught catch(Derived d) { System.out.println("Caught derived class exception"); } a = 0 Divide by zero error inside the finally block Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 29498, "s": 29470, "text": "\n30 Sep, 2018" }, { "code": null, "e": 29725, "s": 29498, "text": "Main.java:4: error: incompatible types\n throw 10;\n ^\n required: Throwable\n found: int\nMain.java:6: error: unexpected type\n catch(int e) {\n ^\n required: class\n found: int\n2 errors" }, { "code": null, "e": 29770, "s": 29725, "text": "Got the Test Exception\nInside finally block " }, { "code": null, "e": 29793, "s": 29770, "text": "Got the Test Exception" }, { "code": null, "e": 29815, "s": 29793, "text": "Inside finally block " }, { "code": null, "e": 29959, "s": 29815, "text": "Main.java:12: error: exception Derived has already been caught\n catch(Derived d) { System.out.println(\"Caught derived class exception\"); } " }, { "code": null, "e": 30012, "s": 29959, "text": "a = 0\nDivide by zero error\ninside the finally block\n" } ]