code-rag-bench/online-tutorials huggingface dataset:
Get fields from multiple sub-documents that match a condition in MongoDB?

To get fields from multiple sub-documents, use MongoDB aggregate with $unwind. Let us create a collection with documents −
> db.demo671.insertOne(
... {
...
...    "details" : [
...    {
...       "id" : "1"
...    },
...    {
...       CountryName:"US",
...       "details1" : [
...       {
...       "id" : "1"
...       },
...       {
...          "id" : "2"
...       }
...       ]
...    },
... {
...    CountryName:"UK",
...    "details1" : [
...    {
...       "id" : "2"
...    },
...    {
...       "id" : "1"
...    }
...    ]
... },
... {
...    CountryName:"AUS",
...    "details1" : [
...       {
...          "id" : "1"
...       }
...       ]
...    }
... ]
... }
... )
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3e5d004263e90dac943e0")
}
Display all documents from a collection with the help of find() method −
> db.demo671.find();
This will produce the following output −
{ "_id" : ObjectId("5ea3e5d004263e90dac943e0"), "details" : [ { "id" : "1" }, { "CountryName" : "US", "details1" : [ { "id" : "1" }, { "id" : "2" } ] }, { "CountryName" : "UK", "details1" : [ { "id" : "2" }, { "id" : "1" } ] }, { "CountryName" : "AUS", "details1" : [ { "id" : "1" } ] } ] }
Here is the query to get fields from multiple sub-documents that match a condition in MongoDB −
> db.demo671.aggregate([
...
...   {$unwind: '$details'},
...
...   {$match: {'details.details1.id': '1'}},
...
...   {$project: {_id: 0, Country: '$details.CountryName'}}
... ]).pretty()
This will produce the following output −
{ "Country" : "US" }
{ "Country" : "UK" }
{ "Country" : "AUS" }
Explicit type casting operator in C++

A type cast provides a method for explicit conversion of the type of an object in a specific situation. It can be used as a unary expression −
( type-name ) cast-expression
The compiler treats cast-expression as type type-name after a typecast has been made. Casts are used to convert objects of any scalar kind to or from the other scalar type. Explicit type casts are constrained by the same rules that determine the effects of implicit conversions. Additional restraints on casts could result from the actual sizes or representation of specific types 
#include
using namespace std;
int main() {
   float x = 3.1;
   int i;
   i = (int)x;

   cout << x << ", " << i << endl;
   return 0;
}
This will give the output −
3.1, 3
What are C++ Manipulators (endl, setw, setprecision, setf)?

Stream Manipulators are functions specifically designed to be used in conjunction with the insertion (<<) and extraction (>>) operators on stream objects, for example −
std::cout << std::setw(10);
They are still regular functions and can also be called as any other function using a stream object as an argument, for example −
boolalpha (cout);
Manipulators are used to changing formatting parameters on streams and to insert or extract certain special characters.
Following are some of the most widely used C++ manipulators −
This manipulator has the same functionality as ‘\n’(newline character). But this also flushes the output stream.
Live Demo
#include<iostream>
int main() {
   std::cout << "Hello" << std::endl << "World!";
}
Hello
World!
This manipulator controls whether decimal point is always included in the floating-point representation. 
 Live Demo 
#include <iostream>
int main() {
   std::cout << "1.0 with showpoint: " << std::showpoint << 1.0 << '\n'
             << "1.0 with noshowpoint: " << std::noshowpoint << 1.0 << '\n';
}
1.0 with showpoint: 1.00000
1.0 with noshowpoint: 1
This manipulator changes floating-point precision. When used in an expression out << setprecision(n) or in >> setprecision(n), sets the precision parameter of the stream out or into exactly n. 
 Live Demo 
#include <iostream>
#include <iomanip>
int main() {
   const long double pi = 3.141592653589793239;
   std::cout << "default precision (6): " << pi << '\n'
             << "std::setprecision(10): " << std::setprecision(10) << pi << '\n';
}
default precision (6): 3.14159
std::setprecision(10): 3.141592654
This manipulator changes the width of the next input/output field. When used in an expression out << setw(n) or in >> setw(n), sets the width parameter of the stream out or in to exactly n. 
Live Demo
#include <iostream>
#include <iomanip>
int main() {
   std::cout << "no setw:" << 42 << '\n'
             << "setw(6):" << std::setw(6) << 42 << '\n'
             << "setw(6), several elements: " << 89 << std::setw(6) << 12 << 34 << '\n';
}
no setw:42
setw(6):    42
setw(6), several elements: 89    1234
How to return the response from an asynchronous call in Javascript?

