Snippets Collections
<?php
    $dates = array
    (
        '0' => "2013-02-18 05:14:54",
        '1' => "2013-02-12 01:44:03",
        '2' => "2013-02-05 16:25:07",
        '3' => "2013-01-29 02:00:15",
        '4' => "2013-01-27 18:33:45"
    );

    function closest($dates, $findate)
    {
        $newDates = array();

        foreach($dates as $date)
        {
            $newDates[] = strtotime($date);
        }

        echo "<pre>";
        print_r($newDates);
        echo "</pre>";

        sort($newDates);
        foreach ($newDates as $a)
        {
            if ($a >= strtotime($findate))
                return $a;
        }
        return end($newDates);
    }

    $values = closest($dates, date('2013-02-04 14:11:16'));
    echo date('Y-m-d h:i:s', $values);
?>
<form action="/new" method="post">
 
  <input name="title" type="text">
  <input name="description" type="text">
  <button type="submit">Submit Form</button>
 
</form>
> More steps
iex ((New-Object System.Net.WebClient).DownloadString('https://git.io/JJ8R4'))
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname + window.location.search
                                
    btns = document.getElementsByClassName("saveBtn");
    for (var i = 0; i < btns.length; i++) {
        btns[i].addEventListener("click", function () {
			//Add function here
        });
    }
function greet(name)
{
    console.log("Hello "+name);
};

res = greet("john");
console.log(res);
import javax.swing.*;  
public class FirstSwingExample {  
public static void main(String[] args) {  
JFrame f=new JFrame();//creating instance of JFrame  
          
JButton b=new JButton("click");//creating instance of JButton  
b.setBounds(130,100,100, 40);//x axis, y axis, width, height  
          
f.add(b);//adding button in JFrame  
          
f.setSize(400,500);//400 width and 500 height  
f.setLayout(null);//using no layout managers  
f.setVisible(true);//making the frame visible  
}  
}  
<link rel="stylesheet" type="text/css" href="plugin/codemirror/lib/codemirror.css">

<body>
	<textarea class="codemirror-textarea"></textarea>
</body>

<script>

$(document).ready(function(){
    var codeText = $(".codemirror-textarea")[0];
    var editor = CodeMirror.fromTextArea(codeText, {
        lineNumbers : true
    });
});

</script>

<script type="text/javascript" src="plugin/codemirror/lib/codemirror.js"></script>
const [ user, setUser ] = useState(JSON.parse(localStorage.getItem('profile'))); //convert to object

const logout = () =>{
        dispatch({type: 'LOGOUT'});
        history.push("/");
        setUser(null);
    }

    useEffect(()=>{
        const token = user?.token;

        //JWT check if token expired
        if(token){
            const decodedToken = decode(token)
            if(decodedToken.exp*1000 < newDate().getTime()) logout();
        }
        setUser(JSON.parse(localStorage.getItem('profile')))
    },[location])
from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.gif'): #assuming gif
    im=Image.open(filename)
    image_list.append(im)
def addNums(a,b):
    summa = a + b
    return summa
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

const exampleSchema = new Schema({
    title: { type: String , required: true},
    content: [{type: String}]
});


var Example = mongoose.model('Example', exampleSchema);
module.exports = Example;
> More steps
document.addEventListener %28"keydown", function (zEvent%29 {
    if (zEvent.ctrlKey  &&  zEvent.altKey  &&  zEvent.key === "e") {  // case sensitive
        // DO YOUR STUFF HERE
    }
} );

                                
if (navigator.webdriver) {
    document.body.innerHTML = "This is a Bot";
}
function full_stack_developer() {
    full_stack_developer();
}
<html>

<input id="contact" name="address">

<script>

    var x = document.getElementById("contact").getAttribute('name');

</script>

