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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
33019978477 | """ Keeps the configuration of the transcriber.
"""
class TranscriberConfig(object):
"""Provide the needed arguments for the transcriber object.
Attributes:
model_path: A string, path to the model file to load.
beam_width: Integer, decoder beam width.
lm_file_path: A string representin... | ivon99/CSCB634-PythonTranscriber | transcriber/transcriber_config.py | transcriber_config.py | py | 1,047 | python | en | code | 0 | github-code | 90 |
70951668778 | import re
from bot import telegram_chatbot
bot = telegram_chatbot("config.cfg")
Previous_Date = datetime.datetime.today() - datetime.timedelta(days=6)
Previous_Date_Formatted = Previous_Date.strftime ('%d/%m/%y') # format the date to dd/mm/yy
pre_date = str(Previous_Date_Formatted)
f = open("WhatsApp Chat with s3 - ... | bhavya4official/telegram-chatbot | server.py | server.py | py | 1,056 | python | en | code | 1 | github-code | 90 |
34047017635 | with open('editfiles/raw/editfile.csv', 'r') as file:
content = file.read()
# print(content)
# slice off trailing ;END
print(content[:-4])
cleaned_content = content[:-4]
with open('editfiles/edited/editfile_cleaned.csv', 'w') as file:
file.write(cleaned_content) | mpolinowski/python-text-processing | editfile.py | editfile.py | py | 273 | python | en | code | 0 | github-code | 90 |
34945445354 | # PasteWeb1/table_name.py
import requests
from time import time, sleep
printable_char = ''
for i in range(33, 127):
printable_char += chr(i)
offset = 0
while True:
cnt = 0
table_name = ''
while True:
cnt += 1
stop = True
for c in printable_char:
sleep(0.1)
... | YungPingXu/NYCU-Software-Security-2022 | Web/HW9/PasteWeb1/table_name.py | table_name.py | py | 1,196 | python | en | code | 0 | github-code | 90 |
42948093131 | import pdb
from logger import web_logger
from utils import (AverageMeter, accuracy, create_loss_fn,
save_checkpoint, reduce_tensor, model_load_state_dict)
from models.trans_crowd import base_patch16_384_token, base_patch16_384_gap
from data import DATASET_GETTERS
from tqdm import tqdm
from torch.util... | wonyangcho/2023bigdataproject | src/main copy.py | main copy.py | py | 30,511 | python | en | code | 0 | github-code | 90 |
75118464296 | #!/usr/bin/python3
"""Module that contains function that loads, add and also save json to file"""
import sys
save = __import__("5-save_to_json_file").save_to_json_file
load = __import__("6-load_from_json_file").load_from_json_file
filename = "add_item.json"
def main(filename):
"""Loads json, Add json to file, sav... | wiseman-umanah/alx-higher_level_programming | 0x0B-python-input_output/7-add_item.py | 7-add_item.py | py | 657 | python | en | code | 0 | github-code | 90 |
33663463982 | #!/usr/bin/env python
#:coding=utf-8:
from setuptools import setup, find_packages
import sys
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(
name='bpssl',
version='1.0.3',
description='SSL/HTTPS for Django',
long_description=open('README.rst').read() + '\n' + open('CHANGES... | beproud/bpssl | setup.py | setup.py | py | 1,131 | python | en | code | 0 | github-code | 90 |
42621182883 | name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
text = open(name)
book = dict()
for line in text:
line.rstrip()
if not line.startswith("From "): continue
words = line.split()
book[words[1]] = book.get(words[1],0)+1
val_order = list()
for k, v in list(book.items()):
val_orde... | dzpiers/Python-For-Everybody | chapter_10-1.py | chapter_10-1.py | py | 410 | python | en | code | 0 | github-code | 90 |
9075142388 | from datetime import datetime
from flask import Flask, render_template, request
from loguru import logger
from api import backend_methods as task
from utils.other_funcs import date_now, sleep_timer
# create the Flask app
app = Flask(__name__)
@logger.catch
@app.route('/')
def index():
return render_template('i... | AgrobnarV/GenerateTestDataPortal_update | flask_app.py | flask_app.py | py | 17,818 | python | en | code | 0 | github-code | 90 |
26037666448 | import logging
import os
import stat
import zc.buildout
from zc.recipe.egg.egg import Eggs
WSGI_TEMPLATE = """\
import sys
sys.path[0:0] = [
%(syspath)s,
]
from pyramid.paster import get_app, setup_logging
configfile = "%(configfile)s"
setup_logging(configfile)
application = get_app(configfile, name=%(app_nam... | garbas/pyramid_recipe_modwgi | pyramid_recipe_modwsgi/__init__.py | __init__.py | py | 2,639 | python | en | code | 0 | github-code | 90 |
26010900944 | #!/usr/bin/env python3
import MySQLdb
def insert_into_table(table_name, data):
db = MySQLdb.connect(host="localhost", user="electros", passwd="electros", db="siigo")
cursor = db.cursor()
try:
query = "INSERT INTO " + table_name + "("
values = "VALUES ("
sep = ""
for key, v... | Jimmer942/Siigo_hackaton_2020 | metodos/crear.py | crear.py | py | 731 | python | en | code | 0 | github-code | 90 |
20769465466 | import logging
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from PIL import ImageFilter
from bat.DicomHandler import DicomHandler
class ImageHandler(DicomHandler):
"""
ImageHandler class is a heritage of DicomHandler class.
The ImageHandler class can provide more functions ba... | snakeqx/ImagePosition | bat/ImageHandler.py | ImageHandler.py | py | 10,169 | python | en | code | 0 | github-code | 90 |
39099752237 | import tkinter as tk
import tkinter.ttk as tk1
import googletrans
import textblob
window = tk.Tk()
window.geometry("900x400")
window.title("Translator by Mr. Ahmad")
#functions
def translate():
try:
# ngambil key dari bahasa asal
for key, value in languages.items():
if (value == ori_c... | madyazdhil/Basic-Python | Term A+/SAT-13/lesson17/translator.py | translator.py | py | 1,995 | python | en | code | 0 | github-code | 90 |
41620478757 | import tkinter as tk
from tkinter import messagebox, simpledialog
from tkinter import ttk
import pickle
import os.path
class DisciplinaCursada:
def __init__(self, disciplina, ano, semestre, nota):
self.__disciplina = disciplina
self.__ano = ano
self.__semestre = semestre
self.__nota... | Luiss1569/Orietado-Objetos-I | Trabalhos/Trabalho 12/aluno.py | aluno.py | py | 11,632 | python | pt | code | 0 | github-code | 90 |
23089641573 | config = {
"exp_name": "uni_lstm",
"epochs": 20,
"encoder": "UniLSTM",
"batch_size": 128,
"hidden_dim": 2048,
"num_layers": 1,
"learning_rate": 1e-3,
"seed": 42,
"debug": False,
# "device": 'cpu',
"device": 'cuda',
"num_workers": 4,
"valid_freq": 1000,
"save_freq"... | AmanDaVinci/Universal-Sentence-Representations | configs/uni_lstm.py | uni_lstm.py | py | 368 | python | en | code | 0 | github-code | 90 |
30402659589 | from django.shortcuts import redirect,render
from django.contrib.auth import login,logout,authenticate
from shop.forms import *
from django.http import HttpResponse,HttpResponseRedirect
from shop.models.models import *
import os
# Create your views here.
fileDir = os.path.dirname(os.path.realpath(__file__))
# fileDir ... | Shashank-S-Rao/test | shop/views/views.py | views.py | py | 5,255 | python | en | code | 0 | github-code | 90 |
18579638839 | import sys
mina=10**10
def waru(a,b):
if a%b==0:
return a//b
else:
return (a//b)+1
N,H=map(int,input().split())
A=list()
B=list()
for i in range(N):
a,b=map(int,input().split())
A.append(a)
B.append(b)
ma=max(A)
ind=A.index(ma)
B=[i for i in B if i>ma]
B=sorted(B,reverse=True)
cou=1
s=0
for i in range... | Aasthaengg/IBMdataset | Python_codes/p03472/s684454987.py | s684454987.py | py | 411 | python | en | code | 0 | github-code | 90 |
14064514191 | from typing import Any, Dict, List, Optional
import numpy as np
from iris.coords import CellMethod
from iris.cube import Cube, CubeList
from iris.exceptions import CoordinateNotFoundError
from numpy import dtype, ndarray
from improver import BasePlugin
from improver.metadata.amend import amend_attributes
from improve... | metoppv/improver | improver/standardise.py | standardise.py | py | 6,926 | python | en | code | 95 | github-code | 90 |
28768621696 | import asyncio
import logging
import time
from secp256k1_zkp import PrivateKey, PublicKey
from .node import Node
from lnoise import Key
logger = logging.getLogger(__name__)
from .messages import message_id, inv_message_id
from uuid import uuid4
class NetworkManager:
def __init__(self, loop, syncer, config):
... | WTRMQDev/leer | leer/transport/network_manager.py | network_manager.py | py | 24,028 | python | en | code | 5 | github-code | 90 |
22617743020 | import time
import torch
from model import UNET
from utils import save_prediction_as_imgs
from dataset import CarvanaDataset
from torch.utils.data import DataLoader
import albumentations as A
from albumentations.pytorch import ToTensorV2
from PIL import Image
import numpy as np
import torchvision
import cv2
IMAGE_HEI... | arief25ramadhan/carvana-unet-segmentation | torchscript_optimization.py | torchscript_optimization.py | py | 2,814 | python | en | code | 0 | github-code | 90 |
15984687296 | import functools
from typing import Callable, Iterable, Optional, Sequence
import warnings
from jax import numpy as jnp
import jax.example_libraries.stax as ostax
from .requirements import layer, supports_masking
from ..utils.kernel import Kernel
from ..utils.typing import InternalLayer, InternalLayerMasked, Kernels
... | google/neural-tangents | neural_tangents/_src/stax/branching.py | branching.py | py | 15,516 | python | en | code | 2,138 | github-code | 90 |
10960259417 | settings = {
'PREFER_DATES_FROM': 'current_period',
'SUPPORT_BEFORE_COMMON_ERA': False,
'PREFER_DAY_OF_MONTH': 'current',
'SKIP_TOKENS': ["t"],
'SKIP_TOKENS_PARSER': ["t", "year", "hour", "minute"],
'TIMEZONE': 'local',
'TO_TIMEZONE': False,
'RETURN_AS_TIMEZONE_AWARE': 'default',
'NO... | Raghav-Pal/PythonAutomationFramework_1 | venv/Lib/site-packages/dateparser_data/settings.py | settings.py | py | 477 | python | gu | code | 12 | github-code | 90 |
15900215915 | #!/usr/bin/python3
"""Module for matrix divided method"""
def matrix_divided(matrix, div):
"""divides all elements of a matrix by div"""
if (type(div) is not int and type(div) is not float):
raise TypeError("div must be a number")
if (div == 0):
raise ZeroDivisionError("division by zero")... | nerraou/alx-higher_level_programming | 0x07-python-test_driven_development/2-matrix_divided.py | 2-matrix_divided.py | py | 1,291 | python | en | code | 0 | github-code | 90 |
5002452950 | class Stat():
def __init__(self, setg):
self.setg = setg
self.active_game = False
with open('highscore.txt') as file:
self.high_score = int(file.read()) if file else 0
self.reset_stats()
def reset_stats(self):
self.ships_left = self.setg.ships_limit
self.score = 0
self.level = 1
| prgup/space_invader | statics.py | statics.py | py | 300 | python | en | code | 1 | github-code | 90 |
11206125484 | from sys import exit
from decouple import config
from config import config_dict
from app import create_app, celery
DEBUG = config('DEBUG', default=True, cast=bool)
# The configuration
get_config_mode = 'Debug' if DEBUG else 'Production'
try:
# Load the configuration using the default values
app_config = con... | diegozarur/webscanner | run.py | run.py | py | 569 | python | en | code | 1 | github-code | 90 |
18651208898 | from show_data import *
import numpy as np
def metric_comparison(st):
df = pd.read_csv(get_route("all"))
df = df[df['T5_query_rewriter'] == "base"]
df = df[df['run_type'] == "automatic"]
df = df.drop(['Id', 'Creation Time', 'T5_query_rewriter', 'run_type'], axis=1)
metrics_dict = {
'averag... | jkoprcina/QueryRewritingDataVisualisation | graphs/metric_comparison.py | metric_comparison.py | py | 1,638 | python | en | code | 0 | github-code | 90 |
7983916988 | import pytest
import math
import time
class Solution(object):
def valid_palindrome_SS(self, str):
str_ans = ""
for i in str:
if i.isalnum():
str_ans += i.lower()
if len(str_ans) == 0:
return True
else:
if len(str... | SahandSomi/algorithms-exercise | Two Pointers/Valid Palindrome/valid_palindrome.py | valid_palindrome.py | py | 1,360 | python | en | code | 0 | github-code | 90 |
70993434536 | # Clash Royale Clan Manager
# computes promotion/demotion/kick/warning lists, average war rank, and weekly war champ according to clan wars II statistics
# uses data from Supercell's Clash Royale API
import json
import requests
import statistics
def data_fetcher(clan_tag, token, category):
# fetches data from API... | iosifsalem/ClashRoyaleClanManager | ClashRoyaleClanManager.py | ClashRoyaleClanManager.py | py | 6,017 | python | en | code | 1 | github-code | 90 |
42384301415 | import os
from werkzeug.utils import secure_filename
from BismarkPusher import BismarkPusher
from FlaskHelpers import FlaskHelpers
from flask import Flask, url_for, render_template
from flask import request
from flask_cors import CORS
from report_processor.bismarck_report import BismarckReport
from models.Results impor... | RoySegall/BismarckValidator | app.py | app.py | py | 3,743 | python | en | code | 1 | github-code | 90 |
11623078255 | ############################################################
# #
# Author: Adrian T. Neumann #
# Date: 11 November 2018 #
# Description: A program that accepts the number #
# of hours wor... | Bach9000/prog1015_an | Assignments/Assignemnt 3/Program 1- Time Sheet.py | Program 1- Time Sheet.py | py | 4,597 | python | en | code | 0 | github-code | 90 |
17980484222 |
from functools import wraps
from flask import make_response, abort
from app.models.customer import Customer
from app.models.video import Video
def validate_endpoint(endpoint):
"""Decorator to validate that endpoint id is an int. Returns JSON and
400 if not found.
"""
@wraps(endpoint) # Makes fn look ... | lgaetano/retro-video-store | app/utils/endpoint_validation.py | endpoint_validation.py | py | 1,499 | python | en | code | 0 | github-code | 90 |
18052667839 | # -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1
def main():
N=int(input())
T,A=map(int,... | Aasthaengg/IBMdataset | Python_codes/p03964/s796893815.py | s796893815.py | py | 512 | python | en | code | 0 | github-code | 90 |
31228021372 | # -*- coding: utf-8 -*-
"""
本程序用通达信数据对股价前复权,将数据保存为excel文件
通达信本地数据格式:
每32个字节为一个5分钟数据,每字段内低字节在前
00 ~ 01 字节:日期,整型,设其值为num,则日期计算方法为:
year=floor(num/2048)+2004;
month=floor(mod(num,2048)/100);
day=mod(mod(num,2048),100);
02 ~ 03 字节: 从0点开始至目前的分钟数,整型
04 ... | RoveAllOverTheWorld512/hyb_bak | fhpgsql2pd.py | fhpgsql2pd.py | py | 11,493 | python | de | code | 0 | github-code | 90 |
18047575669 | # -*- coding: utf-8 -*-
"""
Created on Sun May 10 17:43:29 2020
@author: shinba
"""
n = int(input())
s = input()
t = input()
l = 0
for i in range(n):
if s[i:] == t[:n-i]:
l = n-i
break
print(2*n-l)
| Aasthaengg/IBMdataset | Python_codes/p03951/s501331802.py | s501331802.py | py | 230 | python | en | code | 0 | github-code | 90 |
18669325977 | from json import *
from time import *
from gpio import *
from realhttp import *
from tcp import *
from udp import *
# Vars and Globals
should_alert = False
message = ''
alarm_status = ''
data_carbon = 0
data_aqi = 0
PIN_LCD = 0
THRESH = 1670 # THRESH is the Threshold, New Zealand has the Ambiant set to 10 milligrams ... | Birphon/BCCS183-Internet-of-Things | Lab 9-1-1/SBC1 - LCD.py | SBC1 - LCD.py | py | 2,137 | python | en | code | 0 | github-code | 90 |
18263114609 | N, M, K = map(int, input().split())
friend = {}
for i in range(M):
A, B = map(lambda x: x-1, map(int, input().split()))
if A not in friend:
friend[A] = []
if B not in friend:
friend[B] = []
friend[A].append(B)
friend[B].append(A)
block = {}
for i in range(K):
C, D = map(lambda x... | Aasthaengg/IBMdataset | Python_codes/p02762/s462418193.py | s462418193.py | py | 1,373 | python | en | code | 0 | github-code | 90 |
10334624596 | import os
from glob import glob
from tqdm import tqdm
import pandas as pd
from syntok.tokenizer import Tokenizer
def chunks(tokens, chunksize):
"""Split a list into chunks of ``chunksize`` tokens each."""
for n in range(0, len(tokens), chunksize):
yield tokens[n:n + chunksize]
def main(chunksize=1000):
md = pd... | andreasvc/fictiongenres | topicmodelpreprocess.py | topicmodelpreprocess.py | py | 1,250 | python | en | code | 0 | github-code | 90 |
4423562108 | #
# web_server_status.py
#
# Implements interfacing with the KotakeeOS central home automation
# web server. A single static class should be utilized for all
# speech_server interactions.
import threading
import requests
import json
import datetime
class WebServerStatus:
web_server_ip_address = None
action_stat... | ArthurlotLi/kotakee_companion | speech_server/web_server_status.py | web_server_status.py | py | 10,449 | python | en | code | 2 | github-code | 90 |
6046834609 | """
ファイルやフォルダの操作を行う関数群.
"""
import os
import glob
import pathlib
import platform
import datetime
def makedirs_plus(dir_path, permission=0o2777):
'''
dirの存在を確認して、なかったら作成
:param dir_path:作成したいdirパス
:param permission:与えたいパーミッション、デフォは全開放
:return:なし
'''
if not os.path.exists(dir_... | sikakusosi/kutinawa | kutinawa/kutinawa_fileOP.py | kutinawa_fileOP.py | py | 2,575 | python | ja | code | 1 | github-code | 90 |
20465691989 | import sys
input = sys.stdin.readline
n, m = map(int, input().split())
arr = []
def recur(num, count):
if count == m: # 기저 조건
print(*arr)
return
for i in range(num, n+1):
arr.append(i)
recur(i, count+1)
arr.pop()
recur(1, 0) | undervi/coding_test_python | 백준/Silver/15652. N과 M (4)/N과 M (4).py | N과 M (4).py | py | 309 | python | en | code | 1 | github-code | 90 |
15423176697 | import threading
import time
from tkinter import Tk, Label, StringVar, Frame, Button, Toplevel, Scale, messagebox
import logging
# from functools import partial # allows for passing both a function as well as its arguments, in case of "command=partial(func, arg1, arg2)"
from previous_versions.very_old_code.load_config... | RacingInsights/RacingInsights-V1 | previous_versions/very_old_code/dashboard.py | dashboard.py | py | 20,437 | python | en | code | 0 | github-code | 90 |
43486354133 | from django.db import models
from dataworkspace.apps.core.models import (
TimeStampedUserModel,
)
class UploadedTable(TimeStampedUserModel):
schema = models.TextField()
table_name = models.TextField()
data_flow_execution_date = models.DateTimeField()
def display_name(self):
return f"{sel... | uktrade/data-workspace | dataworkspace/dataworkspace/apps/your_files/models.py | models.py | py | 349 | python | en | code | 42 | github-code | 90 |
297217928 | from pymodbus.client.sync import ModbusSerialClient, ConnectionException
import glob
import json
def modbus_rtu_device_scanner(serial_devices=['/dev/ttyUSB0'], baud_rates=[9600, 19200]):
"""
Scan list of serial devices on every possible configurations of speed (baud rate),
parity and stop bits, to looking... | indeema-bushko/python_examples | modbus_device_scanner/modbus_device_scanner.py | modbus_device_scanner.py | py | 3,408 | python | en | code | 0 | github-code | 90 |
72442516456 | # -*- coding: utf-8 -*-
from openerp.osv import orm, fields
import logging
from openerp import SUPERUSER_ID
from datetime import datetime as dt
_logger = logging.getLogger(__name__)
class nh_clinical_patient_pbp_monitoring(orm.Model):
_name = 'nh.clinical.patient.pbp_monitoring'
_inherit = ['nh.activity.data... | LiberTang0/odoo-temp | nh_pbp/parameters.py | parameters.py | py | 1,904 | python | en | code | 0 | github-code | 90 |
5279081632 | import socket
import threading
ip = '127.0.0.1'
port = 4321
s_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_socket.bind((ip, port))
s_socket.listen()
c_socket,address = s_socket.accept()
print("Got connection from: {}, {}".format(c_socket, address))
m2 = "Hey there client!"
while True:
msg = c_sock... | MONO-C1oud/Projects | learning_N_projects/pythonsockets/server.py | server.py | py | 417 | python | en | code | 0 | github-code | 90 |
8714564178 | '''
Created on May 13, 2011
@author: gaubert
'''
from netCDF4 import Dataset
import numpy
if __name__ == '__main__':
dir = '/homespace/gaubert/ifremer-data'
input_files = [
# '20110502-EUR-L2P_GHRSST-SSTsubskin-AVHRR_METOP_A-eumetsat_sstmgr_metop02_20110502_220403-v01.7-fv01.0.n... | gaubert/viirs-data | src/eumetsat/round_osisaf_data.py | round_osisaf_data.py | py | 1,242 | python | en | code | 2 | github-code | 90 |
18558054279 | A, B = map(int, input().split())
count = 0
for i in range(A, B+1):
check = 0
str_i = str(i)
for j in range(0, (len(str_i)//2)+1):
if int(str_i[j]) != int(str_i[-1-j]):
check += 1
if check == 0:
count += 1
print("{}".format(count)) | Aasthaengg/IBMdataset | Python_codes/p03416/s909216871.py | s909216871.py | py | 277 | python | en | code | 0 | github-code | 90 |
13358720060 | import matplotlib.pyplot as plt
import pandas as pd
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, accuracy_score
from sklearn.svm import SVC
import streamlit as st
df = pd.read_csv("D:\Kathan\Au Assignment\TOD 310- Predicitive Analytics Business for Business\diabetes.csv")
# Visual Pyt... | kathanraval/Predicitive-Analytics-For-Business | SVM.py | SVM.py | py | 1,433 | python | en | code | 0 | github-code | 90 |
18417676629 | import sys
sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7
def resolve():
n = int(input())
S = input()
White = [0] * (n + 1)
Black = [0] * (n + 1)
for i in range(n):
if S[i] == "#":
Black[i + 1] = Black[i] + 1
else:
Black[i + 1] = Bla... | Aasthaengg/IBMdataset | Python_codes/p03069/s948375960.py | s948375960.py | py | 621 | python | en | code | 0 | github-code | 90 |
70150875496 | import random
class Card():
'''
Represents a single card type
'''
def __init__(self, value, name, suit):
self.value = value
self.name = name
self.suit = suit
def is_special(self):
'''
Determine whether the card is one of the special cards (King,
... | DaveTCode/PlatoonNiNoKuni | card.py | card.py | py | 4,138 | python | en | code | 0 | github-code | 90 |
18539194689 | h, w = (int(x) for x in input().split())
S = [list(input()) for _ in range(h)]
next_x = [1, 0, -1, 0]
next_y = [0, 1, 0, -1]
for y in range(h):
for x in range(w):
if S[y][x] == "#":
for i in range(4):
nx = x + next_x[i]
ny = y + next_y[i]
if 0 <=... | Aasthaengg/IBMdataset | Python_codes/p03361/s604090831.py | s604090831.py | py | 475 | python | en | code | 0 | github-code | 90 |
44677421654 | from ast import increment_lineno
import csv
import matplotlib.pyplot as plt
plt.style.use('ggplot')
file = open("english premier league data.csv")
csvreader = csv.reader(file)
header = next(csvreader)
print(header)
rows = []
for row in csvreader:
rows.append(row)
#print(rows)
file.close()
x = ['Man City', 'Liv... | braddyer01/csws-group30-CW | epldata.py | epldata.py | py | 613 | python | en | code | 2 | github-code | 90 |
41616327934 | from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patters import apriori, association_rules
transactions=[
['bread','jam','butter'],
['bread','milk','eggs'],
['bread','milk','butter','jam'],
['milk','butter','eggs'],
['bread','milk','eggs']
]
te = TransactionEncoder()
te_ary = te.fit(transact... | Vedhanth123/5th-Sem-OU | AIDM/association_rules.py | association_rules.py | py | 524 | python | en | code | 0 | github-code | 90 |
5417043662 | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import pylab as plot
from decimal import Decimal
#Initialize some constants
vTX1 = 18.2 #reporter transcription rate constant
vTX2 = 18.2 #repressor transcription rate constant
KTX1 = 8.5 #Michaelis-Menten constant... | ShubhankarLondhe/iGEM | Biosensor/Biosensor t vs GFP.py | Biosensor t vs GFP.py | py | 5,532 | python | en | code | 2 | github-code | 90 |
36556438089 | import json
import os
import pickle
class FileDB:
def __init__(self, cache_dir):
self.cache_dir = cache_dir
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
def get(self, key):
try:
with open(os.path.join(self.cache_dir, key), 'rb') as f:
... | apssouza22/chatflow | server/src/core/common/file_db.py | file_db.py | py | 958 | python | en | code | 95 | github-code | 90 |
72201259498 | # Hard
# You're fiven three inputs, all of which are instances of an Orgchart class that have a directReports property
# pointing to their direct reports (children). The first input is the top manager in an organizational chart, and the other
# two inputs are reports in the organizational chart. The two reports are gu... | ArmanTursun/coding_questions | AlgoExpert/Recursion/Hard/Lowest Common Manager/Lowest Common Manager.py | Lowest Common Manager.py | py | 1,579 | python | en | code | 0 | github-code | 90 |
18297589649 | import sys
import math
from collections import defaultdict
sys.setrecursionlimit(10**7)
def input():
return sys.stdin.readline()[:-1]
mod = 10**9 + 7
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
if N<=0:
ret... | Aasthaengg/IBMdataset | Python_codes/p02821/s153574787.py | s153574787.py | py | 1,794 | python | en | code | 0 | github-code | 90 |
44179403050 | # -----------------------------------------------------------
# 424. Longest Repeating Character Replacement
# You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
# Return the length... | a22yuen/DSA | 3-sliding-windows/424-longest-repeating-character-replacement.py | 424-longest-repeating-character-replacement.py | py | 3,467 | python | en | code | 2 | github-code | 90 |
30883881674 | import csv
def ow_iter_sensory(fn):
with open(fn) as fh:
for row in csv.DictReader(fh):
neuron = row['Neuron']
_sense = row['Landmark']
_type = row['Neurotransmitter']
yield neuron, _type, _sense
def ow_iter_connectome(fn):
with open(fn) as fh:
... | obogames/wyrm | connectome/readers/openworm.py | openworm.py | py | 927 | python | en | code | 2 | github-code | 90 |
14770582542 | n = int(input())
ans = 0
for i in range(n):
s = input()
flag = True
m = len(s)
for j in range(m):
if s[j] != s[(m-1)-j]:
flag = False
if flag:
ans += 1
print(ans) | kaneda05/algo | 1/full_search/4/5.py | 5.py | py | 211 | python | en | code | 0 | github-code | 90 |
23540232784 | from turtle import Turtle
FONT1 = ("Courier", 24, "normal")
FONT2 = ("Courier", 18, "normal")
class ScoreBoard(Turtle):
def __init__(self):
super().__init__()
self.level = 1
self.penup()
self.pencolor("black")
self.goto(-270, 250)
self.write_score()
self.hid... | hantn16/100daysPython | turtle_crossing/scoreboard.py | scoreboard.py | py | 703 | python | en | code | 0 | github-code | 90 |
38918059026 | import logging
from typing import Iterable, List
import numpy as np
from sklearn.model_selection import train_test_split
from torch.utils.data import DataLoader
from src.data.datasets import TorchTransformableSubset, TorchImageDataset
class BaseDataHandler(object):
def __init__(
self,
dataset: T... | GVS-Lab/chromark | src/helper/data.py | data.py | py | 3,925 | python | en | code | 0 | github-code | 90 |
35433823075 | from collections import Counter
class Solution:
def frequencySort(self, s: str) -> str:
c = Counter(s)
bucket = [-1]*(len(s) + 1)
for l, freq in c.items():
if bucket[freq] == -1:
bucket[freq] = []
bucket[freq].append(l)
new_s = ''
fo... | kateshostak/leetcode | sort_characters_by_frequency.py | sort_characters_by_frequency.py | py | 625 | python | en | code | 0 | github-code | 90 |
30959301137 | import pygame
from plane_sprites import *
# 游戏的帧数
FRAME_PER_SEC = 120
# 创建敌机事件
CREATE_ENEMY_EVENT = pygame.USEREVENT
HERO_FIRE_EVENT = pygame.USEREVENT + 1
class PlaneGame(object):
def __init__(self):
print("游戏初始化。。。")
# 1.创建屏幕对象
self.screen = pygame.display.set_mode(SCR... | xiaojie25/PlaneGame | planr_main.py | planr_main.py | py | 3,582 | python | en | code | 1 | github-code | 90 |
20732798152 | import time
from pi_sht1x import SHT1x as sht
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
dat = 2
sck = 3
with sht(dat, sck, gpio_mode = GPIO.BCM) as sensor:
temperature = sensor.read_temperature()
humidity = sensor.read_humidity(temperature)
print("temperature: {}".format(temperature))
print("humidity:... | VladTomici14/Rusty6 | code/sht.py | sht.py | py | 346 | python | en | code | 1 | github-code | 90 |
19255635685 | from sys import stdin
from collections import deque
stdin = open("./input.txt", "r")
num_of_cards = int(stdin.readline())
num_of_choose = int(stdin.readline())
cards = []
for _ in range(num_of_cards):
cards.append(int(stdin.readline()))
answer = set()
def dfs(cur_idx, visited, temp):
visited[cur_idx] = Tru... | ag502/algorithm | Problem/BOJ_5568_카드 놓기/main.py | main.py | py | 860 | python | en | code | 1 | github-code | 90 |
72328682857 | from aiogram import types
from bot.common.keyboard_fabrics import (currency_cb, delete_account_cb,
lang_cb, menu_cb, notification_cb,
notification_payout_cb)
from bot.handlers.text.base_command_handler import BaseCommandHandler
from datab... | Forevka/Emcd | bot/handlers/text/settings_command.py | settings_command.py | py | 2,029 | python | en | code | 2 | github-code | 90 |
20538273416 | # libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from requests import head
import seaborn as sns
# # set seaborn style
# sns.set_theme()
# df = pd.read_csv ('vuln-versions.csv')
# # print(df)
# #print(df[df.columns[1]])
# # Data
# x=range(1,183)
# df[df.columns[2]] = df[df.columns[2]... | cristianstaicu/SecBench.js | analyses/graphs/versions-histogram.py | versions-histogram.py | py | 4,536 | python | en | code | 23 | github-code | 90 |
18187213413 | import unittest
from src.which_are_in import in_array
class TestWhichAreIn(unittest.TestCase):
def test_which_are_in(self):
a1 = ["live", "arp", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
r = ['arp', 'live', 'strong']
self.assertEqual(in_array(a1, a2), r)
... | n1kk0/katas | python/test/test_which_are_in.py | test_which_are_in.py | py | 367 | python | en | code | 0 | github-code | 90 |
33573806441 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 5 12:56:03 2023
@author: zevfine
"""
def madlib(filename):
'''reads a madlib and asks for the inputs'''
fn = open(filename,'r')
txt = fn.read()
word_list = txt.split(' ')
print(word_list)
for i in range(len(word_list)):
... | ZevFine/Personal-Projects | madlibs.py | madlibs.py | py | 846 | python | en | code | 0 | github-code | 90 |
16470745930 | # Bucket Sort - O(n)
def bucket_sort(lst):
# Find the maximum value in the list and calculate the bucket size
max_value = max(lst)
bucket_size = max_value / len(lst)
# Create an empty list of buckets
buckets = [[] for _ in range(len(lst))]
# Put each element in its corresponding bucket
for... | ItemHunt/Data-Structures-and-Algorithms | algorithms/sort/bucket_sort.py | bucket_sort.py | py | 1,111 | python | en | code | 0 | github-code | 90 |
21404773528 | import os
import pathlib
import re
import sys, getopt
import json
from tqdm import tqdm
def run(fname, max_len, min_word_num):
inputFileName = fname
outputFileName = fname.split('.')[0]+'.json' #+ '/out'
#if not os.path.exists(pathout):
# os.makedirs(pathout)
out_list=[]
curr_string="... | ntvuong/Diacritics_Vietnamese | webcorpus_2/get_text.py | get_text.py | py | 2,005 | python | en | code | 1 | github-code | 90 |
10726482272 | nums = [int(num.strip()) for num in open('aoc2019/inputs/1.txt').readlines()]
def calc_fuel(mass):
return (mass//3)-2
def rec_fuel(mass):
fuel = calc_fuel(mass)
if fuel < 0:
return 0
else:
return fuel + rec_fuel(fuel)
total_fuel = sum([calc_fuel(mass) for mass in nums])
print(total... | FjeldMats/AdventOfCode | aoc2019/day1.py | day1.py | py | 406 | python | en | code | 1 | github-code | 90 |
19797178484 | #!/usr/bin/python
# -*-coding:utf8-*-
"""
@author: LieOnMe
@time: 2019/7/27 17:07
"""
import os
import tensorflow as tf
from tensorflow import keras
from utils import conf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
PROJ_PATH = conf.get_project_path()
def pre_process(x, y):
# [0-255] => [-1, 1]
x = 2 * tf.cas... | kaisayi/bordercollie | src/model/cifar10_train.py | cifar10_train.py | py | 2,968 | python | en | code | 0 | github-code | 90 |
16744181813 | import numpy as np
import matplotlib.pyplot as plt
Data= np.genfromtxt('planetas.txt')
x = Data[:,0]
y = Data[:,1]
plt.plot(x,y)
plt.grid()
plt.savefig('Graph.png')
| SebastianSebz/SebastianSuarez_Ejercicio25 | graph.py | graph.py | py | 188 | python | en | code | 0 | github-code | 90 |
18378251989 | s=input()
n=len(s)
f=0
for i in range(n-1):
if(s[i]==s[i+1]):
f=1
break
if(f==1):
print("Bad")
else:
print("Good")
| Aasthaengg/IBMdataset | Python_codes/p02993/s104363473.py | s104363473.py | py | 144 | python | en | code | 0 | github-code | 90 |
7883566691 | from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, MaxPool2D, LSTM, Reshape, Dense, Dropout
from load_data import *
batch_size = 1
inputs = Input(shape = (sampled_data.shape[1],sampled_data.shape[2],sampled_data.shape[3]), batch_size = batch_size)
conv2d_1 = Conv2D(fil... | riyandrika/speech-recognition | RCNN.py | RCNN.py | py | 1,227 | python | en | code | 0 | github-code | 90 |
18503603299 | def check(n):
count = 0
for i in range(1, n + 1):
if(n % i == 0):
count += 1
if(count == 8 and n % 2 != 0):
return True
else:
return False
n = int(input())
count = 0
for i in range(1, n + 1):
if(check(i)):
count += 1
print(count)
| Aasthaengg/IBMdataset | Python_codes/p03281/s441326841.py | s441326841.py | py | 296 | python | en | code | 0 | github-code | 90 |
73246470376 | import torch.nn as nn
import torch
class Config:
def __init__(self):
self.data_path = 'Pheme.csv'
self.batch_size = 64
self.min_freq = 0
self.pad_length = 80
self.embedding_path = '../../Glove_Twitter_wordVec/glove.twitter.27B.200d.txt'
self.embed_size = 200
... | andr2w/Malicious-Attack | TextFooler/model.py | model.py | py | 1,652 | python | en | code | 1 | github-code | 90 |
27984965602 | import numpy as np
import pdb
import torch.nn as nn
import torch
import time
from at5k_1.write_file import write_weight_b
def wr_str(str): # parameter
f = open('E:/AT5000/AT5K_Pytorch_2/Pytorch_Retinaface_master/at5k_1/model_txt/model.txt', 'a')
f.write(str)
f.write('\n')
f.close()
cl... | poyue0221/Learing_me | Pytorch_Retinaface/quanzition_windows/at5k_1/qconv2d.py | qconv2d.py | py | 12,163 | python | en | code | 1 | github-code | 90 |
30095652501 | from PIL import Image, ImageFont, ImageDraw
from newsapi import NewsApiClient
import requests
from io import BytesIO
import os
import time
import sys
import textwrap
import math
def createStory1(img, title, desc, url):
imgWidth = img.width
imgHeight = img.height
fontsFolder = 'FONT_FOLDER'
# Windows
... | PablooogiN/Story2Instagram | topicToStory.py | topicToStory.py | py | 4,096 | python | en | code | 0 | github-code | 90 |
42368220590 | #!/usr/bin/env python
import atexit
import argparse
import os
import shutil
from pathlib import Path
from checkov.arm.runner import Runner as arm_runner
from checkov.cloudformation.runner import Runner as cfn_runner
from checkov.common.bridgecrew.platform_integration import bc_integration
from checkov.common.goget.gi... | jensskott/tf-compliance | venv/lib/python3.9/site-packages/checkov/main.py | main.py | py | 8,043 | python | en | code | 0 | github-code | 90 |
18324169539 | def main():
s = input()
arr = [0]*(len(s)+1)
for i in range(len(s)):
c = s[i]
if c == "<":
arr[i+1] = arr[i]+1
for i in reversed(range(len(s))):
c = s[i]
if c == ">":
arr[i] = max(arr[i], arr[i+1]+1)
print(sum(arr))
if __name__ == "__main__":
... | Aasthaengg/IBMdataset | Python_codes/p02873/s082946344.py | s082946344.py | py | 331 | python | en | code | 0 | github-code | 90 |
21461747880 | from django.conf.urls import url, include
from django.urls import path
from rest_framework import routers, serializers, viewsets
from .views import loginEndpoint, register, NotSeenRentOffersViewSet, ReactionsViewSet
router = routers.DefaultRouter()
router.register(
r"^api/rentoffers", NotSeenRentOffersViewSet, bas... | MichalKarol/rent-tinder | backend/api/urls.py | urls.py | py | 567 | python | en | code | 0 | github-code | 90 |
18223558159 | import itertools
N, M, Q = map(int, input().split())
a = []
b = []
c = []
d = []
for q in range(Q):
aq, bq, cq, dq = map(int, input().split())
a.append(aq)
b.append(bq)
c.append(cq)
d.append(dq)
max_answer = 0
for A in itertools.combinations_with_replacement(range(1, M + 1), N):
# print(A)
... | Aasthaengg/IBMdataset | Python_codes/p02695/s418689100.py | s418689100.py | py | 556 | python | en | code | 0 | github-code | 90 |
27195848568 | """ 1. WAP to remove all the duplicate elements in the list """
# names = ['apple', "google", "apple", "yahoo", "google"]
# l = []
# Method 1:
# for element in names:
# if element not in l:
# l.append(element)
#
# print(l) # ['apple', 'google', 'yahoo']
# Method 2:
# for element in names:
# ... | njmujawar/selenium_practise | Sau_/Assesments/Assesment 2 (List).py | Assesment 2 (List).py | py | 4,624 | python | en | code | 0 | github-code | 90 |
7905818289 | from . import log
from sqlalchemy import exists
class Exporter(object):
def exists(self, url):
raise NotImplementedError
def add(self, recipe):
raise NotImplementedError
class SQLAlchemyExporter(object):
"""
A class for exporting recipes to an sql alchemy database.
Pass in the... | steinitzu/recipe_scrapers | recipe_scrapers/export.py | export.py | py | 2,020 | python | en | code | 0 | github-code | 90 |
5618869141 | import numpy as np
import argparse
# 构造解析函数 包? 外部导入图片的包
import cv2
# 用恐龙做这个真的看不出什么
ap = argparse.ArgumentParser()
ap.add_argument("-i","--image",required=True,
help = " Path to the image")
args = vars(ap.parse_args())
# 加载图像 并且抓取每一个通道
image = cv2.imread(args["image"])
(B,G,R) = cv2.split(image) #numpy 把它倒过来了... | Chentao2000/practice_code | Python_OpenCV/(Practical-Python-and-OpenCV_book1)/ch6/6_22_splitting_and_merging.py | 6_22_splitting_and_merging.py | py | 959 | python | zh | code | 0 | github-code | 90 |
35219691009 | from itertools import permutations
n = int(input())
a = list(map(int, input().split()))
from copy import deepcopy
a1 = deepcopy(a)
a1.sort()
p = []
for i in range(n):
idx = a1.index(a[i])
p.append(idx)
a1[idx] = -1
print(*p)
| yongwoo97/algorithm | silver/1015_수열 정렬.py | 1015_수열 정렬.py | py | 241 | python | en | code | 0 | github-code | 90 |
34716157901 | from selenium import webdriver
from selenium.webdriver.common.by import By
import time
chrome_driver_path = "/Users/huangshihao/Development/chromedriver"
driver = webdriver.Chrome(executable_path=chrome_driver_path)
driver.get("http://orteil.dashnet.org/experiments/cookie/")
count = 0
# grandma_value = driver.find_e... | hao134/100_day_python | day48_selenium_webdriver_browser_and_game_playing_bot/clickcookie.py | clickcookie.py | py | 1,946 | python | en | code | 2 | github-code | 90 |
8257231743 | from datetime import timedelta as t
from datetime import datetime as d
def gi(h):
for k in range(2, h + 1):
if pr_fun(k):
pre.append(k)
def pr_fun(h):
if h <= 1:
return False
for k in range(2, h):
if h % k == 0:
return False
return True
dye, dwk, h = in... | harsh6754/DSA-Problems | leetcode/PrmeVilla.py | PrmeVilla.py | py | 728 | python | en | code | 1 | github-code | 90 |
41529537851 | # -*- coding: utf-8 -*-
# @Author : 李惠文
# @Email : 2689022897@qq.com
# @Time : 2020/7/3 10:58
# 抖音爬虫
import datetime
import os
import sys
import getopt
import urllib.parse
import urllib.request
import copy
import codecs
import requests
import re
from six.moves import queue as Queue
from threading import Thread
import j... | NearHuiwen/TiktokCrawler | amemv-video-ripper.py | amemv-video-ripper.py | py | 24,868 | python | en | code | 43 | github-code | 90 |
27665823847 |
class MultiResultSet(object):
def __init__(self, entities):
self._entities = entities
self.raw = None
self.measurement = ""
def update(self, measurement, data):
self.measurement = measurement
self.raw = data.copy()
for k, v in self.raw.items():
if v:... | museghost/influxalchemy | influxalchemy/resultset.py | resultset.py | py | 365 | python | en | code | null | github-code | 90 |
44669472709 | import random
x = int(random.randrange(5,100))
print(x)
hak = int(input("Kaç Hakkınızın OLmasını İstersiniz :"))
if hak>5:
print("5 den daha hazla hak a sahip olmazsınız.")
while hak >5:
hak = int(input("Kaç Hakkınızın OLmasını İstersiniz :"))
a = 0
while hak >0:
a = int(input("Lutfen bir sayi girin... | osmanozden/basic_python_fundamental | loops_MY_FİRS_GAME.py | loops_MY_FİRS_GAME.py | py | 718 | python | tr | code | 0 | github-code | 90 |
37845781990 | import numpy as np
import pandas as pd
import re
import sqlite3
# import data from csv file
df1 = pd.read_csv('sample.csv')
# pre-processing
df1.drop(columns=['Sticker taps', 'Content type', 'Replies', 'Results', 'Cost per result'], inplace=True)
# df1['Post time'] = pd.to_datetime(df1['Post time'])
df1 = df1.loc[df1... | Patcharanat/Marketing-Dashboard | marketing_dashboard_script.py | marketing_dashboard_script.py | py | 4,454 | python | en | code | 1 | github-code | 90 |
24333941495 | import logging
from .analyzer import Analyzer
from ..matrix.geomatrix import GeoMatrix, PersistentGeoMatrix
L = logging.getLogger(__name__)
class GeoAnalyzer(Analyzer):
'''
This is the analyzer for events with geographical points dimension.
`GeoAnalyzer` operates over the `GeoMatrix` object.
`matrix_id` is... | pypi-buildability-project/BitSwanPump | bspump/analyzer/geoanalyzer.py | geoanalyzer.py | py | 1,438 | python | en | code | null | github-code | 90 |
40746228755 | import re
class CatalPhoto(object):
"""Represents a photo in the Catalhoyuk archive."""
# Regex for extracting record ID from a URL
record_id_re = re.compile(r'(original|preview)=(\d+)', flags=re.IGNORECASE)
def __init__(self, url, annotation=None):
self.url = str(url)
self.record_id... | chrischute/catal | catal/catal_photo.py | catal_photo.py | py | 629 | python | en | code | 0 | github-code | 90 |
17419482192 |
import os, pprint
from krrt.utils import get_file_list, write_file
from data import *
forbidden_files = ['__init__', 'api.py']
def get_name(dom):
suffixes = ['-sat', '-opt', '-strips', '-fulladl', '-06', '-08', '-00', '-02', '98', '00', '-simpleadl', '-adl']
name = dom.split('/')[-1]
for s in suffixes:
... | AI-Planning/api-tools | scripts/formalism-initialization/classical/create-meta.py | create-meta.py | py | 5,643 | python | en | code | 11 | github-code | 90 |
7568317516 | # -*- coding: utf-8 -*-
"""
Assignment 5 problem 3
Computes the total energy per unit area
radiated by a blackbody by computing the integral
I=\int_0^\infty \frac{x^3}{\exp{x}-1} dx multiplied
by a constant. Analytically this integral may in fact be evaluated exactly,
using the Riemann zeta and Gamma functions. Using... | cklanger/Assignment_5 | Langer_problem3.py | Langer_problem3.py | py | 1,713 | python | en | code | 0 | github-code | 90 |
20767418531 | import sys
input = sys.stdin.readline
def cantor(length):
if length == 1:
return '-'
lines = cantor(length // 3)
blank = ' ' * (length // 3)
return lines + blank + lines
if __name__ == '__main__':
while True:
try:
N = int(input())
print(cantor(3**N))
... | feVeRin/Algorithm | problems/4779.py | 4779.py | py | 348 | python | en | code | 0 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.