There are multiple ways to return the response from an asynchronous call in javascript. Let us understand the problem first. Say you have a function called foo that is asynchronous and will give the data after some time. It can do this in 2 ways. It can either accept a callback that it'll call when it is ready to execute with the data. Or it can return a promise.
For example, the setTimeout function accepts a callback and executes it after a fixed amount of time. so lets say that you go with the first approach, then you can pass the function in the setTimeout.
function myFunc(cb) {
   setTimeout(() => cb(100), 1000);
}
myFunc((a) => console.log(a))
100
This will call the setTimeout function with a callback which will execute after 1000 ms. when that function is executed, it'll call the passed callback(cb) with the value returned from the setTimeout's callback.
Using Promises
You can also do this using promises. Wrap your async function with a promise and resolve this promise with the function's return value. You can the chain the then method and pass it a callback to use the value returned from the async function.
,
new Promise(resolve => setTimeout(() => resolve(100), 1000))
   .then(console.log)
100
Sieve of Eratosthenes in java

Sieve of Eratosthenes is the ancient algorithm to find prime numbers up to a given number.
1. Generate integers from 2 to n (Given number).
2. Counting from 2 mark every 2nd integer. (multiples of 2)
3. Now, starting from 3 mark every third integer. (multiples of 3)
4. Finally, marking from 5 mark every 5th integer.(multiples of 5)
import java.util.Scanner;

public class SievePrimeFactors  {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a number");
      int num = sc.nextInt();
      boolean[] bool = new boolean[num];
     
      for (int i = 0; i< bool.length; i++) {
         bool[i] = true;
      }
      for (int i = 2; i< Math.sqrt(num); i++) {
         if(bool[i] == true) {
            for(int j = (i*i); j<num; j = j+i) {
               bool[j] = false;
            }
         }
      }
      System.out.println("List of prime numbers upto given number are : ");
      for (int i = 2; i< bool.length; i++) {
         if(bool[i]==true) {
            System.out.println(i);
         }
      }
   }
}
Enter a number
50
List of prime numbers up to given number are :
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
numpy.char.encode()

This function calls str.encode function for each element in the array. Default encoding is utf_8, codecs available in standard Python library may be used.
import numpy as np 
a = np.char.encode('hello', 'cp500') 
print a
Its output is as follows −
�����


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
PyQt5 – How to make editable ComboBox

22 Apr, 2020
In this article we will see how we can make a combo box such that user and change the value of it by typing. By default when we create a combo box we can only choose from the option in the drop down menu although in editable combo box we can set the text by our self.
In order to do this we will use setEditable method
Syntax : combo_box.setEditable(True)
Argument : It takes bool as argument
Action performed : It will combo box editable
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 120, 30)          # geek list        geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"]          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # creating a editable combo box        self.combo_box.setEditable(True)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Iterate over a list in Python
MongoDB Projection

10 Feb, 2021
MongoDB provides a special feature that is known as Projection. It allows you to select only the necessary data rather than selecting whole data from the document. For example, a document contains 5 fields, i.e.,
{
name: "Roma",
age: 30,
branch: EEE,
department: "HR",
salary: 20000
}

But we only want to display the name and the age of the employee rather than displaying whole details. Now, here we use projection to display the name and age of the employee.
One can use projection with db.collection.find() method. In this method, the second parameter is the projection parameter, which is used to specify which fields are returned in the matching documents.
Syntax:
db.collection.find({}, {field1: value2, field2: value2, ..})
If the value of the field is set to 1 or true, then it means the field will include in the return document.
If the value of the field is set to 0 or false, then it means the field will not include in the return document.
You are allowed to use projection operators, but find() method does not support following projection operators, i.e., $, $elemMatch, $slice, and $meta.
There is no need to set _id field to 1 to return _id field, the find() method always return _id unless you set a _id field to 0.
Examples:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: employee
Document: five documents that contain the details of the employees in the form of field-value pairs.
nikhilchhipa9
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Basics of API Testing Using Postman
Copying Files to and from Docker Containers
Markov Decision Process
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
ML | Introduction to Data in Machine Learning
Fuzzy Logic | Introduction
How to call ‘npm start’ though docker ?

