aboutsummaryrefslogtreecommitdiff
path: root/content/overview-code-blocks.md
blob: 7c9458e9416a77bf52158eddb314e661d1bc892d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
+++
date = 2022-05-16T15:00:00Z
description = "Sample article showcasing syntax highlighting and formatting for Code Blocks with a custom theme."
draft = false
title = "Code Blocks Theme"

[extra]
keywords = "Code, Code Blocks, Syntax, Syntax Highlighting, Theme"
series = "Features"
toc = true

[taxonomies]
tags = [
    "Features",
    "Markdown",
]
+++
This article shows various Code Blocks allowing to easily compare sublime themes.

<!-- more -->

## Code Blocks

Code blocks.. ❤️ with automatic syntax highlighting ✨‍

See [the docs](https://www.getzola.org/documentation/content/syntax-highlighting/) for options.

### Inline Code block

If we want, we can also `specify inline code` which is useful for `the small stuff`.

### Rust

```rust
fn main() {
    let greetings = ["Hello", "Hola", "Bonjour",
                     "Ciao", "こんにちは", "안녕하세요",
                     "Cześć", "Olá", "Здравствуйте",
                     "Chào bạn", "您好", "Hallo",
                     "Hej", "Ahoj", "سلام",
                     "Hej", "Hallo", "Hei",
                     "Helló", "Hallo", "Buna ziua",
                     "Merhaba"];

    for (num, greeting) in greetings.iter().enumerate() {
        print!("{} : ", greeting);
        match num {
            0 =>  println!("This code is editable and runnable!"),//en English
            1 =>  println!("¡Este código es editable y ejecutable!"),//es Spanish
            2 =>  println!("Ce code est modifiable et exécutable !"),//fr French
            3 =>  println!("Questo codice è modificabile ed eseguibile!"),//it Italian
            4 =>  println!("このコードは編集して実行出来ます!"),//jp Japanese
            5 =>  println!("여기에서 코드를 수정하고 실행할 수 있습니다!"),//ko Korean
            6 =>  println!("Ten kod można edytować oraz uruchomić!"),//pl Polish
            7 =>  println!("Este código é editável e executável!"),//pt Portuguese
            8 =>  println!("Этот код можно отредактировать и запустить!"),//ru Russian
            9 =>  println!("Bạn có thể edit và run code trực tiếp!"),//vi Vietnamese
            10 => println!("这段代码是可以编辑并且能够运行的!"),//zh Chinese
            11 => println!("Dieser Code kann bearbeitet und ausgeführt werden!"),//de German
            12 => println!("Den här koden kan redigeras och köras!"),//sv Swedish
            13 => println!("Tento kód můžete upravit a spustit"),//cs Czech
            14 => println!("این کد قابلیت ویرایش و اجرا دارد!"),//fa Persian
            15 => println!("Denne kode kan redigeres og køres!"),//da Danish
            16 => println!("Deze code is bewerkbaar en uitvoerbaar!"),//du Dutch
            17 => println!("Tämä koodi on muokattavissa ja ajettavissa!"),//fi Finnish
            18 => println!("Ez a kód szerkeszthető és futtatható!"),//hu Hungarian
            19 => println!("Denne koden er redigerbar og kjørbar!"),//no Norwegian
            20 => println!("Acest cod este editabil și rulabil!"),//ro Romanian
            21 => println!("Bu kod düzenlenebilir ve çalıştırılabilir!"),//tr Turkish
            _ =>  {},
        }
    }
}
```

### TOML

```toml,linenos,hl_lines=3
base_url = "https://abridge.pages.dev/"
title = "Abridge"
description = "Abridge is a fast and lightweight Zola theme using semantic html, abridge.css class-light CSS, and No Mandatory JS."
default_language = "en"
#theme = "abridge"

build_search_index = true
minify_html = false
feed_filename = "atom.xml"
taxonomies = [
    {name = "categories", feed = true},
    {name = "tags", feed = true},
]
```

### Bash

```bash,hl_lines=5
#!/bin/bash
for d in /sys/kernel/iommu_groups/*/devices/*; do
  n=${d#*/iommu_groups/*}; n=${n%%/*}
  printf 'IOMMU Group %s ' "$n"
  lspci -nns "${d##*/}"
done
```

### HTML

```html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Example HTML5 Document</title>
</head>
<body>
  <!--Main Content Area-->
  <p>Test</p>
</body>
</html>
```

### CSS

```css
html {
    font-size: var(--fs);
}

.c {
    text-align: center;
}
```

### SCSS

```scss

$font: Roboto system-ui -apple-system BlinkMacSystemFont "Segoe UI" Oxygen Ubuntu Cantarell "Fira Sans" "Droid Sans" "Helvetica Neue" "Noto Sans" Helvetica Arial sans-serif !default;
$font-mono: ui-monospace Menlo Monaco Consolas "SF Mono" "Cascadia Mono" "Segoe UI Mono" "DejaVu Sans Mono" "Liberation Mono" "Roboto Mono" "Oxygen Mono" "Ubuntu Monospace" "Ubuntu Mono" "Source Code Pro" "Fira Mono" "Droid Sans Mono" "Courier New" Courier monospace !default;

@mixin font {
  // convert space separated list to comma separated list
  $font: list.join($font, "", $separator: comma);
  $font: functions.remove($font, "");
  $font-mono: list.join($font-mono, "", $separator: comma);
  $font-mono: functions.remove($font-mono, "");

  $font: functions.font-var($font, $fontExt-Main, $findFont-Main);
  $font-mono: functions.font-var($font-mono, $fontExt-Code, $findFont-Code);

  #{--ff}: $font;
  #{--fm}: $font-mono;//code
}
```

### Javascript

```javascript
function closeSearch() {//close the search displaying the regular page.
    const e = document.querySelector("main");
    e.innerHTML = window.main
}

function goSearch() {// on enter key or search icon click display results to the page.
    const e = document.querySelector("main");
    window.main || (window.main = e.innerHTML);
    var t = document.getElementById("suggestions"),
        n = ((ResultsClone = t.cloneNode(!0)).id = "results", document.createElement("div")),
        o = '<h2><button type="button" title="Close Search" onclick="closeSearch()"><i class="svgs x"></i></button> <i class="svgs search"></i> '.concat(document.getElementById("searchinput").value, "</h2>");
    return n.innerHTML = o, ResultsClone.insertBefore(n, ResultsClone.firstChild), e.innerHTML = ResultsClone.outerHTML, t.innerHTML = "", document.getElementById("searchinput").value = "", !1
}! function() {
  // search function code goes here
}
```

### PHP

```php
<?php
/**
 * Postfix Admin
 */
require_once('common.php');
$CONF = Config::getInstance()->getAll();

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    if (!isset($_SESSION['PFA_token'])) {
        die("Invalid token (session timeout; refresh the page and try again?)");
    }
    $fUsername = trim(safepost('fUsername'));
    if ($lang != check_language(false)) { # only set cookie if language selection was changed
        setcookie('lang', $lang, time() + 60*60*24*30); # language cookie, lifetime 30 days
    }
}

$_SESSION['PFA_token'] = md5(uniqid("pfa" . rand(), true));

/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
```

### Json

```json
{
    "name": "Abridge Zola Theme",
    "short_name": "Abridge",
    "description": "Fast & Lightweight Zola Theme",
    "start_url": "/index.html",
    "scope": "/",
    "background_color": "#111111",
    "theme_color": "#222222",
    "display": "standalone",
    "icons": [
        {
            "src": "/android-chrome-192x192.png",
            "sizes": "192x192",
            "type": "image/png"
        },
        {
            "src": "/android-chrome-512x512.png",
            "sizes": "512x512",
            "type": "image/png"
        },
        {
            "src": "/android-chrome-192x192m.png",
            "sizes": "192x192",
            "type": "image/png",
            "purpose": "maskable"
        }
    ]
}
```

### SQL

```sql
-- jelly-actix-web-starter - Creates an accounts table, along with some associated helpers.

create or replace function update_timestamp() returns trigger as $$
begin
    new.updated = now();
    return new;
end;
$$ language 'plpgsql';

create table if not exists accounts (
    id serial primary key,
    name text not null,
    email text not null unique,
    password text not null,
    profile jsonb not null default '{}',
    plan integer not null default 0,
    is_active boolean not null default true,
    is_admin boolean not null default false,
    has_verified_email boolean not null default false,
    last_login timestamp with time zone,
    created timestamp with time zone not null default now(),
    updated timestamp with time zone not null default now()
);

create unique index accounts_unique_lower_email_idx on accounts (lower(email));

create trigger user_updated before insert or update on accounts
for each row execute procedure update_timestamp();
```

### Lua

```lua
function square(x)
    return x * x
end

print(square(2)) -- prints '4'

function getPlayerInformation()
   playerName = UnitName("player")
   playerLevel = UnitLevel("player")
   specId, specName = GetSpecializationInfo(GetSpecialization())

   return "Hey, I'm " .. playerName .. " (Level " .. playerLevel .. "). I'm currently in spec " .. specName .. "."
end

print(getPlayerInformation())
```

### C

```c
#include <stdio.h>
int main() {
    int a;
    /* actual initialization */
    a = 10;
    printf("Hello, World!");
    return 0;
}
```

### C++

```cpp
// Your First C++ Program

#include <iostream>

int main() {
    int a;
    /* actual initialization */
    a = 10;
    std::cout << "Hello World!";
    return 0;
}
```

### Go

```go
package main

import "fmt"

func main() {
    var myvariable1 = 20
    var myvariable2 = "hello world"
    fmt.Println("hello world")
}
```

### Python

```python
#!/usr/bin/env python3
import smtplib, socket
from influxdb import InfluxDBClient

while True:
    send = 1
    later = time.time() + 25200
    iso = time.ctime(later)
    tempF = round(bme280.temperature * 1.8 + 29, 3) #C to F formula is +32, difference is to correct bme280 temperature offset
    humidity = round(bme280.humidity, 3)
    pressure = round(bme280.pressure, 3)
    # serialize data as JSON
    data = [
        {
          "measurement": measurement,
              "tags": {
                  "location": location,
              },
              "time": iso,
              "fields": {
                  "temperature" : tempF,
                  "humidity": humidity,
                  "pressure": pressure
                               }
          }
        ]
    # Send the JSON data to InfluxDB
    try:
      client.write_points(data)
    except socket.error as e:
      print("Could Not Connect to InfluxDB!")
    if tempF > 90 and humidity > 55:
      emailSubject = "Humidity>55:  " + str(int(humidity)) + "%H  , Temperature>90:  " + str(int(tempF)) + "F"
      emailContent = 'Humidity:  ' + str(int(humidity)) + '%H  , Temperature:  ' + str(int(tempF)) + 'F  <a href="https://metrics.example.com">Dashboard</a>'
    elif humidity > 55:
      emailSubject = "Humidity>55:  " + str(int(humidity)) + "%H"
      emailContent = 'Humidity:  ' + str(int(humidity)) + '%H  , Temperature:  ' + str(int(tempF)) + 'F  <a href="https://metrics.example.com">Dashboard</a>'
    elif tempF > 90:
      emailSubject = "Temperature>90:  " + str(int(tempF)) + "F"
      emailContent = 'Humidity:  ' + str(int(humidity)) + '%H  , Temperature:  ' + str(int(tempF)) + 'F  <a href="https://metrics.example.com">Dashboard</a>'
    else:
      send = 0
    if send == 1:
      try:
        if time.time() > lastEmailTime or abs(lastTemp-int(tempF)) > 1:
          lastEmailTime = time.time()+emailInterval
          lastTemp = int(tempF)
          sender.sendmail('jake@example.com', emailSubject, emailContent)
      except socket.error as e:
        print("Could Not Connect to SMTP server!")
    time.sleep(interval)
```

### Ruby

```ruby
=begin
  Ruby program to check whether the
  year is leap year or not between range.
=end

puts "Enter the lower limit:"
lwr = gets.chomp.to_i
puts "Enter the upper limit:"
upr = gets.chomp.to_i

for yr in lwr..upr do
  if yr % 400 == 0
    puts "#{yr} is a leap year"
  elsif yr % 4 == 0 && yr % 100 !=0
    puts "#{yr} is a leap year"
  else
    puts "#{yr} is not a leap year"
  end
end
```