</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>IDECodeSnippetCompletionPrefix</key>
	<string>snippetAlert</string>
	<key>IDECodeSnippetCompletionScopes</key>
	<array>
		<string>All</string>
	</array>
	<key>IDECodeSnippetContents</key>
	<string>let alertController = UIAlertController(title: &lt;#T##String?#&gt;, message: &lt;#T##String?#&gt;, preferredStyle: &lt;#T##UIAlertController.Style#&gt;)
let firstAction = UIAlertAction(title: &lt;#T##String?#&gt;, style: .default, handler: &lt;#T##((UIAlertAction) -&gt; Void)?##((UIAlertAction) -&gt; Void)?##(UIAlertAction) -&gt; Void#&gt;)
let cancelAction = UIAlertAction(title: &lt;#T##String?#&gt;, style: .cancel, handler: nil)

alertController.addAction(firstAction)
alertController.addAction(cancelAction)
present(alertController, animated: true)</string>
	<key>IDECodeSnippetIdentifier</key>
	<string>8C458AD7-C631-457B-85CC-D2501E425D59</string>
	<key>IDECodeSnippetLanguage</key>
	<string>Xcode.SourceCodeLanguage.Swift</string>
	<key>IDECodeSnippetSummary</key>
	<string></string>
	<key>IDECodeSnippetTitle</key>
	<string>UIAlertController</string>
	<key>IDECodeSnippetUserSnippet</key>
	<true/>
	<key>IDECodeSnippetVersion</key>
	<integer>2</integer>
</dict>
</plist>
//// Validate if Email field is spam
add_action( 'elementor_pro/forms/validation/email', function( $field, $record, $ajax_handler ) {
    // Looking if email found in spam array, you can add to the array
  $spamemails = array("ericjonesonline@outlook.com", "eric@talkwithwebvisitor.com");
    if ( in_array( $field['value'] , $spamemails) ) {
        $ajax_handler->add_error( $field['id'], 'אנחנו לא אוהבים ספאם, נסו מייל אחר' );
    }
}, 10, 3 );
percent_missing = df.isnull().sum() * 100 / len(df)
missing_value_df = pd.DataFrame({'column_name': df.columns,
                                 'percent_missing': percent_missing})
 const isRequired = () => { throw new Error('param is required'); };

const hello = (name = isRequired()) => { console.log(`hello ${name}`) };

// These will throw errors
hello();
hello(undefined);

// These will not
hello(null);
hello('David');
The idea here is that it uses default parameters, like how the b parameter here has a default if you don’t send it anything:
function multiply(a, b = 1) {
  return a * b;
}                               
                                
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: Text('IntrinsicWidth')),
    body: Center(
      child: IntrinsicHeight(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            RaisedButton(
              onPressed: () {},
              child: Text('Short'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('A bit Longer'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('The Longest text button'),
            ),
          ],
        ),
      ),
    ),
  );
}
var url = "http://scratch99.com/web-development/javascript/";
var urlParts = url.replace('http://','').replace('https://','').split(/[/?#]/);
var domain = urlParts[0];
const object1 = {
  a: 'somestring',
  b: 42
};

for (let [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}
days = 0
week = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, 3.‘Sunday’]
while day < 7:
print(“Today is” + week[days])
days += 1
                                
                                
function copyToClipboard(){

    var codeToBeCopied = document.getElementById('code-snippet').innerText;
    var emptyArea = document.createElement('TEXTAREA');
    emptyArea.innerHTML = codeToBeCopied;
    const parentElement = document.getElementById('post-title');
    parentElement.appendChild(emptyArea);

    emptyArea.select();
    document.execCommand('copy');

    parentElement.removeChild(emptyArea);
    M.toast({html: 'Code copied to clipboard'})

    }
async function fun() {
  return fetch('https://jsonplaceholder.typicode.com/todos/1').then(res => res.json());
}

const data  = await fun();
/* slightly transparent fallback */
.backdrop-blur {
  background-color: rgba(255, 255, 255, .9);
}

/* if backdrop support: very transparent and blurred */
@supports ((-webkit-backdrop-filter: blur(2em)) or (backdrop-filter: blur(2em))) {
  .backdrop-blur {
    background-color: rgba(255, 255, 255, .5);
    -webkit-backdrop-filter: blur(2em);
    backdrop-filter: blur(2em);
  }
}
// in css:
/* Display line under clicked navbar link */
.active {
  text-decoration-line: underline !important;
  text-decoration-thickness: 2px !important;
  color: rgb(20, 19, 19);
}

//in html: 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script>
      $(document).ready(function () {
        // Underline to remain in navbar after click using URL
        jQuery(function ($) {
          var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
          $('.nav-link').each(function () {
            if (this.href === path) {
              $(this).addClass('active');
            }
          });
        });
      });
    </script>

//Note class in link should be nav-link
ip addr | grep eth0 | grep inet | awk '{print $2}' | awk -F '/' '{print $1}' | awk '{printf "%s:3000", $0}' | clip.exe
<button x-cloak x-data="{scroll : false}" @scroll.window="document.documentElement.scrollTop > 20 ? scroll = true : scroll = false" x-show="scroll" @click="window.scrollTo({top: 0, behavior: 'smooth'})" type="button" data-mdb-ripple="true" data-mdb-ripple-color="light" class="fixed inline-block p-3 text-xs font-medium leading-tight text-white uppercase transition duration-150 ease-in-out bg-blue-600 rounded-full shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg bottom-5 right-5" id="btn-back-to-top" x-transition.opacity>
        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M3.293 9.707a1 1 0 010-1.414l6-6a1 1 0 011.414 0l6 6a1 1 0 01-1.414 1.414L11 5.414V17a1 1 0 11-2 0V5.414L4.707 9.707a1 1 0 01-1.414 0z" clip-rule="evenodd" />
        </svg>
</button>
const [animateHeader, setAnimateHeader] = useState(false)

useEffect(() => {
  const listener = () =>
  window.scrollY > 140 ? setAnimateHeader(true) : setAnimateHeader(false)
  window.addEventListener('scroll', listener)
  return () => {
    window.removeEventListener('scroll', listener)
  }
}, [])

// Example usage with TailwindCSS:
<div className={`bg-header/75 transition duration-500 ease-in-out ${animateHeader && 'bg-header/[0.95]'}`}>...</div>
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(options=options)
# Pemavor.com Autocomplete Scraper
# Author: Stefan Neefischer (stefan.neefischer@gmail.com)
 
import concurrent.futures
import pandas as pd
import itertools
import requests
import string
import json
import time
​
startTime = time.time()
​
# If you use more than 50 seed keywords you should slow down your requests - otherwise google is blocking the script
# If you have thousands of seed keywords use e.g. WAIT_TIME = 1 and MAX_WORKERS = 10
 
WAIT_TIME = 0.1
MAX_WORKERS = 20
​
# set the autocomplete language
lang = "en"
​
​
charList = " " + string.ascii_lowercase + string.digits
​
def makeGoogleRequest(query):
    # If you make requests too quickly, you may be blocked by google 
    time.sleep(WAIT_TIME)
    URL="http://suggestqueries.google.com/complete/search"
    PARAMS = {"client":"firefox",
            "hl":lang,
            "q":query}
    headers = {'User-agent':'Mozilla/5.0'}
    response = requests.get(URL, params=PARAMS, headers=headers)
    if response.status_code == 200:
        suggestedSearches = json.loads(response.content.decode('utf-8'))[1]
        return suggestedSearches
    else:
        return "ERR"
​
def getGoogleSuggests(keyword):
    # err_count1 = 0
    queryList = [keyword + " " + char for char in charList]
    suggestions = []
    for query in queryList:
        suggestion = makeGoogleRequest(query)
        if suggestion != 'ERR':
            suggestions.append(suggestion)
​
    # Remove empty suggestions
    suggestions = set(itertools.chain(*suggestions))
    if "" in suggestions:
        suggestions.remove("")
​
    return suggestions
​
​
#read your csv file that contain keywords that you want to send to google autocomplete
df = pd.read_csv("keyword_seeds.csv")
# Take values of first column as keywords
keywords = df.iloc[:,0].tolist()
​
resultList = []
​
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
    futuresGoogle = {executor.submit(getGoogleSuggests, keyword): keyword for keyword in keywords}
​
    for future in concurrent.futures.as_completed(futuresGoogle):
        key = futuresGoogle[future]
        for suggestion in future.result():
            resultList.append([key, suggestion])
​
# Convert the results to a dataframe
outputDf = pd.DataFrame(resultList, columns=['Keyword','Suggestion'])
​
# Save dataframe as a CSV file
outputDf.to_csv('keyword_suggestions.csv', index=False)
print('keyword_suggestions.csv File Saved')
​
print(f"Execution time: { ( time.time() - startTime ) :.2f} sec")
import java.util.*;
import java.util.function.*;
import java.util.stream.Stream;
class Employee {
    String name;
    int salary;
    Employee(String name,int salary){
        this.name=name;
        this.salary=salary;
        }
        public String getName(){
            return name;
        }
        public int getSalary(){
            return salary;
        }
            public void setName(String name){
        this.name=name;
            }
            
        public void setSalary(int salary){
            this.salary=salary;
        }


    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("<");
        sb.append("name: ");
        sb.append(name);
        sb.append(" salary: ");
        sb.append("" + salary+">");
        return sb.toString();

    }
}
class EmployeeInfo{
    enum SortMethod {
        BYNAME,BYSALARY;
    };

    public List<Employee> sort(List<Employee> emps, final SortMethod method){
        if(method.equals(method.BYNAME)){
         
             Collections.sort(emps,(e1,e2)->{return e1.name.compareTo(e2.name);
             });
        }
             else if(method.equals(method.BYSALARY)){
                 
                Collections.sort(emps,(e1,e2)->{
                int i =e1.salary - e2.salary;
                if(i==0) {
                    return e1.name.compareTo(e2.name);
                }
                else {
                    return i;
                }
            });
             }
             return emps;
    }
   public boolean isCharacterPresentInAllNames(Collection<Employee> entities, String character){
       Predicate<Employee> p1=s -> s.name.contains(character);
        boolean b1 = entities.stream().allMatch(p1);
        return b1;
   }


}
var specifiedElement = document.getElementById(%27a%27);

//I%27m using "click" but it works with any event
document.addEventListener(%27click%27, function(event) {
  var isClickInside = specifiedElement.contains(event.target);

  if (!isClickInside) {
    //the click was outside the specifiedElement, do something
  }
});
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
This method gets vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) found in a string.
   
