Site Tools


New release candidate 3 available: 2020-06-09 "Hogfather". upgrade now! [51.2] (what's this?)
New release candidate 2 available: 2020-06-01 "Hogfather". upgrade now! [51.1] (what's this?)
New release candidate available: 2020-06-01 "Hogfather". upgrade now! [51] (what's this?)
onny:notizen:programmierung

python

example class

class Connection:
    def __init__(self):
        self.mylist = []
    def list_connections(self):
        return "hallo"

constructor fail if condition is not met

class File():
 
    def __new__(self, path, file_path):
        if os.path.isfile(file_path):
             instance = super(File, self).__new__(self)
             instance.path, instance.file_path = path, file_path
             return instance
 
    def __init__(self, path, file_path):
        self.file_path = file_path
        self.name = os.path.relpath(file_path, path)

modularization

mkdir lib
touch lib/__init__.py
lib/utils.py
from datetime import datetime
def log(msg):
    time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print("["+time+"] "+msg)
main.py
from lib.utils import log
[...]

sexy logging

from datetime import datetime
def log(msg):
    time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print("["+time+"] "+msg)

using argparse

import argparse
 
parser = argparse.ArgumentParser()
parser.add_argument("--input", help="choose 'microphone', 'system', 'file' or the name of a recording device (default system)")
parser.add_argument("file", nargs='?', help="common sound file with about 10 seconds runtime (optional)", required=True)
args = parser.parse_args()
 
if args.input:
    if (args.input == "system"):
[...]

beautifulsoup example

from bs4 import BeautifulSoup
soup = BeautifulSoup(req.content, features="lxml")
token = soup.findAll("input", {"name": "_token"})[0]['value']

record, play and save sound

import soundcard as sc
import soundfile as sf
import numpy
sound_device = sc.get_microphone('Monitor', include_loopback=True) # loopback system sound
sound_device = sc.default_microphone()
data = sound_device.record(samplerate=48000, numframes=500000)
sf.write("/tmp/recording.ogg", data, 48000)
default_speaker = sc.default_speaker()
default_speaker.play(data/numpy.max(data), samplerate=48000)

load json config

import json
 
config = {}
with open('config.json') as json_data:
    configfile = json.load(json_data)
    config['preferences'] = configfile["lit-eratur"]["preferences"]
suburl = config['preferences']['suburl']
{
  "lit-eratur": {
    "preferences": {
      "suburl": "",
      "password": "password"
    }
  }
}

current date

import datetime
date = datetime.datetime.now().strftime("%d.%m.%Y")

zahlen aufrunden

import math
 
math.ceil(0.5)

array one line: return/append in case condition is true

# Reconstruct array with file objects in case they are true
self.files_local = [File(self.file_path, x) for x in self.files_local if File(self.file_path, x)]

requests

requests

import requests
upstream_request = requests.get(upstream_url+url_param,allow_redirects=False)
if (upstream_request.status_code == 302):
    upstream_request = requests.get(upstream_url + upstream_head.headers['location'])
if (upstream_request.headers['content-type'] == "text/html;charset=UTF-8" or upstream_request.headers['content-type'] == "text/html; charset=UTF-8"):
    upstream_response = upstream_response.replace("//thepiratebay.org","")

post json

r = requests.post('http://httpbin.org/post', json={"key": "value"})

ponyorm

from pony import orm
db = orm.Database()
 
class Article(db.Entity):
    name = orm.Required(str)
    date = orm.Required(str)
    text = orm.Required(str)
    title = orm.Required(str)
 
@orm.db_session
def add_article(name, date, text, title):
    Article(name=nane, date=date, text=text, title=title)
 
db.bind(provider='sqlite', filename='database.sqlite', create_db=True)
db.generate_mapping(create_tables=True)
 
add_article("Jonas", "01.01.2001", "hallo welt", "mein eintrag")
 
with orm.db_session:
    articles = orm.select(f for f in Article).order_by(lambda: orm.desc(f.id))[:]
    for article in articles:
        print(article["name"])

bottle

import bottle
app = bottle.Bottle()
 
@app.get("/static/logo.png")
def index():
    sequence = int(bottle.request.query['sequence'])
    return bottle.static_file("logo.png", root="static")
 
@app.post("/newpost")
def index():
    myname = bottle.request.forms.get("name")
    print(myname)
    bottle.response.status = 200
    bottle.response.content_type = "text/html; charset=UTF-8"
 
@app.get("/page/<page:int>")
def index(page):
    return bottle.template('index.tpl', page=page)
 
if __name__ == '__main__':
    app.run(reloader=True, debug=True, host='0.0.0.0', port=8080)
else:
    application = app

template syntax

      %for article in articles:
      %  categories = article.categories.split(",")
      <article>
        <h1><i class="em em-bookmark"></i> {{article.title}}</h1>
        <span class="autor">rezensiert von {{article.name}} am {{article.date}} in:
          % for index, category in enumerate(categories):
            % category = category.strip()
            <a href="{{suburl}}/category/{{category}}">
            % if (len(categories) > 1 and index != (len(categories)-1)):
            {{category}}</a>,
            % else:
            {{category}}</a>
            % end
          % end
        </span>
        <p>
          {{! article.text}}
          <br><br><i>Bewertung:</i>
          % for i in range(5):
            % if i >= article.rating:
            <img src={{suburl}}/static/unlit.png class=emoji>
            % else:
            <i class="em em-fire emoji"></i>
            % end
          % end
        </p>
      </article>
      %end

recieve uploaded file

files = {'file': open(sys.argv[1], 'rb')}
r = requests.post('http://localhost:8080/server', files=files)
@app.post("/server")
def index():
    upload = bottle.request.files.get('file')
    print(upload.filename)
    upload.save('/tmp/recv.tar')

regex

regex match between two special chars

pat = r'.*?\[(.*)].*'             #See Note at the bottom of the answer
s = "foobar['infoNeededHere']ddd"
match = re.search(pat, s)
match.group(1)
"'infoNeededHere'"

regex findall

regex = re.compile('https://podcasts.srf.ch/ch/audio/.*?.mp3')
it = re.finditer(regex, requests_response.text)
 
for match in it:
  print (match.group(0))

find/search text html tags

re_search_pat = r'.*(<title>.*</title>).*'
match = re.search(re_search_pat, upstream_response)
site_title = match.group(1)

strip all specific html tags

upstream_response = re.sub(r'<script.+?</script>', '', upstream_response, flags=re.DOTALL)

substitude string with exceptions

upstream_response = re.sub(r'<a ?(.*?)href="(?!magnet)(.*?)</a>', r'<a \1href="#\2</a>', upstream_response, flags=re.DOTALL)

django

applying translations

django-admin makemessages -l de
django-admin compilemessages

javascript

javascript document ready

document.addEventListener("DOMContentLoaded", function() {
  console.log('ready');
});

vanilla js click event

document.getElementsByClassName("header-lang-small")[0].addEventListener("click", function(){
  var dropdown = document.getElementById("dropdown");
  var dropdownIcon = document.querySelector('.header-lang-small .icon');
  console.log(dropdownIcon);
  if (dropdown.style.display === "block") {
    dropdown.style.display = "none";
    dropdownIcon.classList.toggle('active');
  } else {
    dropdown.style.display = "block";
    dropdownIcon.classList.toggle('active');
  }
});

clickevent inside/outside element

document.addEventListener("click", function(){
  var langSelector = document.getElementsByClassName("header-lang-small")[0];
  var dropdown = document.getElementById("dropdown");
  var dropdownIcon = document.querySelector('.header-lang-small .icon');
  var isClickInside = langSelector.contains(event.target);
  if (isClickInside) {
    if (dropdown.style.display === "block") {
      dropdown.style.display = "none";
      dropdownIcon.classList.toggle('active');
    } else {
      dropdown.style.display = "block";
      dropdownIcon.classList.toggle('active');
    }
  } else {
    dropdown.style.display = "none";
    dropdownIcon.classList.remove('active');
  };
 
});

remove/add class from classlist

div.classList.remove("foo");
div.classList.add("anotherclass");

split up javascript files

var MODULE = (function (my) {
     var privateToThisFile = "something";
 
    // add capabilities...
 
     my.publicProperty = "something";
 
     my.publicPropertyFunc = function(){
        alert("something");
     });
 
    return my;
}(MODULE || {}));

print mixed objects

console.log('%d: %s', i, value);

vanilla js query child

var testContainer = document.querySelector('#test');
var fourChildNode = testContainer.querySelector('.four');

vanilla js change content text

    var webgl_field = document.getElementById('webgl');
    if (webgl_support()) {
      webgl_field.textContent = "JA";
    } else {
      webgl_field.textContent = "NOE";
    }

vanilla js ajax post form

    document.getElementById('form').onsubmit = function (evt) {
     evt.preventDefault();
     var form = document.querySelector('form');
     var form_data = new FormData(form);
     var request = new XMLHttpRequest();
      request.onreadystatechange = function() {
        if(request.readyState === 4) {
          if(request.status === 200) {
            location.reload();
          }
        }
      }
      request.open('POST', '{{suburl}}/newpost');
      request.send(form_data);
    }

vanilla js change style element

    function show_create_post() {
      var x = document.getElementById("create_post");
      if (x.style.display === "block") {
        x.style.display = "none";
      } else {
        x.style.display = "block";
      }
    }

hashurl navigation

        if (window.location.hash) {
          var hashurl = window.location.hash.split("#")[1];
          load_page(hashurl);
        } else {
          load_page('/');
        }
 
        window.addEventListener('hashchange', function(event) {
          var hashurl = event.newURL.split("#")[1];
          load_page(hashurl);
        }, false);

nprogress progress bar ajax calls

<script src="https://unpkg.com/nprogress@0.2.0/nprogress.js"></script><
NProgress.configure({ showSpinner: false, trickleSpeed: 50 });
 
function load_page(hashurl) {
  NProgress.start();
  $.get('{{suburl}}'+'/ajax/'+hashurl, function(data) {
    $("body").html(data);
    var site_title = data.match(/<title>(.*?)<\/title>/);
    document.title = site_title[1];
    NProgress.done();
  })
}

for loop element of object

var lists = document.getElementsByClassName("bestandliste");
for (let list of lists) {
  list.style.display = "none";
}

get id of element

console.log(listElement.id);

html

starting template

<!doctype html>
<html lang="de">
<head>
  <meta data-react-helmet="true" charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1">

include remote js file

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

include remote css file

<link rel="stylesheet" type="text/css" href="/lib/exe/css.php?t=dokuwiki&amp;tseed=b35240351d681d3969980f5cbb368ff4"/>

include javascript inside html document

<script language="javascript">
alert("hello");
</script>

css within html

  <style type="text/css">
    nav.main {
      background-color: green; /* will be overridden by body internal styles */
    }
  </style>

footer bottom page

<html>
<head>
  <style type="text/css">
 
    body {
      margin: 0 !important;
      padding: 0 !important;
    }
 
    * {
      margin: 0;
      padding: 0;
    }
 
    article {
      min-height: 100vh;
      display: grid;
      grid-template-rows: 1fr auto;
      grid-template-columns: 100%;
    }
 
    main {
      background: whitesmoke;
      padding: 1rem;
    }
 
    footer {
      background: purple;
      padding: 1rem;
    }
 
  </style>
</head>
 
<body>
 
  <article>
      <main>
          <strong contenteditable>Hi, there's not much content, yet. You can write in here to expand the container.</strong>
      </main>
      <footer>
          All rights reversed.
          <br>
          <small>I am always at the bottom of the page</small>
      </footer>
  </article>
 
</body>
</html>

css

sweet font styling

font-family: consolas,Menlo-Regular,Menlo,Monaco,monospace;
    font-size: 125%;
    line-height: 135%;

media queries, page greater than 600px

      @media (min-width: 600px) {
        article {
          min-width: 600px;
        }
      }

style table columns

    td:nth-child(2) {
      max-width: 200px;
    }
 
    td:nth-child(3) {
      max-width: 200px;
    }

css easy center div box content vertical and horizontal align

      body {
        margin: 0 !important;
        padding: 0 !important;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        height: 100vh;
      }

php

enable debugging / error log

/etc/php/conf.d/debug.ini
display_startup_errors = true
display_errors = true
html_errors = true
log_errors = true
track_errors = true
error_log = /var/log/php-errors.log
touch /var/log/php-errors.log
chmod a+w+r /var/log/php-errors.log

print / echo array

echo '<pre>'; print_r($array); echo '</pre>';

using arrays

$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";

foreach, loop

foreach($chars as $item) {
  echo "<li>".$item."</li>";
};

substring, substr

echo substr("Hello world",6);

push array, append array

$z = [];
array_push($z, 'she', 'it');

check string exists in array

if (in_array("Glenn", $people))

sql

Update field:

UPDATE forwardings SET destination='alex.bloss@online.de' WHERE 'destination=bloss@bigwood.de';

Insert field:

INSERT INTO forwardings (SOURCE, destination) VALUES ('markus.heim@wew-heim.de', 'heimmarkus@yahoo.de');
INSERT INTO forwardings VALUES ('markus.heim@wew-heim.de', 'heimmarkus@yahoo.de');

Delete row:

DELETE FROM domains WHERE DOMAIN='alex-vt.de';
mysql> \P /usr/bin/less
PAGER SET TO /usr/bin/less

Delete all rows:

TRUNCATE my_table;

Create database:

CREATE DATABASE roundcubemail;
GRANT ALL PRIVILEGES ON roundcubemail.* TO roundcube@'http-new' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;

delete user:

DROP USER gitlab@'http.pi';

mysql

Dump database

mysqldump -u root -p Tutorials > tut_backup.sql

Backup everything

mysqldump -u root -p --all-databases > alldb.sql

Setup

systemctl stop mysqld
mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
systemctl start mysqld
mysql_secure_installation

postgresql

drop database

sudo -u postgres -i
dropdb onlyoffice

change user password

sudo -i -u postgres psql -c "ALTER USER gitlab WITH PASSWORD '****';"

upgrade user to be superuser

ALTER USER myuser WITH SUPERUSER;
ALTER USER myuser WITH NOSUPERUSER;

sqlite

List tables

.tables

Select

SELECT * FROM oc_radio_stations;

Query table schema

.schema oc_radio_stations

Insert into table

INSERT INTO oc_radio_stations VALUES('1','1');

Drop table

DROP TABLE torrents;

Order by

SELECT * FROM orders ORDER BY currenttime DESC;

Convert mysql to sqlite, using script

./mysql2sqlite ../oc_news_items.sql > oc_news_items.sql 

update string

UPDATE Article SET name = REPLACE(name, "mathilde", "Mathilde");

bash

loop

#!/bin/sh
while true
do
    sleep 10
    iw wlan0 connect test
    ifconfig wlan0 10.0.0.2 255.255.255.0 up
    iw dev wlan0 link
done

wordpress

using wp_query

$args = array(
    'cat'     =>  $categories[0]->cat_ID,
    'orderby' => 'title',
    'order'   => 'ASC',
);
$query = new WP_Query( $args );
 
if ( $query->have_posts() ) :
  while ( $query->have_posts() ) :
    $query->the_post();
    echo get_the_title();
  endwhile;
  wp_reset_postdata();

manual db query

$allPostTitles = $wpdb->get_results( "
SELECT post_title
FROM {$wpdb->posts}
WHERE post_type = 'post' and post_status = 'publish'
ORDER BY post_title ASC" );
echo '<pre>'; print_r($allPostTitles); echo '</pre>';

translating text

_e("Showing results", 'kit');
echo "<strong> ";
printf( esc_html__( '%d to %d', 'kit' ), $post_count_start, $post_count_end );
echo "</strong> ";
_e("from total results", 'kit');
echo " <strong>" . $wp_query->found_posts. "</strong>";
onny/notizen/programmierung.txt · Last modified: 2020/07/11 15:24 by 10.25.0.1