[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
Script General
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 35
Thread images: 5
So, /g/, a while back there was this thread in which people were showing off cool linux scripts and/or python scripts. I figured it was time to start that up again. So, /g/, show me your scripts.

Rules:
>explain what the code does
>no malicious code unless explained to be
>if copypasta give credit

I'll start. This one finds the average color of the gnome de then sets your terminal background as the color.
#!/usr/bin/python2

from PIL import Image
import os
import re

def compute_average_image_color(img):
width, height = img.size

r_ave = 0
g_ave = 0
b_ave = 0

for x in range(0, width):
for y in range(0, height):
r, g, b = img.getpixel((x,y))
r_ave = (r + r_ave) / 2
g_ave = (g + g_ave) / 2
b_ave = (b + b_ave) / 2

return (r_ave, g_ave, b_ave)
location = os.popen('gsettings get org.gnome.desktop.background picture-uri')
loc_mod = location.read()
loc_mod = loc_mod[8:-2]
img = Image.open(loc_mod)
img = img.resize((200,100)) # Small optimization
average_color = compute_average_image_color(img)
average_color = """ "'rgb """ + str(average_color) + """ '" """
average_color = re.sub(' ', '', average_color)
output = "dconf write /org/gnome/terminal/legacy/profiles:/:68776a23-af20-4589-a2b9-6ee6622a8ffc/background-color " + average_color
os.system(output)
>>
command_not_found_handle() {
echo -e ">implying error"
return 127
}

.bashrc, this code changes the output if you type in some command that doesn't exist for example. -e option if you want to use color-codes.
>>

makezip()
{
zip -r "${1%%/}.zip" "$1";
}
maketar()
{
tar cvzf "${1%%/}.tar.gz" "${1%%/}/";
}
extract()
{
if [ -f $1 ] ; then
case $1 in
*.tar.bz2) tar xvjf $1 ;;
*.tar.gz) tar xvzf $1 ;;
*.bz2) bunzip2 $1 ;;
*.rar) unrar x $1 ;;
*.gz) gunzip $1 ;;
*.tar) tar xvf $1 ;;
*.tbz2) tar xvjf $1 ;;
*.tgz) tar xvzf $1 ;;
*.zip) unzip $1 ;;
*.Z) uncompress $1 ;;
*.7z) 7z x $1 ;;
*) echo "'$1' >extract< failed" ;;
esac
else
echo "'$1' not valid"
fi
}

.bashrc for easier extracting and packaging.
>>