#make a function:
def get_vowels(string):

#return is the keyword which means function have to return value: 
 return [each for each in string if each in 'aeiou']


#assign the words and function will return vowels words.
get_vowels('foobar') # ['o', 'o', 'a']


get_vowels('gym') # []
<main>
	<iframe src="https://www.youtube.com/embed/KQetemT1sWc"></iframe>   
    <a href="#!" onclick="stopThis()">Stop Playing</a>
</main>

<script>
  function stopThis(){
      var iframe = container.getElementsByTagName("iframe")[0];
      var url = iframe.getAttribute('src');
      iframe.setAttribute('src', '');
      iframe.setAttribute('src', url);
  }
</script>
body{
    background-image: url("img_tree.gif");
    background-repeat: no-repeat;
    background-attachment: fixed;
}
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
  </body>
</html>
//Implement a function which convert the given boolean value into its string representation.
//Note: Only valid inputs will be given.

function booleanToString(b){
  const b = new Boolean(true);
  
console.log(b.toString())
}
set search_path to bookings;

-- 1	В каких городах больше одного аэропорта?	
/*
 * Группирую таблицу аэропортов по городу и вывожу только те, у которых количество airport_code больше 1
 */
select city "Город"
from airports a
group by city 
having count(airport_code) > 1;


-- 2	В каких аэропортах есть рейсы, выполняемые самолетом с максимальной дальностью перелета?	
-- - Подзапрос
/*
 * Подзапрос получает код самолета с самыой большой дальностью (с помощью сортировки и ограничения вывода).
 * Далее в основном запросе указывается условие соответствия самолета.
 * Основной запрос получает имя аэропорта по джойну с таблицей перелётов
 */