04 Jul, 2021
The following article covers how to call npm start through docker. While doing so, we will dockerize a simple React App.
Docker is an open-source platform for running, shipping, and managing applications. It allows us to manage our infrastructure in the same way as we manage our applications. 
It runs the application in a kind of isolated environment called container. A container is lightweight and contains everything needed to run the application. Multiple containers can run on the same host, and they can also share data between them securely.
 
Creating the React Application:
Step 1: Create a React application using the following command.npx create-react-app docker-react
Step 1: Create a React application using the following command.
npx create-react-app docker-react
Step 2: After creating your project folder(i.e. docker-react), move to it by using the following command.cd docker-react
Step 2: After creating your project folder(i.e. docker-react), move to it by using the following command.
cd docker-react
Step 3: Create a file named Dockerfile in the root of your app.
Step 3: Create a file named Dockerfile in the root of your app.
Project Structure: It will look like this.
Writing the Dockerfile: Write down the following lines to your Dockerfile.
FROM node:alpine
RUN mkdir /app
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
CMD ["npm", "start"]
Explanation:
First, we load the base image node:alpine which is a lightweight Linux distribution with a node installed in it.
Then we copy the package.json file which contains the app’s dependencies into our working directly.
And then we install the dependencies and copy the project files into our working directory.
Finally, we run the command npm start.
Creating docker image: Run the following command from the project’s root directory. Make sure your docker daemon is running.
docker build -t <yourname/projectname> .
Steps to run the application: Run the application using following command from the root directory of your folder.
docker run -d -it -p 3000:3000 <yourname/projectname>
Here we need to map our localhost port to the one of the container which in our case is 3000.
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
docker
Node-npm
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
How to generate JSON output using Python?

The json module in python allows you to dump a dict to json format directly. To use it,
import json

my_dict = {
   'foo': 42,
   'bar': {
      'baz': "Hello",
      'poo': 124.2
   }
}
my_json = json.dumps(my_dict)
print(my_json)
This will give the output −
'{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}'
You can also pass indent argument to prettyprint the json. 
import json

my_dict = {
   'foo': 42,
   'bar': {
      'baz': "Hello",
      'poo': 124.2
   }
}
my_json = json.dumps(my_dict, indent=2)
print(my_json)
This will give the output −
{
   "foo": 42,
   "bar":
   {
      "baz": "Hello",
      "poo": 124.2
   }
}
Expedia Hackerrank test for SDE (8 Years Experienced)

05 Nov, 2020
The test was conducted on Hackerrank platform and there were three questions that needed to be solved in 100 minutes:
Run-length Encoding.Device name system: Given a list of IoT devices having names say:int[] deviceNames={"tv","fridge","microwave",
                   "tv","microwave","tv","fridge"}
Generate a list that uniquely identifies these names, in case of conflicts add a number at the end. Output device names should be:outputDeviceNames={"tv","fridge","microwave",
                   "tv1","microwave1","tv2","fridge1"}
Longest ordered subsequence of vowels.
Run-length Encoding.
Run-length Encoding.
Device name system: Given a list of IoT devices having names say:int[] deviceNames={"tv","fridge","microwave",
                   "tv","microwave","tv","fridge"}
Generate a list that uniquely identifies these names, in case of conflicts add a number at the end. Output device names should be:outputDeviceNames={"tv","fridge","microwave",
                   "tv1","microwave1","tv2","fridge1"}

Device name system: Given a list of IoT devices having names say:
int[] deviceNames={"tv","fridge","microwave",
                   "tv","microwave","tv","fridge"}

Generate a list that uniquely identifies these names, in case of conflicts add a number at the end. Output device names should be:
outputDeviceNames={"tv","fridge","microwave",
                   "tv1","microwave1","tv2","fridge1"}

