seq_id
stringlengths
4
11
text
stringlengths
113
2.92M
repo_name
stringlengths
4
125
sub_path
stringlengths
3
214
file_name
stringlengths
3
160
file_ext
stringclasses
18 values
file_size_in_byte
int64
113
2.92M
program_lang
stringclasses
1 value
lang
stringclasses
93 values
doc_type
stringclasses
1 value
stars
int64
0
179k
dataset
stringclasses
3 values
pt
stringclasses
78 values
40521294695
import sys sys.path.append("..") from common import * opsm = { "+": lambda *v: sum(v), "*": lambda *v: mult(v) } def toks(str): tokens = [] for ch in str: if ch.isnumeric(): tokens.append(int(ch)) else: tokens.append(ch) return tokens def atom(toks): curr = toks.pop(0) if ...
archanpatkar/advent2020
Day-18/part2.py
part2.py
py
1,099
python
en
code
0
github-code
36
29790427487
import json from flask import Flask, request from flask_cors import CORS from queue import Queue from helpers.utils import utils from helpers.db import queries from helpers.algo import boundary from helpers.algo import neighbours from helpers.algo import degrees_count from helpers.algo.new_hex_loc import* app = Flas...
ricksr/cluster-anywhr
cluster/app.py
app.py
py
11,777
python
en
code
1
github-code
36
13966927417
from itertools import combinations def make_combinations_set(order, menu_num): result = set() menus = sorted([ch for ch in order]) comb_menu = combinations(menus, menu_num) for each_comb in comb_menu: result.add(''.join(each_comb)) # print(result) return result def solution(orders, c...
Devlee247/NaverBoostCamp_AlgorithmStudy
week5/P01_myeongu.py
P01_myeongu.py
py
1,634
python
en
code
1
github-code
36
74174195942
#!/usr/bin/python3 """ square class """ from models.rectangle import Rectangle class Square(Rectangle): """ class """ def __init__(self, size, x=0, y=0, id=None): """ square construct """ super().__init__(size, size, x, y, id) def __str__(self): """ string rep """ ...
humeinstein/holbertonschool-higher_level_programming
0x0C-python-almost_a_circle/models/square.py
square.py
py
2,114
python
en
code
0
github-code
36
33968414347
class Point: MAX_COORD = 100 MIN_COORD = 0 def __init__(self, x, y): self.x = x self.y = y def set_coord(self, x, y): if self.MIN_COORD <= x <= self.MAX_COORD and self.MIN_COORD <= y <= self.MAX_COORD: self.x = x self.y = y def set_min_coord(self, m...
ivannumberone7/my_oop
7.py
7.py
py
853
python
ru
code
0
github-code
36
13866614560
import datetime from sqlalchemy import Column, Integer, String, DateTime, ForeignKey from sqlalchemy.orm import relationship from app.db.base_model import Base class ArticleModel(Base): __tablename__ = "articles" id = Column(Integer, primary_key=True, autoincrement=True) title = Column(String(255)) ...
matheus-feu/FastAPI-JWT-Security
app/models/article.py
article.py
py
753
python
en
code
3
github-code
36
14129279608
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import sqlite3 from datetime import datetime db_name = 'dbmovie{0}.db'.format(str(datetime.now())[:10].replace('-', '')) cla...
zenmeder/dbmovie
dbmovie/pipelines.py
pipelines.py
py
1,434
python
en
code
0
github-code
36
25168770770
#!/usr/bin/env python3 a, b = 65, 8921 a, b = 703, 516 a_fac, b_fac = 16807, 48271 div = 2147483647 _a, _b = a, b matches = 0 for i in range(40000000): _a = (_a * a_fac) % div _b = (_b * b_fac) % div match = 1 if (_a ^ _b) & 0xffff == 0 else 0 #print(_a, _b, match) matches += match print('part1', ...
piratejon/toyproblems
adventofcode/2017/15/solve.py
solve.py
py
651
python
en
code
1
github-code
36
6689643445
import os import uuid import json import minio import logging class storage: instance = None client = None def __init__(self): try: """ Minio does not allow another way of configuring timeout for connection. The rest of configuration is copied from source code ...
spcl/serverless-benchmarks
benchmarks/wrappers/openwhisk/python/storage.py
storage.py
py
2,464
python
en
code
97
github-code
36
5213215500
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: seen_set = set() longest = 0 start, end = 0, 0 l = len(s) while start < l and end < l: if s[end] not in seen_set: seen_set.add(s[end]) end += 1 longe...
tugloo1/leetcode
problem_3.py
problem_3.py
py
461
python
en
code
0
github-code
36
31167909236
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as pl n = [] e = [] ep = [] with open('cohesive.txt') as file: next(file) for line in file: value = line.strip().split(' ') n.append(int(value[0])) e.append(float(value[1])) ep.append(float(value[2])) n = [int(i) ...
leschultz/MSE760
hw1/cohesiveplot.py
cohesiveplot.py
py
640
python
en
code
0
github-code
36
43508294902
import sys from pathlib import Path sys.path.append(Path(__file__).resolve().parents[2]) # rel imports when in package if __name__ == '__main__' and __package__ is None: __package__ = 'kuosc' print(Path(__file__).resolve()) print(__package__) # from kurosc.lib.plotformat import setup
chriswilly/kuramoto-osc
Python/kurosc/kurosc/tests/pathtest.py
pathtest.py
py
293
python
en
code
2
github-code
36
31556431228
from copy import deepcopy import numpy as np from qode.fermion_field import occ_strings from qode.fermion_field.state import state, dot, resolvent from hamiltonian import hamiltonian, SD_excitations # Energy calculated from Q-Chem 4.3: # SCF energy in the final basis set = -2.8551604262 # CCSD total energy ...
sskhan67/GPGPU-Programming-
QODE/Applications/component_tests/ccsd/attic/non_linear_opt_w_state_arithmetic.py
non_linear_opt_w_state_arithmetic.py
py
1,599
python
en
code
0
github-code
36
44647926786
import boto3 import json from decimal import Decimal from boto3.dynamodb.conditions import Key dynamodb = boto3.resource('dynamodb') attendance_table = dynamodb.Table('attendance_table_user') #queryで特定のuser_idの出社予定取ってくる def query_attendance(id): result = attendance_table.query( KeyConditionExpressio...
SOICHI0826/kinikare_server
lambdafunction/get_attendance.py
get_attendance.py
py
957
python
en
code
0
github-code
36
74436411945
import os from pathlib import Path import pandas as pd import numpy as np from matplotlib import pyplot as plt from shutil import copyfile config = { # General 'symbol': 'spy', 'symbol_name': 'S&P500', 'category': {'unespecified': ['spy']}, # 'gld', 'spy','xle', 'emb','dia', 'qqq', 'ewp' 'extensi...
cetrulin/Quant-Quote-Data-Preprocessing
src/select_mahab_series.py
select_mahab_series.py
py
16,131
python
en
code
0
github-code
36
21140466023
# считывание списка из входного потока a = '3 Сергей', '5 Николай', '4 Елена', '7 Владимир', '5 Юлия', '4 Светлана' lst_in = list(a) print(lst_in) B = [i.split() for i in lst_in] print(B) F = [i.split()[0] for i in lst_in] print(F) d = dict.fromkeys(F) # d_key = list(d) # for i in range(len(d)): # C = [] # for...
Tosic48/FirstProject
HW/dict.py
dict.py
py
574
python
ru
code
0
github-code
36
947943428
#!/usr/bin/env python3 import requests import bs4 base_url = "https://quotes.toscrape.com/page/{}/" authors = set() quotations = [] for page_num in range(1,2): page = requests.get(base_url.format(page_num)) soup = bs4.BeautifulSoup(page.text,'lxml') boxes = soup.select(".quote") #selected all the qu...
SKT27182/web_scaping
get_quotes_author.py
get_quotes_author.py
py
751
python
en
code
0
github-code
36
11210169685
from django.conf import settings from travels import models from django.utils.html import escapejs def project_settings(request): project_settings = models.Settings.objects.all()[0] return { 'project_settings' : project_settings } def settings_variables(request): ''' Provides base URLs for use in templates ''' ...
UNICEF-Youth-Section/Locast-Web-Rio
travels/settings_context_processor.py
settings_context_processor.py
py
754
python
en
code
0
github-code
36
10302851450
l = input("insert list of integers with comma") l = l.lstrip('[').rstrip(']').split(',') sum = 0 temp = 0 for i in range(0, len(l)): l[i] = int(l[i]) sum += l[i] temp += l[i] ** 2 mean = sum / len(l) var = temp / len(l) - mean ** 2 print(f"Means: {mean}") print(f"Variance: {var}") ''' scores = [100, 90, 8...
MyuB/OpenSW_Exercise
week02/ex04_02.py
ex04_02.py
py
569
python
en
code
0
github-code
36
14531544904
mhb_file = open("mhb_gesamt.txt","r",encoding="utf8") mhb_gesamt = mhb_file.read() mhb_file.close() modDescrSeq = mhb_gesamt.split("Modulbezeichnung: ") i = 1 while i<len(modDescrSeq): fileName = "ModDescr_" + str(i) file = open(fileName + ".txt","w") file.write(modDescrSeq[i].strip()) file.close() ...
bmake/modcat-prototyp
dataPrep/InitialMapping/split_mhb.py
split_mhb.py
py
328
python
en
code
2
github-code
36
18190036430
import pandas as pd import Levenshtein import numpy as np from anytree.search import find from utils.category_tree import get_category_tree from utils.io_custom import read_pickle_object from scipy.spatial.distance import cosine import re def find_node(id, tree): return find(tree, lambda node: node.name == id) d...
comptech-winter-school/online-store-redirects
utils/feature_generation.py
feature_generation.py
py
8,101
python
ru
code
3
github-code
36
16018321414
import sys def change(): change = 1000 - int(sys.stdin.readline()) counter = [1, 5, 10, 50, 100, 500] cnt = 0 counter.reverse() for i in counter: if change >= i: current_cnt, change = divmod(change, i) cnt += current_cnt return cnt print(change...
Zikx/Algorithm
Baekjoon/Greedy/change.py
change.py
py
323
python
en
code
0
github-code
36
13909907482
"""Module with lagrangian decomposition methods.""" # Python packages # Package modules import logging as log from firedecomp.AL import ARPP from firedecomp.AL import ADPP from firedecomp.fix_work import utils as _utils from firedecomp.original import model as _model from firedecomp.classes import problem as _problem ...
jorgerodriguezveiga/firedecomp
firedecomp/AL/AL.py
AL.py
py
22,213
python
en
code
0
github-code
36
69833306343
class detail: def __init__(self) -> None: self.__name="harry" a=detail() # print(a.__name) #cannot access directly # print(a._detail__name) #can be accessed indirectly #NAME MANGLING print(a.__dir__()) #from this we see all the available methods on a
Adarsh1o1/python-initials
oops/access_specifiers.py
access_specifiers.py
py
268
python
en
code
1
github-code
36
5128321881
# Задача-2: # Даны два произвольные списка. # Удалите из первого списка элементы, присутствующие во втором списке. lst_1 = [1, 3, 5, 7, 9] lst_2 = [3, 8, 6, 5] new = [] for i in lst_1: if i not in lst_2: new.append(i) lst_1 = new print(lst_1, lst_2)
BocheVskiy/HW3_easy
easy_2.py
easy_2.py
py
351
python
ru
code
0
github-code
36
70390276585
from flask import Flask,render_template,request,jsonify import utils app = Flask(__name__) @app.route('/') #Base API def home(): print('Testing Home API') return render_template('home.html') @app.route('/predict', methods = ['POST']) def prediction(): print('Testing prediction API') data = request.f...
PrashantBodhe/irisproject1
interface.py
interface.py
py
820
python
en
code
0
github-code
36
31062248631
from tkinter import * import os import platform ### FUNCTION TO KILL def stopProg(e): root.destroy() ### FUCNTION THAT DOES CALCULATIONS FOR CENTER OF SCREEN ### AND THEN CENTERS THE WINDOW def center(window,w,h): ws = window.winfo_screenwidth() hs = window.winfo_screenheight() x = (ws/2) - (w/2) y = (hs/2) - (h...
MikeVaughanG/timesheet-input-system
Main.py
Main.py
py
3,648
python
en
code
0
github-code
36
19982458840
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import logging import unittest from tutorons.regex.extract import ApacheConfigRegexExtractor, JavascriptRegexExtractor,\ GrepRegexExtractor, SedRegexExtractor from tutorons.common.htmltools import HtmlDocument logging.basicCo...
andrewhead/tutorons-server
tutorons/tests/regex/test_extractor.py
test_extractor.py
py
8,711
python
en
code
6
github-code
36
16919406854
from rest_framework.parsers import JSONParser from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.decorators import api_view import io from rest_framework import status from todos.models import Task from .serializers import TaskSerializer @api_view(['GET'...
Khot-abhishek/TODO_WITH_API
api/views.py
views.py
py
2,318
python
en
code
0
github-code
36
26938917107
# from microbit import * # from mpu9250 import MPU9250 # from mpu9250 import MPU9250 # imu = MPU9250('X') # while True: # print(imu.accel.xyz) # print(imu.gyro.xyz) # print(imu.mag.xyz) # print(imu.temperature) # print(imu.accel.z) # sleep(1000) from PiicoDev_Unified import sleep_ms from Piic...
alexanderhalpern/educationalrobot
imu.py
imu.py
py
1,299
python
en
code
0
github-code
36
12220208294
from json import loads from logging_tools import Logger from population import create_sample from requests import get from requests import post from requests.auth import HTTPBasicAuth from string import Template from time import sleep from uuid import uuid1 """ Template for the whisk rest api. """ whisk_rest_api = Tem...
mariosky/ga_action
py_client/evolution.py
evolution.py
py
4,228
python
en
code
1
github-code
36
71551898663
from __future__ import annotations import falcon from app.models import Rating from app.schemas.ratings import rating_item_schema class RateResource: deserializers = {"post": rating_item_schema} def on_post(self, req: falcon.Request, resp: falcon.Response, id: int): """ --- summary:...
alysivji/falcon-batteries-included
app/resources/ratings.py
ratings.py
py
1,133
python
en
code
15
github-code
36
44676432785
# Дан список чисел. Если среди них есть ноль - вывести yes, иначе no. my_list = [1, 2, 100, 0, 3] # а можно было запросить у пользователя ввести числа через пробел # my_list = [int(i) for i in input().split()] has_zero = False for i in my_list: if i == 0: has_zero = True break if has_zero: p...
buevichd/tms-lessons
lesson_06/cycles/task_04.py
task_04.py
py
454
python
ru
code
3
github-code
36
38242299725
import os, re, math, sys from collections import defaultdict VCF_CONTIG_PATT = re.compile('ID=(\w+),length=(\d+)') PROG_NAME = 'Hycco' DESCRIPTION = 'Hycco is an HMM based method to estimate hybrid chromosomal crossover points using distinguising SNPs from two parental genotypes' FILE_TAG = 'crossover_regions' DEF...
tjs23/hycco
hycco.py
hycco.py
py
16,851
python
en
code
1
github-code
36
18180968433
# Student Virtual Assistant # Libraries for accessing Google Scholar and scheduling reminders import webbrowser import schedule import time # Function to access Google Scholar def search_scholar(query): webbrowser.open(f"https://scholar.google.com/scholar?q={query}") # Function to input schedule def in...
macnya/Student_virtual_assistant
Student_VA.py
Student_VA.py
py
1,790
python
en
code
0
github-code
36
38777184708
#!/usr/bin/python import csv import json import pprint import re import sys def replace_if_not_empty(dict, key, value): if key not in dict or not dict[key]: dict[key] = value def to_float_or_none(value): # lmao lazy try: return float(value) except ValueError: return None d...
penguinuwu/Mousebase
backend/csv_parser/parse_csv.py
parse_csv.py
py
7,636
python
en
code
1
github-code
36
646308278
#Lista de Exercício 3 - Questão 38 #Dupla: 2020314273 - Cauã Alexandre e 2021327294 - Kallyne Ferro #Disciplina: Programação Web #Professor: Italo Arruda #Um funcionário de uma empresa recebe aumento salarial anualmente: Sabe-se que: #Esse funcionário foi contratado em 1995, com salário inicial de R$ 1.000,00; ...
caalexandre/Revisao-Python-IFAL-2023-Caua-e-Kallyne
Lista3/l3q38CK-523.py
l3q38CK-523.py
py
1,450
python
pt
code
0
github-code
36
38625939524
from tkinter import * from tkinter import messagebox from tkinter import ttk #css for tkinter from configparser import ConfigParser # import io # import urllib.request # import base64 import time import ssl ssl._create_default_https_context = ssl._create_unverified_context import requests weather_url = 'http://a...
superduperkevin/WeatherGUI
weather_app.py
weather_app.py
py
3,867
python
en
code
0
github-code
36
7952291852
from __future__ import annotations import logbook from discord import Interaction from discord import Message from discord.ext.commands import Context from json import dumps from logging import Logger from time import time from utils import send_response from yt_dlp.YoutubeDL import YoutubeDL from yt_dlp import Downlo...
ruubytes/Maon.py
src/track.py
track.py
py
6,962
python
en
code
0
github-code
36
29421162955
import firebase_admin from firebase_admin import credentials, firestore import os from gcloud import storage from pprint import pprint from datetime import datetime import ast from django import template INDEX = 1 INDEX_historic = 1 INDEX_cv = 1 # Setup the connexion to the project cred = credentials.Certificate("./w...
SnipeHR/SnipeHR-github.io
website/query_firestore.py
query_firestore.py
py
12,180
python
en
code
0
github-code
36
29282945445
sayilar=(1,2,4,8,12,50,100) harfler=("a","b","h","f","ğ","r") sonuc=min(sayilar) sonuc=max(sayilar) "minimum ve maximum sonuçlarını söyler" #ekleme sayilar.append(20) harfler.append("p") sayilar.insert(3,11) harfler.insert(4,"c") "append sona ekler insert nereye koymak istersen" #silme sayilar.pop() ...
FMDikici/Python_proje1
formuller_list_methods.py
formuller_list_methods.py
py
775
python
tr
code
0
github-code
36
13042186116
#!/usr/bin/env python """ Datapath for QEMU qdisk """ import urlparse import os import sys import xapi import xapi.storage.api.v5.datapath import xapi.storage.api.v5.volume import importlib from xapi.storage.libs.libcow.datapath import QdiskDatapath from xapi.storage import log def get_sr_callbacks(dbg, uri): u ...
xcp-ng/xcp-ng-xapi-storage
plugins/datapath/qdisk/datapath.py
datapath.py
py
2,192
python
en
code
4
github-code
36
16028301314
import pymongo import os import pandas as pd import json def main(): client = pymongo.MongoClient("mongodb://localhost:27017/") databases = client.list_database_names() if "fifa" not in databases: db = client["fifa"] players_collection = db["players"] ultimate_team_collection = db...
wconti27/DS4300_FIFA_Tool
import_data.py
import_data.py
py
2,486
python
en
code
0
github-code
36
70077095145
from types import SimpleNamespace import random, string, sys ''' To execute the testing function run the code with command line argument test ex. ~$ python change_making.py test For normal usage run the script with an amount as a command line argument ex. ~$ python change_making.py 23.62 ''' class InvalidInputError(E...
chris-hamberg/algorithms_python
greedy.py
greedy.py
py
5,526
python
en
code
0
github-code
36
43429079723
# coding: utf-8 class Queue: def __init__(self): self.tree_list = [] def enqueue(self, tree): self.tree_list.append(tree) def dequeue(self): return self.tree_list.pop(0) def is_empty(self): pass if __name__ == '__main__': tree_list = [] queue = Queue() ...
oamam/atcoder_amama
python/beginner/20140913/20140913D.py
20140913D.py
py
1,297
python
en
code
0
github-code
36
28228486901
lines="hi hello hi hello" # o/p #hai,2 #hello,2 #split function words=lines.split(" ") print(words) dic={} for word in words:#hai hello if(word not in dic):#hai not in dic,hello not in dic dic[word]=1 else: dic[word]+=1 print(dic)
Jesta398/project
collections'/dictionary/wordcount.py
wordcount.py
py
256
python
en
code
0
github-code
36
22729381839
import re from General.utilities import * from General import feedparser def getContentExtend(RssUrl,Pattern, FetchNumber=None): #get the feed FeedContent = cachedFetch(RssUrl) feed = feedparser.parse(FeedContent) FetchList=[] Num=0 reObj=re.compile(Pattern,re.M|re.S|re.U) reObj_noScriptAll = re.compile...
YuJianrong/GAEProjects
FeedsToolsBox/ControlCenter/ContentExtend.py
ContentExtend.py
py
1,065
python
en
code
0
github-code
36
20053563450
# -*- coding: utf-8 -*- """ Created on Fri Sep 28 15:42:03 2018 @author: tf """ from numpy import * import operator import os, sys #2.1 a simple kNN classifier def classify0(inX, dataSet, labels, k): ''' a simple kNN classifier ''' dataSetSize = dataSet.shape[0]; diffMat = tile(inX, (dataSetSize...
Cjh327/Machine-Learning-in-Action
kNN/kNN.py
kNN.py
py
4,174
python
en
code
2
github-code
36
19970778695
import eventlet import msgpack import random from copy import copy from datetime import datetime from . import cmds from . import msgs import os log_file = open(os.path.join(os.getcwd(), 'client.log'), 'w') def write_log(msg): global log_file log_file.write( "{0} - {1}\n".format(datetime.now(), str(...
jason-ni/eventlet-raft
eventlet_raft/client.py
client.py
py
4,133
python
en
code
3
github-code
36
19406180140
# # @lc app=leetcode id=202 lang=python3 # # [202] Happy Number # # @lc code=start class Solution: def isHappy(self, n: int) -> bool: seen = set() while n != 1: res = 0 for digit in str(n): res += int(digit) ** 2 n = res if n in seen: ...
Matthewow/Leetcode
vscode_extension/202.happy-number.py
202.happy-number.py
py
409
python
en
code
2
github-code
36
70562629544
import sys input = sys.stdin.readline def get_primenumber_under(n): is_primes = [False, False] + [True for _ in range(2, n+1)] for i in range(2, int(n**0.5)+1): j = 2 while i*j <= n: if is_primes[i*j]: is_primes[i*j] = False j += 1 return is_primes ...
zsmalla/algorithm-jistudy-season1
src/chapter2/4_기초수학(2)/임지수/15711_python_임지수.py
15711_python_임지수.py
py
1,493
python
ko
code
0
github-code
36
20851705442
# Take the code from the How To Decode A Website exercise # (if you didn’t do it or just want to play with some different code, use the code from the solution), # and instead of printing the results to a screen, write the results to a txt file. # In your code, just make up a name for the file you are saving to. # E...
ismsadek/python-basics
Ex 21.py
Ex 21.py
py
973
python
en
code
1
github-code
36
31527008003
Test_case = int(input()) for t in range(Test_case): N = int(input()) count = [1] * N idx = 0 carrot = list(map(int, input().split())) for i in range(1, N): if carrot[i] > carrot[i-1]: count[idx] += 1 else: idx += 1 max_count = 0 for j in count: ...
Ikthegreat/TIL
Algorithm/0203/9367.py
9367.py
py
434
python
en
code
0
github-code
36
30844385629
""" USC Spring 2020 INF 553 Foundations of Data Mining Assignment 3 Student Name: Jiabin Wang Student ID: 4778-4151-95 """ from pyspark import SparkConf, SparkContext, StorageLevel from trainAuxiliary import * ''' import os import re import json import time import sys import math import random ...
jiabinwa/DSCI-INF553-DataMining
Assignment-3/task3train.py
task3train.py
py
1,215
python
en
code
0
github-code
36
3853684048
# 死锁:一直等待对方释放锁的情景叫做死锁 # 需求:多线程同时根据下标在列表中取值,要保证同一时刻只能有一个线程去取值 import threading lock = threading.Lock() def get_value(index): # 上锁 lock.acquire() my_list = [1, 4, 6] if index >= len(my_list): print('下标越界') return # 取值不成功, 也要释放互斥锁, 不要影响后面进程进行 lock.release() else: ...
Edward-Lengend/python
PycharmProjects/16多任务编程/02线程/py_07_死锁.py
py_07_死锁.py
py
701
python
zh
code
0
github-code
36
19476289451
from tkinter import * from piece import piece window = Tk() labels=[0]*240 for r in range(24): for c in range(10): labels[r*10+c]=Label(window, bg='black', height=1, width=2) labels[r *10+c].grid(row=r,column=c, sticky=S+N+E+W) firstSquare=piece(window, labels, 0, 10,5) window.mainloop()
gegoff/tetris
board.py
board.py
py
311
python
en
code
0
github-code
36
69839957223
from django.conf.urls.defaults import * from django.contrib import admin import os.path admin.autodiscover() MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), "media") urlpatterns = patterns('', (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^admin/', include(admin.site.urls...
friendofrobots/ice-divisi
explore/urls.py
urls.py
py
995
python
en
code
1
github-code
36
28890711101
"""Tool for processing pytd files. pytd is a type declaration language for Python. Each .py file can have an accompanying .pytd file that specifies classes, argument types, return types and exceptions. This binary processes pytd files, typically to optimize them. Usage: pytd_tool [flags] <inputfile> <outputfile> ""...
google/pytype
pytype/pytd/main.py
main.py
py
3,389
python
en
code
4,405
github-code
36
15991432175
"""Point-wise Spatial Attention Network""" import torch import torch.nn as nn up_kwargs = {'mode': 'bilinear', 'align_corners': True} norm_layer = nn.BatchNorm2d class _ConvBNReLU(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, r...
zyxu1996/Efficient-Transformer
models/head/psa.py
psa.py
py
3,539
python
en
code
67
github-code
36
29045421069
# Python class Solution(object): def createTargetArray(self, nums, index): """ :type nums: List[int] :type index: List[int] :rtype: List[int] """ arrList = list() for x in range(0, len(index)): arrList.insert(index[x], nums[x]) ...
richard-dao/Other
LeetCode-Problems/Easy/Target-Array-In-Order.py
Target-Array-In-Order.py
py
345
python
en
code
0
github-code
36
12080387469
from tinydb import TinyDB, Query, where db = TinyDB("data.json", indent=4) db.update({"score": 10}, where ("name") == "Patrick") db.update({"roles": ["Junior"]}) db.update({"roles": ["Expert"]}, where("name") == "Patrick") db.upsert({"name": "Pierre", "score": 120, "roles": ["Senior"]}, where("name") == "Pierre") d...
yunus-gdk/python_beginner
tiny-db/maj.py
maj.py
py
402
python
en
code
0
github-code
36
6877383992
#from IPython.display from PIL import Image from PIL import ImageDraw from PIL import ImageFont from IPython.display import display from IPython.core.display import HTML import json from pprint import pprint import os import time #import md5 import hashlib import os from aliyunsdkcore.profile import region_provider ...
jhs2jhs/AlibabaCloud_ImageSearch_Demo_py2
myutil.py
myutil.py
py
8,204
python
en
code
1
github-code
36
15770209264
# coding: utf-8 # In[ ]: class Weighted_Graph(): """Класс взвешенных графов. Для представления графа используется список ребер Атрибуты: :self.v: int - количество вершин :self.graph: list - список ребер Функции: :add_edge(u,v,w): добавляет ребро весом w между...
annykay/problrms_ROSALND
Bellman_FordAlgo.py
Bellman_FordAlgo.py
py
3,407
python
ru
code
0
github-code
36
73679903143
import telebot from telebot import types import firebase_admin from firebase_admin import credentials from firebase_admin import db bot = telebot.TeleBot("") # Замените на свой токен! DB_URL = '' user_dict = {} class User: def __init__(self, tgid): self.tgid = tgid self.fio_name = ...
psshamshin/CuberClub_BOT
tgbotlastfinal.py
tgbotlastfinal.py
py
4,885
python
ru
code
0
github-code
36
8639664963
# -*- coding: utf-8 -*- # # Virtual Satellite 4 - FreeCAD module # # Copyright (C) 2019 by # # DLR (German Aerospace Center), # Software for Space Systems and interactive Visualization # Braunschweig, Germany # # This program is free software: you can redistribute it and/or modify # it under the ter...
virtualsatellite/VirtualSatellite4-FreeCAD-mod
VirtualSatelliteCAD/json_io/products/json_product_assembly.py
json_product_assembly.py
py
9,732
python
en
code
9
github-code
36
70911138665
#М8О-301Б-19 #Цыкин Иван #Вариант 5 #Эллипсойд from OpenGL.GLUT import * #Подключение библиотек from OpenGL.GL import * from OpenGL.GLU import * import math #константы ngon=60 angle_step=2*math.pi/ngon r1_step = 0.005 r2_step = 0.001 delta=0.6 theta1 = 2*math.pi/ngon xrot = 0.2 yrot = 0.0 d1 = 1 ...
youngtommypickles/ComputerGraphics
CG3.py
CG3.py
py
4,289
python
ru
code
0
github-code
36
38230641429
from __future__ import division, print_function import numpy as np import scipy.linalg from MatrixIO import load, store import click def lqr(A,B,Q,R): """Solve the continuous time lqr controller. dx/dt = A x + B u cost = integral x.T*Q*x + u.T*R*u """ #ref Bertsekas, p.151 #fi...
Zomega/thesis
Wurm/Stabilize/LQR/python/LQR.py
LQR.py
py
1,450
python
en
code
0
github-code
36
34887554995
import django_filters from .models import * from django_filters import DateFilter, CharFilter, NumberFilter from django.forms.widgets import TextInput, NumberInput, DateInput, SelectDateWidget # class TitleFilter(django_filters.FilterSet): # title = CharFilter(field_name='title', lookup_expr='icontains', # ...
viginti23/project-home-gardens
home/filters.py
filters.py
py
2,126
python
en
code
0
github-code
36
932080591
import argparse import sys from FitsToPNG import main_run from FitsMath import calibration_compute_process from JsonConvert import JsonConvert def argument_handling(): """ Method to deal with arguments parsing :return: file path to fits file and path to a new png file """ parser = argparse.Argumen...
AstroPhotometry/AstroPhotometry
python/main.py
main.py
py
1,913
python
en
code
1
github-code
36
5145048204
from .range_borders import Date, FromInfinity, ToInfinity from datetime import timedelta class DateRange: """ This class implements date ranges that support open borders, so it is possible to create date ranges that contain all dates up to a specific date or all dates from a specific date on. Strict r...
tlie03/OpenDateRange
src/openDateRange/date_range.py
date_range.py
py
3,833
python
en
code
0
github-code
36
32366680678
n=input("insertar la secuencia a ser identificada : ") m=int(input("insertar la cantidad de secuencias candidatas")) def hamming(n,*n1): suma=0 i=-1 while i<=len(n) : i+=1 if n[i]!=n1[i]: suma=suma+1 print(n[i]) print(suma) if i>len(n): ...
masteronprime/python-codigos-diversos
comrparar.py
comrparar.py
py
452
python
es
code
2
github-code
36
73118895784
import socket import pickle from task11_2_user import User class ClientUser: def __init__(self, host, port): self.host = host self.port = port self._socket = None def run(self): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as self._socket: self._socket.co...
IlyaOrlov/PythonCourse2.0_September23
Practice/julmakarova/task11_2_client.py
task11_2_client.py
py
657
python
en
code
2
github-code
36
25450914107
from rest_framework import serializers from taggit.serializers import TagListSerializerField, TaggitSerializer from accounts.models import Profile from ...models import Post, Category class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ("name", "id") ...
AmirhosseinRafiee/Blog
mysite/blog/api/v1/serializers.py
serializers.py
py
2,319
python
en
code
0
github-code
36
20681022248
__author__ = 'elmira' import numpy as np from lxml import etree from collections import Counter from matplotlib import pyplot as plt from matplotlib import mlab def open_corpus(fname): parser = etree.HTMLParser() # создаем парсер хтмл-страниц # скармливаем парсеру майстемовский xml, берем тэг body и все что...
elmiram/homework
seminar9/task2 (4 points)/genre-by-pos.py
genre-by-pos.py
py
3,848
python
ru
code
0
github-code
36
35916291856
class Solution(object): def minWindow(self, s, t): """ :type s: str :type t: str :rtype: str """ t_counter = {} for i in t: if i in t_counter: t_counter[i] += 1 else: t_counter[i] = 1 least = len(...
emirgit/Leetcode
Solutions - Python/Minimum Window Substring.py
Minimum Window Substring.py
py
1,262
python
en
code
0
github-code
36
43062682888
import json import scrapy from scrapy.crawler import CrawlerProcess def decodeEmail(e): de = "" k = int(e[:2], 16) for i in range(2, len(e) - 1, 2): de += chr(int(e[i:i + 2], 16) ^ k) return de headers = { 'Host': 'ufcstats.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent':...
frankamania/Scrapers
ufcstats.com/ufcstats.com_parse_player_data.py
ufcstats.com_parse_player_data.py
py
3,749
python
en
code
0
github-code
36
10877583563
import sys import os from tqdm.rich import tqdm import pandas as pd import datetime import tables from pathlib import Path from typing import TypedDict class TrialSummary(TypedDict): subject: str task: str step: str n_trials: int data_path = Path.home() / "Dropbox" / "lab" / "autopilot" / "data" subj...
auto-pi-lot/autopilot-paper
code/log_counting/count_trials.py
count_trials.py
py
1,137
python
en
code
1
github-code
36
41935148033
import json import re from datetime import datetime from newspaper import Article i = 0 # id number file_path="./MK.json" news_format_json = {} news_format_json['MK'] = [] for y in range(2020, 2021): for m in range(1, 2): for n in range(0, 10001): url = "https://www.mk.co.kr/news...
hyeonoir/Stocksnet
MK.py
MK.py
py
1,571
python
en
code
0
github-code
36
9748891676
from flask import request, Blueprint, abort from models.alarm import Alarm from models.response import ResponseJSON alarm_routes = Blueprint("alarm", __name__, url_prefix="/server/alarm") @alarm_routes.route("/", methods=["POST"]) def add_alarm(): if not request.json or 'name' not in request.json: abort...
byUNiXx/kivy_flask_gps
server/src/routes/alarm.py
alarm.py
py
1,817
python
en
code
0
github-code
36
6184889157
#set encoding=utf-8 entities = dict( laquo = u'\u00AB', raquo = u'\u00BB') REQUISITES = dict( name = u"ООО «Издательский дом «Практика»", INN = "7705166992", BIK = "044525225", KPP = "", correspondentAccount = "30101810400000000225", bene...
temaput/practica.ru
practica/practica/requisites.py
requisites.py
py
856
python
ru
code
0
github-code
36
6994057460
from lib.cuckoo.common.abstracts import Signature class AndroidGooglePlayDiff(Signature): name = "android_google_play_diff" description = "Application Permissions On Google Play Differ (Osint)" severity = 3 categories = ["android"] authors = ["Check Point Software Technologies LTD"] minimum = "...
cuckoosandbox/community
modules/signatures/android/android_google_play_diff.py
android_google_play_diff.py
py
867
python
en
code
312
github-code
36
36319285982
from random import randint from Savedata import Savedata from entity.Entity import EntInt from entity.Player import Player from entity.Enemy.Boss import Boss from entity.Enemy.Malicious import Malicious from entity.Enemy.SimpleEnemy import SimpleEnemy from entity.item.Shield import Shield from entity.item.CadenceUp imp...
2doupo/Shooter
Levels/Level.py
Level.py
py
5,657
python
en
code
0
github-code
36
13491582898
from datetime import datetime import csv, os class File: def __init__(self, name, date): self.fr = None self.fw = None self.fa = None self.filename = f"./files/{name}_{date}.csv" def filename_change(self, filename): self.filename = filename def file_write(self, titl...
jjaekkaemi/dgsb_app
file.py
file.py
py
1,697
python
en
code
0
github-code
36
30167619288
from itertools import combinations import random # If true, extra inforamtion will appear DEBUG = False # O(n*log(n)) def greedy(v, w, W): n = len(w) profit = [(0, i) for i in range(n)] x = [False for i in range(n)] for i in range(n): profit[i] = (v[i]/w[i],i) profit.sort(key = lambda profit: prof...
X-V-III/OK2020
algorithms.py
algorithms.py
py
3,274
python
en
code
1
github-code
36
41903865929
import sys from django.db.models import Avg, Variance from django.shortcuts import render from rest_framework import generics from rest_framework.decorators import api_view, parser_classes from rest_framework.generics import ListCreateAPIView from rest_framework.parsers import JSONParser from rest_framework.response i...
harjiwiga/exchange_rate
exchangerateapp/views.py
views.py
py
6,788
python
en
code
0
github-code
36
71654885545
import sys import re import ranges def read_cleanup_file(filename, full_overlaps_only): sum = 0 with open(filename, 'r') as fp: for line in fp: toks = re.split(',|-', line.strip()) if len(toks) != 4: raise Exception('wrong line format. tokens: %s' % toks) ...
dakopoulos/aoc22
day4/main.py
main.py
py
1,004
python
en
code
0
github-code
36
14258883967
import string priorities = dict(zip(string.ascii_lowercase + string.ascii_uppercase, range(1,53))) def puzzle_one(): total = 0 for line in open("input.txt"): rucksack = line.strip() half_length: int = len(rucksack) // 2 # Get the unique values from each compartment to compare compartment_1 = ''.j...
Villarrealized/advent-of-code
2022/03/main.py
main.py
py
1,005
python
en
code
0
github-code
36
72040624744
import numpy as np import pandas as pd from scipy.linalg import svd def centerData(X): X_mean = np.mean(X) print(X_mean) X_c = X - X_mean return X_c def compute_F_Mat(X_c, fullMatrices=False): ''' Compute the Singular Value Decomposition & F matrix Return Values - F matrix (Fv1) ...
ChavezE/Parallel_PFVA
SVD_Probaility_Tables.py
SVD_Probaility_Tables.py
py
3,354
python
en
code
0
github-code
36
23315150792
import math field = [line.strip() for line in open("input.txt").readlines()] def traverse(field, side_step, height_step, pos=0, hit_stuff=""): for counter in range(0, len(field), height_step): hit_stuff += field[counter][pos] pos = (pos + side_step) % len(field[0]) return hit_stuff.count("#") ...
g-clef/advent_of_code_2020
day 3/day3.py
day3.py
py
478
python
en
code
0
github-code
36
35456769757
from generator import Generator from enviroment import Enviroment import sys utilization = round(float(Enviroment.INITAL_UTILIZATION), 2) finalUtilization = round(float(Enviroment.FINAL_UTILIZATION), 2) processorsNumber = int(Enviroment.PROCESSORS_NUMBER) generationNumber = int(Enviroment.GENERATION_INITIAL_NUMBER) de...
AlveZs/simulator-taskset-generator
main.py
main.py
py
766
python
en
code
0
github-code
36
20288196012
# cmd_xp.py import discord from user import User from lang.lang import Lang from cmds.cmd import ServerCmd async def cmd_user_xp_get_self(server, userid, channel, message): if userid not in server.members.keys(): raise Exception(f'Cannot self display user xp ({userid}) : user id not found in this guild')...
shoko31/InKeeperBot
cmds/cmd_xp.py
cmd_xp.py
py
2,704
python
en
code
0
github-code
36
16310369333
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Now there are 8 patterns of packages of Oreo. How many packages should you buy so that you can get all 8 patterns? (calculate the expectation of the number.) More generally, if there are N patterns, what is the result? ''' import random import sys def findN(n=8): ...
yanglyuxun/my-python-codes
Oreo.py
Oreo.py
py
662
python
en
code
0
github-code
36
26022845612
""" Defina una función areaTriangulo, que consuma un lado y la altura perpendicular a este y entregue como salida el área del triángulo. Busque la fórmula para calcularla. """ def areaTriangulo(): base = int(input('Ingrese la base del Triangulo: ')) altura = int(input('Ingrese la altura del Triangulo: ')) ...
Boris1409/Python-semestre-1
PYTHON SEMESTRE 2/Tareas/AreaTriangulo.py
AreaTriangulo.py
py
427
python
es
code
0
github-code
36
73112544743
import csv import re import numpy as np class DataUtils(object): """ 此类用于加载原始数据 """ def __init__( self, data_source: str, *, alphabet: str = "abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\"/\\|_@#$%^&*~`+-=<>()[]{}", batch_size=128, input_size: int = 10...
howie6879/pylab
src/papers/character_level_convolutional_networks_for_text_classification/data_utils.py
data_utils.py
py
4,334
python
en
code
49
github-code
36
43296825934
""" Enums. """ from pypy.module._cffi_backend import misc from pypy.module._cffi_backend.ctypeprim import (W_CTypePrimitiveSigned, W_CTypePrimitiveUnsigned) class _Mixin_Enum(object): _mixin_ = True def __init__(self, space, name, size, align, enumerators, enumvalues): self._super.__init__(self,...
mozillazg/pypy
pypy/module/_cffi_backend/ctypeenum.py
ctypeenum.py
py
2,759
python
en
code
430
github-code
36
7052172062
from django.core.context_processors import csrf from django.shortcuts import render_to_response from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import Authenti...
sawardekar/Django_OTP
otpapp/views.py
views.py
py
5,575
python
en
code
1
github-code
36
5049967399
import array import struct from contextlib import contextmanager from typing import List, Tuple from cuda import cudart from cuda.cudart import cudaError_t from .mapping import Mapping def _raise_if_error(error: cudaError_t): if error != cudaError_t.cudaSuccess: raise RuntimeError(error) @contextmanag...
NVIDIA/TensorRT-LLM
tensorrt_llm/_ipc_utils.py
_ipc_utils.py
py
3,753
python
en
code
3,328
github-code
36
20533018449
import pandas as pd import numpy as np import warnings def FeatureNormalization(X): m = np.size(X, axis=0) # number of training examples n = np.size(X, axis=1) # number of features mu = np.mean(X, axis=0) mu = np.reshape(mu, [1, n]) print("Size of mu:", np.size(mu)) sigma = np.std(X) mu_...
Neomius/MachineLearning
LinearRegressionGradientDecent.py
LinearRegressionGradientDecent.py
py
1,502
python
en
code
0
github-code
36
501279690
import pandas as pd import numpy as np class GetAngles(object): """ Calculates angles for a image based on coordinates. """ def __init__(self): self.angle = [] self.magnitude_list = [] self.col_names = [] self.origin = 8 self.relative_coor = [] self.x_coor = [] self.y_coor = [] ...
janguyen86/asl_sentence_classification_project
code/angle_calculation.py
angle_calculation.py
py
5,527
python
en
code
1
github-code
36
2847540723
# QUs:https://leetcode.com/problems/cousins-in-binary-tree/ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def isCousins(self, root, x, y)...
mohitsinghnegi1/CodingQuestions
leetcoding qus/Cousins in Binary Tree.py
Cousins in Binary Tree.py
py
997
python
en
code
2
github-code
36