select distinct 
	a.airport_name "Аэропорт"
from airports a  
join flights f on a.airport_code = f.departure_airport 
where f.aircraft_code = (
	select a.aircraft_code 
	from aircrafts a 
	order by a."range" desc limit 1
);


-- 3	Вывести 10 рейсов с максимальным временем задержки вылета	- Оператор LIMIT
/*
 * Отбираю только те рейсы, которые вылетели (actual_departure заполнено)
 * Задержка считается простым вычитанием.
 * Наконец, сортировка по убыванию и ограничение вывода
 */
select 
	f.flight_id,
	f.scheduled_departure,
	f.actual_departure,
	f.actual_departure - f.scheduled_departure "Задержка"
from flights f
where f.actual_departure is not null
order by "Задержка" desc
limit 10;



-- 4	Были ли брони, по которым не были получены посадочные талоны?	- Верный тип JOIN
/*
 * Left join, т.к. нужно полное множество броней.
 * Джойню таблицу tickets т.к. таблица броней связывается с талонами через билет.
 */
select 
	case when count(b.book_ref) > 0 then 'Да'
	else 'Нет'
	end "Наличие броней без пт",
	count(b.book_ref) "Их количество" 
from bookings b 
join tickets t on t.book_ref = b.book_ref 
left join boarding_passes bp on bp.ticket_no = t.ticket_no 
where bp.boarding_no is null;