Longest ordered subsequence of vowels.
Longest ordered subsequence of vowels.
The last question is of Dynamic Programming and was the most important question of the whole test, I was not able to solve all the test cases of this question and was rejected, even though I was able to solve the first two questions with 100 percent test cases passed.
My advice for these tests should be to quickly solve the first two questions and give maximum time to the last question as it holds the maximum weightage.
Expedia
Marketing
Experienced
Interview Experiences
Expedia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bifid Cipher in Cryptography - GeeksforGeeks

06 Nov, 2019
This cipher technique considered more secure compared to other substitution algorithms reason being it breaks the message apart into two separate streams and then recombines them. It is a combination of the Polybius square with the transposition and uses fractionation to achieve diffusion. This encrypting technique invented by Felin Delastelle. It just only ever used by amateur cryptographers.
Encrypting Algorithm:For this cipher technique algorithm, we use the 25-letter “key-Square” table.
Example:
   1   2   3   4   5
1  R   A   N   C   H

2  O   B   D   E   F

3  G   I   K   L   M
 
4  P   Q   S   T   U  

5  V   W   X   Y  Z 
Here we merged J with the I because we are using a 5 X 5 square key matrix so we can use only 25 characters out of the 26.
Let us take “RAMSWARUP IS THE STUDENT OF THE NIT CALICUT” as our plain text.
Step-1:Now find each letter of the plain text in the key-square and write the corresponding row number and column in two separate lines. For example, our first letter is the “R” which is present in the first row and first column, so the key cipher text key value for it is “1-1”.
        RAMSWARUP     IS       THE     STUDENT      OF      THE      NIT     CALICUT 
ROW :   113451144     34       412     4442214      22      412      134     1133144
COL :   125322151     23       454     3453434      15      454      324     4242454 
Step-2:Now select a certain amount of size (this is called the period) which indicate how many key values we are going to take. for example in this example take the block size is 5. So divide the values in the block of the period.
ROW:   11345   11443   44124  44221  42241   21341  13314  4
COL:   12532   21512   34543  45343  41545   43244  24245  4 
Step-3:Now merge the values of rows and columns. Rows values followed by the columns. Final values after combining the values of rows and columns:
1134512532    1144321512     4412434543    4422145343    4224141545     2134143244     1331424245   44 
Step-4 (Final Step):Now select pair values from the final combined values and take corresponding character value from the key-square matrix. (first value indicates the row number and second value indicates the column values).
For example first taken value is 11 which indicates the character “R” and then we took 34 which is representing the character “L”.
CIPHER-TEXT:  RLVFIRTIHATASUSTBCXSQECHUOLCITNGQQUT 
ramswarup_kulhary
Rohit Mahali
cryptography
Computer Networks
cryptography
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Socket Programming in Python
Types of Network Topology
TCP 3-Way Handshake Process
User Datagram Protocol (UDP)
UDP Server-Client implementation in C
Types of Transmission Media
Distance Vector Routing (DVR) Protocol
Hamming Code in Computer Network
Advanced Encryption Standard (AES)
Angular Highcharts - Basic Pie Chart

Following is an example of a Pie Chart.
We have already seen the configurations used to draw a chart in Highcharts Configuration Syntax chapter. Now, let us see an example of a basic pie chart. We will also understand additional configuration. We have changed the type attribute in chart.
Configure the chart type to be 'pie' based. chart.type decides the series type for the chart. Here, the default value is "line".
var series = {
   type: 'pie'
};
app.component.ts
import { Component } from '@angular/core';
import * as Highcharts from 'highcharts';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
   highcharts = Highcharts;
   chartOptions = {   
      chart : {
         plotBorderWidth: null,
         plotShadow: false
      },
      title : {
         text: 'Browser market shares at a specific website, 2014'   
      },
      tooltip : {
         pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
      },
      plotOptions : {
         pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
               enabled: true,
               format: '<b>{point.name}%</b>: {point.percentage:.1f} %',
               style: {
                  color: (Highcharts.theme && Highcharts.theme.contrastTextColor)||
                  'black'
               }
            }
         }
      },
      series : [{
         type: 'pie',
         name: 'Browser share',
         data: [
            ['Firefox',   45.0],
            ['IE',       26.8],
            {
               name: 'Chrome',
               y: 12.8,
               sliced: true,
               selected: true
            },
            ['Safari',    8.5],
            ['Opera',     6.2],
            ['Others',      0.7]
         ]
      }]
   };
}
Verify the result.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
rename command in Linux with Examples - GeeksforGeeks

