Site Tools


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

window.onclick = function(event) {
  if (event.target.closest('.search')) {
  };
};

split up javascript files

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

jquery select by attribute content

$( "tr[data-id='"+data[station]["stationid"]+"']" ).remove();

jquery select dynamicly loaded ajax elements

$('body').on('click','.btn + :not([class=disabled])', function() {
  var link = $(this).attr('src');
  load_page(link);
});

jquery set background color

$(this).parent().css("background-color", "yellow");

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();
  })
}

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;
    }
 
    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

  display: flex;
  justify-content: center;
  align-items: center;

advanced

      body {
        margin: 0 !important;
        padding: 0 !important;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        opacity: 1;
        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

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");
onny/notizen/programmierung.txt · Last modified: 2019/10/03 09:34 by 141.52.249.1