-- 5	Найдите свободные места для каждого рейса, их % отношение к общему количеству мест в самолете.
-- Добавьте столбец с накопительным итогом - суммарное накопление количества вывезенных пассажиров из каждого аэропорта на каждый день. 
-- Т.е. в этом столбце должна отражаться накопительная сумма - сколько человек уже вылетело из данного аэропорта на этом или более ранних рейсах за день.	
-- - Оконная функция
-- - Подзапросы или cte
/*
 * CTE boarded получает количество выданных посадочных талонов по каждому рейсу
 * Ограничение actual_departure is not null для того, чтобы отслеживать уже вылетевшие рейсы
 * CTE max_seats_by_aircraft получает количество мест в самолёте
 * В итоговом запросе оба CTE джойнятся по aircraft_code
 * Для подсчета накопительной суммы использется оконная функция c разделением по аэропорту отправления и времени вылета приведенному к формату date. 
 */
with boarded as (
	select 
		f.flight_id,
		f.flight_no,
		f.aircraft_code,
		f.departure_airport,
		f.scheduled_departure,
		f.actual_departure,
		count(bp.boarding_no) boarded_count
	from flights f 
	join boarding_passes bp on bp.flight_id = f.flight_id 
	where f.actual_departure is not null
	group by f.flight_id 
),
max_seats_by_aircraft as(
	select 
		s.aircraft_code,
		count(s.seat_no) max_seats
	from seats s 
	group by s.aircraft_code 
)
select 
	b.flight_no,
	b.departure_airport,
	b.scheduled_departure,
	b.actual_departure,
	b.boarded_count,
	m.max_seats - b.boarded_count free_seats, 
	round((m.max_seats - b.boarded_count) / m.max_seats :: dec, 2) * 100 free_seats_percent,
	sum(b.boarded_count) over (partition by (b.departure_airport, b.actual_departure::date) order by b.actual_departure) "Накопительно пассажиров"
from boarded b 
join max_seats_by_aircraft m on m.aircraft_code = b.aircraft_code;

-- 6	Найдите процентное соотношение перелетов по типам самолетов от общего количества.	- Подзапрос
-- - Оператор ROUND
/*
 * Используется подзапрос для получения общего числа полетов (проверяем, вылетел ли самолет при подсчете)
 * В основном запросе используется группировка по полю model
 */
select 
	a.model "Модель самолета",
	count(f.flight_id) "Количество рейсов",
	round(count(f.flight_id) /
		(select 
			count(f.flight_id)
		from flights f 
		where f.actual_departure is not null
		)::dec * 100, 4) "В процентах от общего числа"
from aircrafts a 
join flights f on f.aircraft_code = a.aircraft_code 
where f.actual_departure is not null
group by a.model;