24 May, 2019
rename command in Linux is used to rename the named files according to the regular expression perlexpr. It can change the name of the multiple files. If the user will not specify any file names on the command line with this command then it will take the file name from the standard input.
Syntax:
rename [options] expression replacement file...

Options:
rename -s: This option renames the files ignoring the symbolic links.Example:rename -s 's/root/new/' sym.png
Example:
rename -s 's/root/new/' sym.png
rename -v: This option is used to show which files is being renamed, if there is any.Example:rename -v 's/jpeg/png/' *.jpeg
Example:
rename -v 's/jpeg/png/' *.jpeg
rename -n : This option comes into play when the user wants to see only the final change.Example:rename -n 's/png/jpeg/' *.png
Example:
rename -n 's/png/jpeg/' *.png
rename -o : This option will not going to overwrite the existing files.Example:rename -o 's/jpeg/png/' *.jpeg
Example:
rename -o 's/jpeg/png/' *.jpeg
rename -V: This option will show the version information and exit.Example:rename -V 's/jpeg/png/' *.jpeg
Example:
rename -V 's/jpeg/png/' *.jpeg
rename -help : This option will going show the help message and exit.Example:rename -help
Example:
rename -help
linux-command
Linux-file-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Python | Merge Tuple String List values to String

03 Nov, 2019
Sometimes, while working with records, we can have a problem in which any element of record can be of type string but mistakenly processed as list of characters. This can be a problem while working with a lot of data. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehension + join()The combination of above functionalities can be used to achieve to solution of above task. In this, we get the character list using list comprehension and conversion task is performed by join().
# Python3 code to demonstrate working of# Merge Tuple String List values to String# using list comprehension + join()  # initialize listtest_list = [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)]  # printing original listprint("The original list : " + str(test_list))  # Merge Tuple String List values to String# using list comprehension + join()res =  [''.join(i) for i, j in test_list]  # printing resultprint("The joined character list tuple element to string is : " + str(res))
The original list : [([‘g’, ‘f’, ‘g’], 1), ([‘i’, ‘s’], 2), ([‘b’, ‘e’, ‘s’, ‘t’], 3)]The joined character list tuple element to string is : [‘gfg’, ‘is’, ‘best’]
 
Method #2 : Using map() + join() + lambdaThe task performed by list comprehension in the above method can be performed by map() and lambda function can be used to construct the logic to achieve the solution to this task.
# Python3 code to demonstrate working of# Merge Tuple String List values to String# using map() + join() + lambda  # initialize listtest_list = [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)]  # printing original listprint("The original list : " + str(test_list))  # Merge Tuple String List values to String# using map() + join() + lambdares = list(map(lambda sub : "".join(sub[0]), test_list))  # printing resultprint("The joined character list tuple element to string is : " + str(res))
The original list : [([‘g’, ‘f’, ‘g’], 1), ([‘i’, ‘s’], 2), ([‘b’, ‘e’, ‘s’, ‘t’], 3)]The joined character list tuple element to string is : [‘gfg’, ‘is’, ‘best’]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Deque in Python
Defaultdict in Python
Queue in Python
Rotate axis tick labels in Seaborn and Matplotlib
Defaultdict in Python
Python program to add two numbers
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
Python Program for factorial of a number
Convert a string to lowercase in Julia – lowercase() and lowercasefirst() Methods

01 Apr, 2020
The lowercase() is an inbuilt function in julia which is used to return a string with all characters converted to lowercase.
Syntax: lowercase(s::AbstractString)
Parameters:
s::AbstractString: Specified string.
Returns: It returns a string with all characters converted to lowercase.
Example:
# Julia program to illustrate # the use of lowercase() method   # Getting a string with all # characters converted to lowercaseprintln(lowercase("GFG"))println(lowercase("GEEKS"))println(lowercase("GEEKSFORGEEKS"))
Output:
gfg
geeks
geeksforgeeks

