Site Tools


onny:notizen:programmierung

python

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)")
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")

requests

import requests
upstream_head = requests.head(upstream_url+url_param)
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'])
    upstream_head = requests.head(upstream_url + upstream_head.headers['location'])
if (upstream_head.headers['content-type'] == "text/html;charset=UTF-8" or upstream_head.headers['content-type'] == "text/html; charset=UTF-8"):
    upstream_response = upstream_response.replace("//thepiratebay.org","")

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():
    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

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)

javascript

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

javascript document ready

$(document).ready(function(){
  console.log('ready');
});

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

trim string to max length

var string = string.substring(0,100);

vuejs

add data to attribute string, for example ``<a href``

<a :href="`#/browse/show/${getEpisode.podcastid}/${getEpisode.id}`">{{ getEpisode.title }}</a>

on click change route

<div
	v-lazy:background-image="getEpisode.imgURL"
	class="playerThumb"
	@click="$router.push(`/browse/show/${getEpisode.podcast_id}/${getEpisode.id}`)" />

watch data or property change

props: {
	podcasts: {
		type: Array,
		default() { return [] },
	},
},
watch: {
	podcasts(newValue, oldValue) {
		const slider = this.$refs.slider
		console.log(slider.scrollLeft, slider.scrollWidth, slider.clientWidth)
		if (slider.scrollWidth > slider.clientWidth) {
			this.showNext = true
		}
	},
},

reference html element

<div class='cart-list' ref="cartList"></div>
 
[...]
 
export default {
  name: 'Cart',
  computed: {
    isOverflowing() {
      var element = this.$refs.cartList;
      return (element.offsetHeight < element.scrollHeight || element.offsetWidth < element.scrollWidth)
    }
  }
};

commit / pass more than one parameter to store action-method

methods: {
	...mapActions([
		'queryEpisodes',
		]),
 
	async loadEpisodes(page) {
		const response = await this.queryEpisodes({ page, sortBy: 'pubdate' })
		[...]
	},
 
# store/episodes.js:
 
actions: {
	async queryEpisodes({ commit, getters }, { page, sortBy } = {}) {
		const response = await episodeApiClient.queryEpisodes(null, page, sortBy)
		[...]
	},

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

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

popover menu

.main-navigation ul li ul.sub-menu {
	opacity: 0;
	position: absolute;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);
	transition:opacity 250ms ease-out;
	padding: 20px;
	z-index: 2;
	left: 17px;
	background: white;
}
 
.main-navigation ul li:hover ul.sub-menu {
	opacity: 1;
	transition:opacity 250ms ease-out;
}

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

foreach loop

foreach($this->service->findAll($this->userId) as $station) {
	$this->logger->error($station);
	$track = $trackList->addChild('track');
	$track->addChild('location', 'http://localhost/test.mp3');
	$track->addChild('title', 'Radio Test 404fm');
	$track->addChild('image', 'http://localhost/favicon.ico');
}

get array length

var_dump(count($a));

get type of variable

foreach($data as $episode) {
	$this->logger->error(gettype($episode));	
}

convert string to int

intval("12345");

convert array to string

foreach($data as $episode) {
	$this->logger->error(implode(",", $episode));	
}

nextcloud app dev

logging, available methods: emergency, alert, critical, error, warning, notice, info, debug

use OCP\ILogger;
 
class EpisodeController extends Controller {
 
	/** @var ILogger */
	private $logger;
 
[...]
 
	public function __construct(IRequest $request,
								EpisodeService $service,
								FyydApiService $fyydapi,
								ILogger $logger,
								$userId) {
		parent::__construct(Application::APP_ID, $request);
		$this->service = $service;
		$this->fyydapi = $fyydapi;
		$this->logger = $logger;
		$this->userId = $userId;
	}
 
[...]
 
        public function log($message) {
            $this->logger->error($message);
            /* $this->logger->error($message, ['extra_context' => 'my extra context']); */
        }

wordpress

registering menus

functions.php
if ( ! function_exists( 'iaro_setup' ) ) :
 
	function iaro_setup() {
 
                [...]
 
		register_nav_menus(
			array(
				'menu-1' => esc_html__( 'Primary', 'iaro' ),
				'menu-2' => esc_html__( 'Secondary', 'iaro' ),
			)
		);
 
                [...]

customize menu entries, wrap entry into span element

functions.php
		add_filter('nav_menu_item_args', function ($args, $item, $depth) {
	    if ($args->theme_location == 'menu-1' || $args->theme_location == 'menu-2') {
	        $title             = apply_filters('the_title', $item->title, $item->ID);
	        $args->link_before = '<span>';
	        $args->link_after  = '</span>';
	    }
	    return $args;
		}, 10, 3);

check if query is front page

if ( is_front_page() ) :
    get_header( 'front' );
else :
    get_header();
endif;

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

delete specific row

delete from oc_storages where numeric_id=58;

remove user

DROP USER 'bloguser'@'localhost';

postgresql

drop database

sudo -u postgres -i
dropdb onlyoffice
onny/notizen/programmierung.txt · Last modified: 2021/06/05 17:28 by 2a02:8071:3eb9:a600:2927:7e8f:694a:b9d0