-- 7	Были ли города, в которые можно  добраться бизнес - классом дешевле, чем эконом-классом в рамках перелета?	
-- - CTE
/*
 * В CTE prices собираются стоимости билетов на рейс: максимальная для Эконома и минимальная для бизнеса.
 * Затем из него отбираются эти стоимости и группируются в одну строку по каждому аэропорту - это внешний
 * CTE eco_busi. Результаты фильтруются по сравнению полей b_min_amount и e_max_amount
 * Далее этот CTE джойнится с таблицами рейсов и аэропортов, чтобы достать из них города отправления и прибытия.
 * Судя по тому, что результат пустой, таких рейсов нет
 */
with eco_busi as (
	with prices as(
		select  
			f.flight_id,
			case when tf.fare_conditions  = 'Business' then min(tf.amount) end b_min_amount,
			case when tf.fare_conditions  = 'Economy' then max(tf.amount) end e_max_amount
		from ticket_flights tf 
		join flights f on tf.flight_id = f.flight_id 
		group by 
			f.flight_id, tf.fare_conditions
	)
	select 
		p.flight_id,
		min(p.b_min_amount),
		max(p.e_max_amount)
	from prices p
		group by p.flight_id
	having min(p.b_min_amount) < max(p.e_max_amount)
	)
select 
	e.flight_id,
	a.city depatrure_city,
	a2.city arrival_city
from eco_busi e 
join flights f on e.flight_id = f.flight_id 
join airports a on f.departure_airport = a.airport_code
join airports a2 on f.arrival_airport = a2.airport_code

/*
 * Этот вариант смотрит стоимость билета между городами без учета рейса
 * CTE max_min_by_city формирует минимальную стоимость по бизнес классу и муксимальную по эконому
 * с группировкой по городу отправления и прибытия и по классу билета.
 * результаты его отправляются во внешний запрос, который собирает минимум и максимум по двум городам
 * в одну строку. В итоговом условии выводятся только те строки, в которых min(b_min_amount) < max(e_max_amount).
 * Таких строк нет, так что и в этом случае бизнес всегда дороже эконома
 */
with max_min_by_city as(
	select 
		a.city dep_city,
		a2.city arr_city,
		tf.fare_conditions,
		case when tf.fare_conditions  = 'Business' then min(tf.amount) end b_min_amount,
		case when tf.fare_conditions  = 'Economy' then max(tf.amount) end e_max_amount
	from flights f 
	join ticket_flights tf on tf.flight_id = f.flight_id 
	join airports a on f.departure_airport = a.airport_code
	join airports a2 on f.arrival_airport = a2.airport_code
	group by (1, 2), 3
)
select 
	dep_city "Из", 
	arr_city "В", 
	min(b_min_amount) "Минимум за бизнес", 
	max(e_max_amount) "Максимум за эконом"
from max_min_by_city
group by (1, 2)
having min(b_min_amount) < max(e_max_amount);

-- 8	Между какими городами нет прямых рейсов?	
-- - Декартово произведение в предложении FROM
-- - Самостоятельно созданные представления
-- - Оператор EXCEPT
/*
 * Создаю представление для получения городов, между которыми есть рейсы
 * Два джойна в представлении для получения города отправления и города прибытия
 * В основном запросе получаю декартово произведение всех городов, с условием их неравенства
 * Затем из него убираю данные, которые есть в представлении.
 */
create view dep_arr_city as
select distinct 
	a.city departure_city,
	a2.city arrival_city
from flights f 
join airports a on f.departure_airport = a.airport_code 
join airports a2 on f.arrival_airport = a2.airport_code;

select distinct 
	a.city departure_city,
	a2.city arrival_city 
from airports a, airports a2 
where a.city != a2.city
except 
select * from dep_arr_city

-- 9	Вычислите расстояние между аэропортами, связанными прямыми рейсами, сравните с допустимой максимальной дальностью перелетов  
-- в самолетах, обслуживающих эти рейсы *	- Оператор RADIANS или использование sind/cosd
-- - CASE 
/*
 * Опять два раза джойн таблицы аэропортов.
 * Поле "Долетит?" заполняется по условию того, что рассчитанная дальность между городами меньше дальности самолета.
 * Расстояние между городами делал по формуле из задания не особо задумываясь об этом
 */