The lowercasefirst() is an inbuilt function in julia which is used to return a string with first character converted to lowercase.
Syntax: lowercasefirst(s::AbstractString)
Parameters:
s::AbstractString: Specified string.
Returns: It returns a string with first character converted to lowercase.
Example:
# Julia program to illustrate # the use of lowercasefirst() method   # Getting a string with first# character converted to lowercaseprintln(lowercasefirst("GFG"))println(lowercasefirst("GEEKS"))println(lowercasefirst("GEEKSFORGEEKS"))
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Exception handling in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Get number of elements of array in Julia - length() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
NamedTuple in Julia
Find maximum element along with its index in Julia - findmax() Method
Searching in Array for a given element in Julia
Difference Between MATLAB and Julia
Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods
Broadcasting across arrays in Julia
.NET Core - Migrations

In this chapter, we will migrate the console application which contains the project.json file build system instead of MSBuild (*.csproj). So, we have an old project which contains the following files.
Now the question is, why do we need migration? This project is created using .NET Core 1.0 preview 2 tooling and now we have installed .NET Core 2.0 preview 1 tooling. Now when you build this application using .NET Core 2.0 command line utility, then you will see the following error.
This is because the project.json build system is no longer available in .NET Core 2.0, so we need migration so that it can work properly. To see the available commands, let us run the following command.
dotnet help 

In the commands section, you can see the different commands and you can also see the migrate command which will migrate a project.json based project to a MSBuild based project.
Let us now run the following command.
dotnet migrate 

You will see a summary of the migration process and here you can also see that a project is migrated successfully.
Let us now see the directory structure by using the following command.
tree /f 

You will now see the *.csproj file along with Program.cs file in the project root directory and project.json is moved to the backup folder.
Let us open the console.csproj file. Now you can restore and build this project using the MSBuild system by running the following command.
dotnet restore 

You can now see that all the packages are restored.
You can now build your project with the following command.
dotnet build 

You can now see that the project is built successfully using MSBuild and console.dll is also generated in ..\bin\Debug\netcoreapp1.0 folder.
The following screenshot shows the directory structure and files.
PyQt5 | How to adjust the image inside Push Button ?

22 Apr, 2020
When we set image to a push button we see that if the push button size is smaller than the image then image will get cropped. In this article we will see how we can retain the actual size of the image.
There are two ways to do this :
-> Change the size of Push Button according to the size of image.-> Instead of using background image use image as a skin.
Note : In first way, push button size may or may not be changed. It depends on the image size and in second way no change will occur to push button size.
Method #1 : Changing the size of button.
Code :
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 1000, 800)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a push button        button = QPushButton("CLICK", self)          # setting geometry of button        button.setGeometry(10, 15, 100, 40)          # adding action to a button        button.clicked.connect(self.clickme)          # setting background image        button.setStyleSheet("background-image : url(image.png);")          # resizing button according to size of image        button.resize(724, 430)      # action method    def clickme(self):          # printing pressed        print("pressed")  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :Note: This method is not preferable if image size is to large. 
Method #2 : Setting image as a skin.
Code :
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a push button        button = QPushButton("CLICK", self)          # setting geometry of button        button.setGeometry(100, 150, 100, 40)          # adding action to a button        button.clicked.connect(self.clickme)          # setting image as skin        button.setStyleSheet("border-image : url(image.png);")        # action method    def clickme(self):          # printing pressed        print("pressed")  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :Note : This method is not preferable if image shape is not as of button.
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to access the last element in a Pandas series?