function lowercase()
{
for file ; do
filename=${file##*/}
case "$filename" in
*/*) dirname==${file%/*} ;;
*) dirname=.;;
esac
nf=$(echo $filename | tr A-Z a-z)
newname="${dirname}/${nf}"
if [ "$nf" != "$filename" ]; then
mv "$file" "$newname"
echo "lowercase: $file --> $newname"
else
echo "lowercase: $file not changed."
fi
done
}
function swap()
{
local TMPFILE=tmp.$$

[ $# -ne 2 ] && echo "swap: 2 arguments needed" && return 1
[ ! -e $1 ] && echo "swap: $1 does not exist" && return 1
[ ! -e $2 ] && echo "swap: $2 does not exist" && return 1

mv -v "$1" $TMPFILE
mv -v "$2" "$1"
mv -v $TMPFILE "$2"
echo "Done: $1 & $2 switched filenames!!!"
}
function calc()
{
awk "BEGIN{print $*}";
}

lowercase does what it says, swap [file1] [file2] changes the filenames between two files, calc is a simple calculator with awk
>>
this one is a batch-script. You can use it to hide .rar files in .png files.
Open up the final image with winrar/7zip and you can use the archive in it.

copy /B 2.png + 1.rar hidden_archive_in_pic.png
>>
shopt -s autocd

at the top of your .bashrc means that you never need to type "cd". /var/somewhere lets you auto-change-directory
>>
little colortest scripts

colortest()
{
#!/bin/bash
#https://github.com/mikker/dotfiles/blob/master/bin/colortest.sh
#
# This file echoes a bunch of color codes to the
# terminal to demonstrate what's available. Each
# line is the color code of one forground color,
# out of 17 (default + 16 escapes), followed by a
# test use of that color on all nine background
# colors (default + 8 escapes).
#
if [ $1 ]
then
T=$1
else
T='gYw' # The test text
fi
echo -e "\n 40m 41m 42m 43m\
44m 45m 46m 47m";

for FGs in ' m' ' 1m' ' 30m' '1;30m' ' 31m' '1;31m' ' 32m' \
'1;32m' ' 33m' '1;33m' ' 34m' '1;34m' ' 35m' '1;35m' \
' 36m' '1;36m' ' 37m' '1;37m';
do FG=${FGs// /}
echo -en " $FGs \033[$FG $T "
for BG in 40m 41m 42m 43m 44m 45m 46m 47m;
do echo -en "$EINS \033[$FG\033[$BG $T \033[0m";
done
echo;
done
echo
}
colortest2()
{
#http://bitmote.com/index.php?post/2012/11/19/Using-ANSI-Color-Codes-to-Colorize-Your-Bash-Prompt-on-Linux
#!/bin/bash
#
# generates an 8 bit color table (256 colors) for reference,
# using the ANSI CSI+SGR \033[48;5;${val}m for background and
# \033[38;5;${val}m for text (see "ANSI Code" on Wikipedia)
#
echo -en "\n + "
for i in {0..35}; do
printf "%2b " $i
done
printf "\n\n %3b " 0
for i in {0..15}; do
echo -en "\033[48;5;${i}m \033[m "
done
#for i in 16 52 88 124 160 196 232; do
for i in {0..6}; do
let "i = i*36 +16"
printf "\n\n %3b " $i
for j in {0..35}; do
let "val = i+j"
echo -en "\033[48;5;${val}m \033[m "
done
done
echo -e "\n"
}
>>
>>51790589
>
    else
echo "'$1' not valid"

Should ask the user for a file, not saying that it's invalid.
>extract
> not valid
>>
Ive been using Z with fish lately

You can access folders you frequent with a shortcut

like /home/user/school/project2

you can just use z project2 .

Saves a lot of time especially with fish

https://github.com/rupa/z
>>
>>51790573
Oh I'm gonna love this

>>51790589
Pretty cool

>>51790150
Also, OP here. I realized that the gnome wallpaper location call includes URL special characters so it need this above the image opening.
import urllib
loc_mod = urllib.unquote(loc_mod)
>>
>>51790150

this is nice.
>>
>>51790589
You know there's an "a" option to tar? It guesses compression from the extension.

# a = auto detect
tar axvf file.tar.xz […] # eXtract
tar acvf file.tar.gz <…> # Create

# For zip & rar
7z x file.rar […] # eXtract
7z a file.zip <…> # Append
>>
>>51791244
I didn't know. That is cool!
>>
>>51790150
You're not averaging. The last 5 pixels are responsible for 97% of the final "average" color, because you're giving each new pixel the same weight as the combination of all pixels before it.
>>
>>51790664
That's clever
>>
>>51790664
Or for a real operating system
cat 2.png 1.rar > hidden_archive_in_pic.png
>>
>>51793081
This. Better option is to add everything and divide by max at the end, or just divide by a flat amount and add as you go.
>>
There is a doge script I found a while back
## install python-pip here
# pip install doge
>>
>>51793081
Oh shit, you are totally right. Hold on a few.
>>
>>51790767
Pretty neat
>>
>linux scripts
you mean GNU scripts?
>>
This keeps fucking up. Trying to copy the folder im working on in Documents to the Nginx folder but I can't get it to work due to sudo.
#/bin/bash
#Always backup html folder before running script
cd /usr/share/nginx/html
sudo rm -rf index.html tech.html sport.html
cd /home/j/Documents/html
sudo mv index.html tech.html sport.html /usr/share/nginx/html
cd /usr/share/nginx/html
sudo cp index.html tech.html sport.html /home/j/Documents/html/
>>
This is a script I stole off of Stack Exchange.

When running, it checks if a USB device has been mounted, and if so it opens a terminal to the mounted directory. Works in Ubuntu.

#!/usr/bin/env python3
import os
import subprocess
import time
home = os.environ["HOME"]

def get_mountedlist():
return [(item.split()[0].replace("├─", "").replace("└─", ""),
item[item.find("/"):]) for item in subprocess.check_output(
["lsblk"]).decode("utf-8").split("\n") if "/" in item]

def identify(disk):
command = "find /dev/disk -ls | grep /"+disk
output = subprocess.check_output(["/bin/bash", "-c", command]).decode("utf-8")
if "usb" in output:
return True
else:
return False

done = []
while True:
mounted = get_mountedlist()
new_paths = [dev for dev in mounted if not dev in done and not dev[1] == "/"]
valid = [dev for dev in new_paths if identify(dev[0]) == True]
for item in valid:
os.chdir(item[1])
subprocess.call(["gnome-terminal"])
os.chdir(home)
done = mounted
time.sleep(2)
>>
File: 1448985092426.jpg (137 KB, 507x655) Image search: [Google]
1448985092426.jpg
137 KB, 507x655
>>51793351
sudo chmod a+w /usr/share/nginx/html/*.html
for i in ~/j/Documents/html/*.html; do cat $i > /usr/share/nginx/html/$(basename $i); done

cd /usr/share/nginx/html
ln -s ~/j/Documents/html/*.html .
>>
>>51793528
*Tips fedora*
Thank you sir !
>>
File: cl_00.webm (3 MB, 853x480) Image search: [Google]
cl_00.webm
3 MB, 853x480
Convert a bunch of video files to mkv.

#!/bin/bash
#Requires mkvtoolnix
find -type f -name '*.ogm' | {
while read filename ; do
mkvmerge -o "${filename%.ogm}.mkv" "$filename"
done
}


You can change the extension to match the file you want to convert.
>>
File: heykidimacomputer.jpg (2 MB, 3000x2000) Image search: [Google]
heykidimacomputer.jpg
2 MB, 3000x2000
I guess this is the right thread to ask in. I have a collection of FLAC files (already backup elsewhere) that I want to convert to Opus.
The directory structure looks like this:
~/Music/FLAC
|\_ Artist
| |\_ Album
| |\_ track_1.flac
| |\_ track_2.flac
| |\_ cover.jpeg
|\_ Artist 2
| |\_ Album 2
| |\_ track_1.flac
| |\_ track_2.flac
| |\_ cover.jpeg


I want it to become this:
~/Music/OPUS
|\_ Artist
| |\_ Album
| |\_ track_1.opus
| |\_ track_2.opus
| |\_ cover.jpeg
|\_ Artist 2
| |\_ Album 2
| |\_ track_1.opus
| |\_ track_2.opus
| |\_ cover.jpeg


Sure, I can manually go through every directory containing FLAC files and use
ls -1 *.flac | parallel --eta opusenc --bitrate 256K '{}' '{.}.opus' && rm *.flac;
but that takes WAY too fucking long.

Can any bash gurus help me out?
>>
>>51793967
Just use find instead of ls.
>>
>>51794039
How?
>>
>>51793967
https://github.com/cmcginty/flacsync
or anything on github
>>
>>51794059
Just drop it in where you're using ls. As in
find -type f -name "*.flac" | parallel your command
>>
>>51794164
That's what I assumed. Thanks, man.
I used
find -iname '*.flac' | parallel --eta opusenc --bitrate 256K '{}' '{.}.opus';

Now how can I remove the flac files?
>>
>>51794192
>>51794164
Nevermind, I got it.

>>
>>51793411
What do you use it for?
>>
>>51793224
>>51793182
>>51793081
OP again, and I know I suck dick. I fixed the average thing and realized that averaging sucks. So my new method just picks the highest occurring color. Works technically better than the original, and way better then true averaging.
#!/usr/bin/python2

from PIL import Image
import os
import re
import urllib

forg_glo = 0
def compute_average_image_color(img):
width, height = img.size
pixels = img.getcolors(width * height)
avg_pix = pixels[0]
for i, color in pixels:
if i > avg_pix[0]:
avg_pix = (i, color)
#compare("Most Common", img, avg_pix[1])
(count, (r, g, b)) = avg_pix
if (((r > 220) and (g > 220)) and (b > 220)):
r_inv = 255 - r
g_inv = 255 - g
b_inv = 255 - b
ria = (r_inv + g_inv + b_inv) / 3
os.system("""dconf write /org/gnome/terminal/legacy/profiles:/:68776a23-af20-4589-a2b9-6ee6622a8ffc/foreground-color "'rgb(""" + str(ria) + "," + str(ria) + "," + str(ria) + """)'" """)
else:
os.system("""dconf write /org/gnome/terminal/legacy/profiles:/:68776a23-af20-4589-a2b9-6ee6622a8ffc/foreground-color "'rgb(255,255,255)'" """)
return (r, g, b)
location = os.popen('gsettings get org.gnome.desktop.background picture-uri')
loc_mod = location.read()
loc_mod = loc_mod[8:-2]
loc_mod = urllib.unquote(loc_mod)
img = Image.open(loc_mod)
img = img.resize((250,250)) # Small optimization
average_color = compute_average_image_color(img)
average_color = """ "'rgb """ + str(average_color) + """ '" """
average_color = re.sub(' ', '', average_color)
output = "dconf write /org/gnome/terminal/legacy/profiles:/:68776a23-af20-4589-a2b9-6ee6622a8ffc/background-color " + average_color
os.system(output)
Thread replies: 35
Thread images: 5

banner
banner
[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y] [Home]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.