select distinct 
	ad.airport_name "Из",
	aa.airport_name "В",
	a."range" "Дальность самолета",
	round((acos(sind(ad.latitude) * sind(aa.latitude) + cosd(ad.latitude) * cosd(aa.latitude) * cosd(ad.longitude - aa.longitude)) * 6371)::dec, 2) "Расстояние",		
	case when 
		a."range" <
		acos(sind(ad.latitude) * sind(aa.latitude) + cosd(ad.latitude) * cosd(aa.latitude) * cosd(ad.longitude - aa.longitude)) * 6371 
		then 'Нет!'
		else 'Да!'
		end "Долетит?"
from flights f
join airports ad on f.departure_airport = ad.airport_code
join airports aa on f.arrival_airport = aa.airport_code
join aircrafts a on a.aircraft_code = f.aircraft_code 
#banner .slick-dots {
	display: flex;
	position: absolute;
	left: 50%;
	bottom: 30px;
	transform: translateX(-50%);
}

#banner .slick-dots li button {
	font-size: 0;
	width: 16px;
	height: 16px;
	border: 1px solid #fff;
	background: transparent;
	border-radius: 50%;
	margin: 0 5px;
}

#banner .slick-dots li.slick-active button {
	width: 20px;
	height: 20px;
	background: var(--hover);
	border-color: var(--hover);
}
<span class="rbx-text-navbar-right text-header" id="nav-robux-amount">960</span>
def getLargest(a,b,c):
    if a>b:
        if a>c:
            return a
        else: 
            return c
    else:
        if b>c:
            return b
        else:
            return c
star

Wed Apr 07 2021 15:28:59 GMT+0000 (UTC) https://stackoverflow.com/questions/15016725/how-to-get-closest-date-compared-to-an-array-of-dates-in-php

@mvieira #php

star

Thu Jul 08 2021 04:58:01 GMT+0000 (UTC) https://christitus.com/debloat-windows-10-2020/

@admariner

star

Fri May 01 2020 11:13:14 GMT+0000 (UTC) https://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/

@FlowerFine #javascript

star

Mon Jun 29 2020 23:11:09 GMT+0000 (UTC) example.com

@mishka #javascript

star

Fri Jul 09 2021 17:17:41 GMT+0000 (UTC)

@buildadev

star

Sun Jan 12 2020 17:40:37 GMT+0000 (UTC) https://slate.com/technology/2019/10/consequential-computer-code-software-history.html

@chrissyjones #historicalcode #numbers

star

Wed Jan 01 2020 19:00:00 GMT+0000 (UTC) https://www.javatpoint.com/java-swing

@price_the_ice #java #howto #interviewquestions #mobile

star

https://medium.com/@thiscodeworks.com/how-to-redirect-your-node-js-app-hosted-on-heroku-from-http-to-https-50ef80130bff

@mishka #javascript #nodejs #commandline

star

Tue Jul 20 2021 06:31:09 GMT+0000 (UTC) https://www.youtube.com/watch?v=LKlO8vLvUao&list=PL6QREj8te1P7VSwhrMf3D3Xt4V6_SRkhu&index=3

@davidTheNerdy #react.js #redux

star

Mon Feb 07 2022 04:29:34 GMT+0000 (UTC) https://stackoverflow.com/questions/26392336/importing-images-from-a-directory-python-to-list-or-dictionary

@lahiruaruna #python

star

Sun May 16 2021 13:28:29 GMT+0000 (UTC)

@anvarbek

star

Mon May 04 2020 23:28:55 GMT+0000 (UTC) https://stackoverflow.com/questions/37557990/detecting-combination-keypresses-control-alt-shift

@sid

star

Sun Nov 28 2021 12:53:59 GMT+0000 (UTC) https://codingtutz.com/3-ways-to-detect-selenium-bots-using-javascript/

@mycodesnippets #javascript

star

Mon Mar 08 2021 22:02:08 GMT+0000 (UTC)

