- 1
Прыщеговно
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
0
Прыщеговно
Explanation: The issue stemmed from two issues one in normpath and the other in os.path.join. It turns out that when normpath (or abspath) gets an absolute path starting with a single slash or 3+ slashes, the result would have a single slash. However, if the input had exactly two leading slashes the output will retain them. This behavior conforms to an obscore passage in the POSIX standard (last paragraph):
A pathname that begins with two successive slashes may be interpreted in an implementation-defined manner, although more than two leading slashes shall be treated as a single slash.
normpath и abspath из os.path
+1
In [42]: os.path.join(r'c:\asd', r'c:\www')
Out[42]: 'c:\\www'
Нахуя???
0
def sql_select_filter(sql, flt, order=None, limit=None, offset=None, group_by=None, lock=None, withSelectWrapper=True):
if withSelectWrapper and group_by is None:
if re.search(r'^\s*select\s+', sql, flags=re.IGNORECASE | re.MULTILINE):
sql = "SELECT * FROM ( " + sql + " ) as z99 "
else:
sql = "SELECT * FROM " + sql + " "
sql = sql.replace("%", '%%')
where, vals = _make_where_conditions(flt)
if where is not None:
sql += " WHERE " + where
if group_by is not None and len(group_by):
sql += " GROUP BY " + ",".join(group_by)
if order is not None and len(order):
order_fields = []
for field, direction in order.items():
order_fields.append(field + " " + direction)
sql += " ORDER BY " + ",".join(order_fields)
if limit is not None:
sql += " LIMIT %s"
vals.append(limit)
if offset is not None:
sql += " OFFSET %s"
vals.append(offset)
if lock is not None:
sql += " FOR " + lock
return sql, vals
Конструктор SQL запроосов, все очень секурно!
0
try:
assert isinstance(tag, bs4.element.Tag)
except AssertionError:
raise TypeError
−2
import json
import time
import requests
from multiprocessing.dummy import Pool as ThreadPool
max_threads = 10
fname = "data.json"
headers = {"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36", "referer":"https://datmusic.xyz/?q=Home+resonance", "authority":"api-2.datmusic.xyz"}
def api(url):
while True:
try:
r = requests.get(url, headers=headers)
r = r.json()
if r['status'] == 'error':
pass
else:
return r['data'][0]['download']
except Exception as e:
pass
def download(a):
# open in binary mode
while True:
try:
with open(a[1]+".mp3", "wb") as file:
response = requests.get(a[0],headers=headers)
if not (response.status_code == 503):
file.write(response.content)
print(a[1],"downloaded")
break
else:
pass
except Exception as e:
pass
songs = []
with open(fname) as json_data:
data = json.load(json_data)
for mp3 in data['list']:
song = []
autor = mp3[4]
title = mp3[3][:-5]
song.append(autor)
song.append(title)
songs.append(song)
links = []
def linker(a):
song = []
link = api("https://api-2.datmusic.xyz/search?q=" + a[0] + "+" + a[1] + "&page=0")
song.append(link)
song.append(a[0] + ' - ' + a[1])
links.append(song)
print(a[1])
for a in songs:
linker(a)
#if len(links) > 10:
# break
pool = ThreadPool(max_threads)
results = pool.map(download, links)
pool.close()
pool.join()
#Наговнокодил загрущик плейлистов с контача. Как получить json плейлиста подумай сам (перейди в музыку, открой Network в f12 и мониторь запрос при открытии плейлиста)
#Парсер 1 поточный, загрущик многопоточный. Работает через апи datmusic.xyz спс им
#vk.com music downloader v1.0a
#загрущик музыки вк
json = https://gist.githubusercontent.com/alekxeyuk/a1ccd2c62ab56a71320a02582cfc06f9/raw/4f2622c4beeddfa7e3082c276e1c138c87478e83/data.json
−2
secs = 0
fsecs = 0.0
mins = 40
lastsecs = 0
prevsecs = 0
def getTimeStr() :
def f ( x ) :
if ( 10 <= x <= 19 ) : return ''
y = x % 10
if ( y == 1 ) : return 'а'
if ( 2 <= y <= 4 ) : return 'ы'
return ''
return 'Время: %d минут%s %d секунд%s' % ( mins , f ( mins ) , secs , f ( secs ) )
def updateTimer() :
global timeString , root , secs , fsecs , lastsecs , prevsecs , mins
if ( fin ) : return
prevsecs , lastsecs = lastsecs , clock()
t = secs
if ( fsecs > 0 ) :
fsecs -= lastsecs - prevsecs
secs = int ( fsecs )
elif ( mins > 0 ) :
mins -= 1
fsecs = 60 + fsecs - lastsecs + prevsecs
secs = int ( fsecs )
else :
finish()
if ( secs == t ) :
timeString [ 'text' ] = getTimeStr()
root.after ( 100 , updateTimer )
Святая Питония и tkinter
−1
from itertools import *
lines = tuple ( chain ( ( tuple ( product ( *g ( range ( 3 ) , ( i , ) ) ) ) for g in ( lambda i , j : ( i , j ) , lambda i , j : ( j , i ) ) for i in range ( 3 ) ) , ( ( ( 0 , 0 ) , ( 1 , 1 ) , ( 2 , 2 ) ) , ( ( 2 , 0 ) , ( 1 , 1 ) , ( 0 , 2 ) ) ) ) )
def aimove ( table , i , j ) :
from random import choice
possiblewin = ( lambda x : ( lambda f : ( lambda x : len ( x ) and x [ 0 ] ) ( tuple ( filter ( lambda x : x , map ( f , lines ) ) ) ) ) ( lambda k : 2 == sum ( table.get ( i ) == x for i in k ) and ( lambda e : len ( e ) == 1 and e [ 0 ] ) ( tuple ( i for i in k if not table.get ( i ) ) ) ) )
return ( ( 1 , 1 ) if ( 1 , 1 ) not in table.keys() else possiblewin ( -1 ) or possiblewin ( 1 ) or ( lambda : ( lambda x : x if table.get ( x ) == None else ( lambda x : len ( x ) and x [ 0 ] ) ( tuple ( filter ( lambda x : not table.get ( x ) , permutations ( ( 0 , 2 ) ) ) ) ) ) ( ( 2 * ( i == 0 ) , 2 * ( j == 0 ) ) ) ) () or ( lambda : choice ( tuple ( filter ( lambda x : x not in table.keys() , product ( *tee ( range ( 3 ) ) ) ) ) ) ) () )
iseog = lambda table : ( lambda x : len ( x ) and x [ 0 ] ) ( tuple ( filter ( lambda x : abs ( x ) == 3 , ( sum ( table [ ij ] for ij in keys if table.get ( ij ) ) for keys in lines ) ) ) ) or len ( table ) >= 9
table = {}
eog = 0
while not eog :
i , j = map ( int , input ( "введите координаты: " ) .split() )
if ( i , j ) in table.keys() :
print ( "эта клетка занята" )
continue
if i not in range ( 3 ) or j not in range ( 3 ) :
print ( "неправильные координаты" )
continue
table [ i , j ] = 1
eog = iseog ( table )
if not eog :
table [ aimove ( table , i , j ) ] = -1
eog = iseog ( table )
for ij in product ( *tee ( range ( 3 ) ) ) :
print ( ( " " , "x" , "o" ) [ table.get ( ij ) or 0 ] , end = ( " | " , " | " , "\n" ) [ ij [ 1 ] ] )
if ij [ 0 ] < 2 and ij [ 1 ] == 2 :
print ( "--+---+--" )
print ( ( "ничья. тебе везёт ( пока что )" , "ты победил. ах ты жульник!" , "ты продул, а я победил. бе-бе-бе!" ) [ eog // 3 ] )
Лямбда. Лямбда. Хуямбда.
0
class Task:
def set_activity( activity_method ):
# проанализировать исходный код activity_method
# разделить цепочку команд на N частей
pass
def _get_parts_number():
return N
def _run_part( part_num ):
# выполнить часть part_num
pass
def run(tasks):
execution = True
part_num = 0
while execution:
execution = False
for task in tasks:
if part_num < task._get_parts_number():
task._run_part( part_num )
execution = True
part_num += 1
Попросил коллегу реализовать concurrency многозадачность, он на питоне нагавнякал такое.
0
def create_delta(self, timestamp, subs: set):
sym_subs = subs.symmetric_difference(self.subs)
added_subs = sym_subs.difference(self.subs)
removed_subs = sym_subs.difference(subs)
return DeltaEntry(timestamp, added_subs, removed_subs)
0
def calc ( x ) :
if type ( x ) is not list :
return x
if len ( x ) == 0 :
return x
while type ( x [ 0 ] ) is list :
x = x [ 0 ] + x [ 1: ]
c = x [ 0 ]
print ( x )
if c == 'I' :
if len ( x ) <= 1 :
return x
return calc ( x [ 1: ] )
elif c == 'K' :
if len ( x ) <= 2 :
return x
return calc ( [ x[1] ] + x [ 3: ] )
elif c == 'W' :
if len ( x ) <= 2 :
return x
return calc ( x[1:3] + x[ 2: ] )
elif c == 'S' :
if len ( x ) <= 3 :
return x
return calc ( [ x[1] , x [3] , [ x[2] , x[3] ] ] + x [ 4: ] )
elif c == 'B' :
if len ( x ) <= 3 :
return x
return calc ( [ x[1] , [ x[2] , x[3] ] ] + x[4:] )
elif c == 'C' :
if len ( x ) <= 3 :
return x
return calc ( [ x[1] , x[3] , x[2] ] + x[ 4 : ] )
return [ c ] + calc ( x [ 1: ] )
def parse ( s , n = 0 ) :
res = []
i = n
while i < len ( s ) :
if s [ i ] == '(' :
t = parse ( s , i + 1 )
res.append ( t [ 0 ] )
i = t [ 1 ] - 1
elif s [ i ] == ')' :
return ( res , i + 1 )
else :
res.append ( s [ i ] )
i += 1
return ( res , i )
print ( '>> ' , end = '' )
while True :
for i in calc ( parse ( input() ) [ 0 ] ) :
print ( i , end = '' )
print ( '\n>> ' , end = '' )
Вычисляэ комбинаторныэ термы, и выдаё промежности, типа:
>> S(SKK)(SKK)x
['S', ['S', 'K', 'K'], ['S', 'K', 'K'], 'x']
['S', 'K', 'K', 'x', [['S', 'K', 'K'], 'x']]
['K', 'x', ['K', 'x'], [['S', 'K', 'K'], 'x']]
['x', [['S', 'K', 'K'], 'x']]
['S', 'K', 'K', 'x']
['K', 'x', ['K', 'x']]
['x']
xx