26 Nov, 2020
Prerequisite: Pandas 
Pandas series is useful in handling various analytical operations independently or as being a part of pandas data frame. So it is important for us to know how various operations are performed in pandas series. The following article discusses various ways in which last element of a pandas series can be retrieved.
Method 1: Naive approach 
There are two naive approaches for accessing the last element:
Iterate through the entire series till we reach the end.
Find the length of the series. The last element would be length-1 (as indexing starts from 0).
Program:
Python3
# importing the pandas libraryimport pandas as pd  # initializing the seriesser = pd.Series(['g', 'e', 'e', 'k', 's'])  # iterating the series until the iterator reaches the end of the seriesfor i in range(0, ser.size):    if i == ser.size-1:        # printing the last element i.e, size of the series-1        print("The last element in the series using loop is : ", ser[i])  # calculating the length of the serieslen = ser.size  # printing the last element i.e len-1 as indexing starts from 0print("The last element in the series by calculating length is : ", ser[len-1])
Output:
Method 2: Using .iloc or .iat
Pandas iloc is used to retrieve data by specifying its integer index. In python negative index starts from end therefore we can access the last element by specifying index to -1 instead of length-1 which will yield the same result. 
Pandas iat is used to access data of a passed location. iat is comparatively faster than iloc.  Also note that ser[-1] will not print the last element of series, as series supports positive indexes only. However, we can use negative indexing in iloc and iat.
Program:
Python3
# importing the pandas library and timeimport pandas as pdimport time# initializing the seriesser = pd.Series(['g', 'e', 'e', 'k', 's'])  start = time.time()print("The last element in the series using iloc is : ", ser.iloc[-1])end = time.time()  print("Time taken by iloc : ", end-start)  start = time.time()print("The last element in the series using iat is : ", ser.iat[-1])end = time.time()  print("Time taken by iat : ", end-start)
Output:
Method 3: Using tail(1).item()
tail(n) is used to access bottom n rows from a series or a data frame and item() returns the element of the given series object as scalar.
Program:
Python3
# importing the pandas libraryimport pandas as pd# initializing the seriesser = pd.Series(['g', 'e', 'e', 'k', 's'])  # printing the last element using tailprint("The last element in the series using tail is : ", ser.tail(1).item())
Output:
Python Pandas-exercise
Python pandas-series
Python-pandas
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
PHP | imagecreatetruecolor() Function

23 Aug, 2019
The imagecreatetruecolor() function is an inbuilt function in PHP which is used to create a new true-color image. This function returns a blank image of the given size.
Syntax:
resource imagecreatetruecolor( $width, $height )
Parameters: This function accepts two parameters as mentioned above and described below:
$width: This parameter is used to set the width of image.
$height: This parameter is used to set the height of image.
Return Value: This function returns an image resource identifier on success, or False on errors.
Below programs illustrate the imagecreatetruecolor() function in PHP:
Program 1:
<?php    // Set the vertices of polygon$values = array(            150,  50, // Point 1 (x, y)            50, 250,  // Point 2 (x, y)            250,  250 // Point 3 (x, y)        );      // Create the size of image or blank image$image = imagecreatetruecolor(300, 300);    // Set the background color of image$background_color = imagecolorallocate($image,  0, 153, 0);     // Fill background with above selected colorimagefill($image, 0, 0, $background_color);   // Allocate a color for the polygon$image_color = imagecolorallocate($image, 255, 255, 255);     // Draw the polygonimagepolygon($image, $values, 3, $image_color);     // Output the picture to the browserheader('Content-type: image/png');     imagepng($image);?>
output:
Program 2:
<?php   // Create the size of image or blank image.$image = imagecreatetruecolor(500, 300);   // Display the height of image.echo imagesy($image);   ?>
output:
300
Related Articles:
PHP | imagecolortransparent() Function
PHP | imagepolygon() Function
Reference: http://php.net/manual/en/function.imagecreatetruecolor.php
Image-Processing
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
C program to sort an array using pointers

25 May, 2022
Given an array of size n, the task is to sort this array using pointers in C. Examples:
Input: n = 5, arr[] = {0, 23, 14, 12, 9}
Output: {0, 9, 12, 14, 23}

Input: n = 3, arr[] = {7, 0, 2}
Output: {0, 2, 7}
Approach: The array can be fetched with the help of pointers with the pointer variable pointing to the base address of the array. Hence in order to sort the array using pointers, we need to access the elements of the array using (pointer + index) format.  
Below is the implementation of the above approach:  
C
#include <stdio.h> // Function to sort the numbers using pointersvoid sort(int n, int* ptr){    int i, j, t;     // Sort the numbers using pointers    for (i = 0; i < n; i++) {         for (j = i + 1; j < n; j++) {             if (*(ptr + j) < *(ptr + i)) {                 t = *(ptr + i);                *(ptr + i) = *(ptr + j);                *(ptr + j) = t;            }        }    }     // print the numbers    for (i = 0; i < n; i++)        printf("%d ", *(ptr + i));} // Driver codeint main(){    int n = 5;    int arr[] = { 0, 23, 14, 12, 9 };     sort(n, arr);     return 0;}
0 9 12 14 23
Time Complexity: O(n2), where n represents the size of the given array.Auxiliary Space: O(1), no extra space is required, so it is a constant.
singh008nranjan
ManasChhabra2
samim2000
Arrays
C-Pointers
C Language
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
Memory Layout of C Programs
How to implement toggle using ReactJS ?

08 Apr, 2021
If we want to implement toggle functionality to a button, then we can have states in our component that will either be true or false and based on the value of state we can implement toggle functionality. When we click on the button and the current value of the state is true then we changed it to false and vice versa. When we change the state the component will re-render and based on the value of state content will display.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: 
Example: Here we will create a button component to toggle, we will use the JavaScript this keyword as well.
App.js
import React from 'react'   class Counter extends React.Component {       render() {        return(            <div>                <Button text = "Hello from GFG"> </Button>            </div>        )    }}  class Button extends React.Component{    state = {        textflag: false,    }           ToggleButton() {        this.setState(            {textflag : !this.state.textflag}        );    }       render() {        return(            <div>                <button onClick={() => this.ToggleButton()}>                  { this.state.textflag === false ? "Hide":"Show" }                </button>                {!this.state.textflag && this.props.text}            </div>        )    }}  export default Counter;
Output:
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS setState()
How to pass data from one component to other component in ReactJS ?
Re-rendering Components in ReactJS
ReactJS defaultProps
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React
Python PIL | Image.convert() Method

26 Jul, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
Image.convert() Returns a converted copy of this image. For the “P” mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette.
Syntax: Image.convert(mode=None, matrix=None, dither=None, palette=0, colors=256)
Parameters:mode – The requested mode. See: Modes.matrix – An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values.dither – Dithering method, used when converting from mode “RGB” to “P” or from “RGB” or “L” to “1”. Available methods are NONE or FLOYDSTEINBERG (default).palette – Palette to use when converting from mode “RGB” to “P”. Available palettes are WEB or ADAPTIVE.colors – Number of colors to use for the ADAPTIVE palette. Defaults to 256.
Returns: An Image object.
Image Used:
     # importing image class from PIL packagefrom PIL import Image  # creating image objectimg = Image.open(r"C:\Users\System-Pc\Desktop\scene3.jpg")  # using convert method for img1img1 = img.convert("L")img1.show()  # using convert method for img2 img2 = img.convert("1")img2.show()
Output1:
Output2:
Another Example: Taking another image.
Image Used:
     # importing image class from PIL packagefrom PIL import Image  # creating image objectimg = Image.open(r"C:\Users\System-Pc\Desktop\scene4.jpg")  # using convert method for img1img1 = img.convert("L")img1.show()  # using convert method for img2 img2 = img.convert("1")img2.show()
Output1:
Output2:
Python-pil
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
Python OOPs Concepts
Creating child process using fork() in Python - GeeksforGeeks

12 Dec, 2017
Create a child process and display process id of both parent and child process.
Fork system call use for creates a new process, which is called child process, which runs concurrently with process (which process called system call fork) and this process is called parent process. After a new child process created, both processes will execute the next instruction following the fork() system call.
Library used :os : The OS module in Python provides a way of using operating system dependent functionality. The functions that the OS module provides allows you to interface with the underlying operating system that Python is running on; be that Windows, Mac or Linux. It can be imported as –
import os

fork() : fork() is an operation whereby a process creates a copy of itself. It is usually a system call, implemented in the kernel.
getpid() : getpid() returns the process ID (PID) of the calling process.Below is Python program implementing above :# Python code to create child process import os  def parent_child():    n = os.fork()      # n greater than 0  means parent process    if n > 0:        print("Parent process and id is : ", os.getpid())      # n equals to 0 means child process    else:        print("Child process and id is : ", os.getpid())          # Driver codeparent_child()Output :Child process and id is :  32523
Parent process and id is :  32524
Note : Output can vary time to time, machine to machine or process to process.My Personal Notes
arrow_drop_upSave
Below is Python program implementing above :
# Python code to create child process import os  def parent_child():    n = os.fork()      # n greater than 0  means parent process    if n > 0:        print("Parent process and id is : ", os.getpid())      # n equals to 0 means child process    else:        print("Child process and id is : ", os.getpid())          # Driver codeparent_child()
Output :
Child process and id is :  32523
Parent process and id is :  32524

Note : Output can vary time to time, machine to machine or process to process.
Python-Library
system-programming
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python