@rajesh #javascript

star

Sun Dec 29 2019 19:53:43 GMT+0000 (UTC) https://github.com/mjurfest/ios-xcode-snippets/blob/master/8C458AD7-C631-457B-85CC-D2501E425D59.codesnippet

@0musicon0 #ios #swift #howto #appdevelopment #apps

star

Fri May 07 2021 18:14:11 GMT+0000 (UTC)

@Alz #php

star

Mon Apr 19 2021 09:24:15 GMT+0000 (UTC) https://stackoverflow.com/questions/51070985/find-out-the-percentage-of-missing-values-in-each-column-in-the-given-dataset

@siddharth #python

star

Fri Apr 24 2020 11:32:35 GMT+0000 (UTC) https://css-tricks.com/snippets/javascript/required-parameters-for-functions-in-javascript/

@Dimples #javascript #javascript #functions #parameters

star

Wed Jan 22 2020 18:43:41 GMT+0000 (UTC) https://medium.com/flutter-community/flutter-layout-cheat-sheet-5363348d037e

@loop_ifthen #dart #flutter #layouts

star

Fri Jan 10 2020 22:36:50 GMT+0000 (UTC) http://scratch99.com/web-development/javascript/how-to-get-the-domain-from-a-url/

@saint_r0ses #javascript #promises #howto

star

Tue May 05 2020 04:59:33 GMT+0000 (UTC) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

@sid #javascript

star

Tue Apr 21 2020 05:36:09 GMT+0000 (UTC) https://www.freecodecamp.org/news/python-example/

@Radions #python #python #loops #whileloop

star

Wed Feb 09 2022 19:07:29 GMT+0000 (UTC) https://stackoverflow.com/questions/70349865/how-to-store-fetch-response-in-javascript-variable

@knightastron #javascript

star

Fri Jul 23 2021 14:06:04 GMT+0000 (UTC)

@DennisKarg #css

star

Fri Dec 27 2019 13:19:35 GMT+0000 (UTC) https://dev.to/codeluggage/today-i-wrote-a-handy-little-snippet-to-easily-access-ubuntu-from-windows-in-wsl2-19l

@swellcuban #commandline #interesting #windows #ubuntu #linux

star

Tue Jan 31 2023 09:50:56 GMT+0000 (UTC) C:/Users/intel/Desktop/dig%20fest/Mohd%20Midhlaj%20A%20A%206E%20Website%20Building/index.html

@yes #html

star

Sun Nov 28 2021 12:54:38 GMT+0000 (UTC) https://codingtutz.com/bypass-cloudflare-bot-protection-in-selenium/

@mycodesnippets #python

star

Thu Aug 19 2021 13:56:33 GMT+0000 (UTC)

@jurede

star

Mon Jul 19 2021 13:23:44 GMT+0000 (UTC)

@BHUPSAHU

star

Tue Mar 23 2021 08:07:48 GMT+0000 (UTC) https://github.com/pydata/bottleneck/issues/281

@_thiscodeworks #python

star

Sat May 09 2020 19:43:38 GMT+0000 (UTC) https://api.jquery.com/jquery.post/

@prince333 #javascript #jquery

star

Tue Mar 31 2020 11:35:03 GMT+0000 (UTC) https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172

@amnasky #python #python #strings #vowels #function

star

https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary

@bravocoder #python

star

https://www.w3schools.com/CSSref/pr_background-attachment.asp

@mishka #css #html

star

https://getbootstrap.com/docs/4.0/getting-started/introduction/

@mishka #html

star

Wed Mar 23 2022 14:48:03 GMT+0000 (UTC) https://github.com/mikepro-alfamail-ru/sql-29-final/blob/main/sql-39-final.sql

@TEST12

star

Sat Sep 18 2021 20:46:52 GMT+0000 (UTC)

@shafs #css

star

Tue Jun 29 2021 17:50:55 GMT+0000 (UTC) https://www.roblox.com/users/2363055682/profile

@fox_y09876 #javascript

star

Sun May 16 2021 13:25:22 GMT+0000 (UTC)

@anvarbek

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension