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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
22766444587 | from flask import Blueprint, render_template, url_for, request, redirect, flash, make_response
from flask_login import login_required, current_user
from models import * # import database details
from sqlalchemy import or_
import matplotlib.pyplot as plt
import io
import base64
import sqlite3
# creating bluep... | Satyajay2020/College_Project | analytics.py | analytics.py | py | 1,109 | python | en | code | 0 | github-code | 36 |
16109071350 | import requests
authors = ['John Donne', 'George Herbert', 'Andrew Marvell', 'Richard Crashaw', 'Henry Vaughan', 'Anne Bradstreet', 'Katherine Philips', 'Sir John Suckling', 'Edward Taylor']
# authors = ['William Shakespeare']
titles = []
#prohibited_punctuation = [',', ';', ' ', '"']
prohibited_punctuation = [' ', '... | canzhiye/metaphysical-poetry-generator | poetry_grabber.py | poetry_grabber.py | py | 983 | python | en | code | 0 | github-code | 36 |
23115996703 | import torch
from NAQS import NAQS, intial_state
from lnZ_2d import TensorSampling, HonNN
import numpy as np
from scipy.linalg import sqrtm
from scipy import sparse
import csv
import time
def learning(model, model0, optimizer, loss_func, epoch_start, epoch_end, batch_size, my_device, beta=1.0, memo='init', save... | Sixuan00/Free-Energy-NN | 2D/New Method/main.py | main.py | py | 15,844 | python | en | code | 0 | github-code | 36 |
1817846315 | #! /bin/python
# gsheet flask entry handler
#
# @file: gsheet
# @time: 2022/01/26
# @author: Mori
#
import flask
from service.gsheet import (
init_credentials,
compelete_worksheet,
reading_worksheet,
read_wks_from_google_sheet,
)
SHEET_ID = "1vXqHdA6RTD9cMMv8CvRQMW-jM9GSajAZOVcdJMwEFDM"
WKS_TITLE = "... | moriW/auto_firebase | backend/web/gsheet.py | gsheet.py | py | 1,147 | python | en | code | 0 | github-code | 36 |
3336257171 | from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
import requests
import time
import pandas as pd
import json
from pp... | ur2136/DrinkEasy | CodeBase/BackEnd/Pre-Processing Scripts/googleplaces.py | googleplaces.py | py | 7,915 | python | en | code | 0 | github-code | 36 |
33467143543 | DEFAULTS = {
'label': "\uf538 {virtual_mem_free}/{virtual_mem_total}",
'label_alt': "\uf538 VIRT: {virtual_mem_percent}% SWAP: {swap_mem_percent}%",
'update_interval': 5000,
'callbacks': {
'on_left': "toggle_label",
'on_middle': "do_nothing",
'on_right': "do_nothing"
},
'... | denBot/yasb | src/core/validation/widgets/yasb/memory.py | memory.py | py | 2,131 | python | hi | code | 593 | github-code | 36 |
37633953540 | # Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.
#
# For all leaves in the tree, consider the numbers represented by th... | sunnyyeti/Leetcode-solutions | 1022_Sum_of_Root_To_Leaf_Binary_Numbers.py | 1022_Sum_of_Root_To_Leaf_Binary_Numbers.py | py | 1,292 | python | en | code | 0 | github-code | 36 |
11747758050 | import streamlit as st
import numpy as np
import pandas as pd
st.title('Steamlit 基礎')
st.write('Hello World!')
st.write('I love World')
df = pd.DataFrame({
'1列目': [1,2,3,4],
'2列目': [10,20,30,40]
})
st.dataframe(df.style.highlight_between(axis=1), width=300,height=150)
df_1 = pd.DataFrame(
np.random.rand(10... | tetsukira/iris_streamlit | main.py | main.py | py | 1,489 | python | ja | code | 0 | github-code | 36 |
74839486503 | from lxml import etree
import pandas
def getdata(name , indx):
allarr = []
f = open(name, encoding="utf-8")
# 输出读取到的数据
text = f.read()
f.close()
htmll = etree.HTML(text)
arr = []
arr.append(indx)
name = htmll.xpath('//div[@class="Blockreact__Block-sc-1xf18x6-0 Flexreact__Flex-sc-1... | chenqiuying1023/opensea-supergucci | handletocsv.py | handletocsv.py | py | 2,353 | python | en | code | 1 | github-code | 36 |
29613368843 | import os,random,warnings,time,math
import torch
import torch.nn as nn
from dataloader.data_loader import prepare_dataset, _collate_fn
from base_builder.model_builder import build_model
from dataloader.vocabulary import KsponSpeechVocabulary
from omegaconf import OmegaConf
from tensorboardX import SummaryWriter
... | jungwook518/WOOK_Challenge | test.py | test.py | py | 2,663 | python | en | code | 0 | github-code | 36 |
34879164954 | import pyvisa as visa
import time
from datetime import datetime
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
plt.rcParams['animation.html'] = 'jshtml'
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure impo... | DbIXAHUEOKEAHA/LPI_RAS | GPIB_window.py | GPIB_window.py | py | 7,233 | python | en | code | 0 | github-code | 36 |
33596607925 | import sys
import numpy as np
import pandas as pd
#from agents.policy_search import PolicySearch_Agent
from agents.agent import DDPG
from task import Task
num_episodes = 1000
target_pos = np.array([0., 0., 100.])
task = Task(target_pos=target_pos)
agent = DDPG(task)
for i_episode in range(1, num_episodes+1):
sta... | AndyClouder/ML | RL-Quadcopter-2/project.py | project.py | py | 817 | python | en | code | 1 | github-code | 36 |
17453339669 | import torch.nn as nn
import torch.nn.functional as F
import torch
import numpy as np
def get_fpn_sf_global(num_classes, mode):
return FPN_SF(num_classes, expansion=4, mode=mode)
def get_fpn_sf_local(num_classes, mode):
return FPN_SF(num_classes, expansion=1, mode=mode)
class FPN_SF(nn.Module):
def _... | yida2311/OSCC_SF | models/fpn_semantci_flow.py | fpn_semantci_flow.py | py | 8,230 | python | en | code | 0 | github-code | 36 |
26080680770 | # while을 이용한 반복문
i = 1
while i<= 100:
print(i, end=' ')
i += 1 # ++i 불가능
# 1 ~ 100 사이 정수 중 홀수만 출력
i = 1
sum = ''
while i <= 100:
if i % 2 == 1: sum += str(i) + ' '
i += 1
print(sum)
# 무한루프
# 반복문의 조건식이 언제나 참이면
# 반복을 중단하지 않고 계속 반복을 지속하는 상황
# 단, 무한루프에서 탈출하려면 break를 이용
# while True:
# 반복실행할 문장
# 반복실행 ... | Dongcoon/python39 | 12while.py | 12while.py | py | 2,143 | python | ko | code | 0 | github-code | 36 |
14257608746 | import csv, os, glob, google_trans_new
from tqdm import tqdm # sweet progress bar
#==============================================================================
def get_lang():
"""
Purpose:
gets language to translate to from user
Dependencies:
google_trans_new
Argument:
None
... | mcheffer/xml_translator | xml_translator.py | xml_translator.py | py | 4,817 | python | en | code | 0 | github-code | 36 |
25107393040 | from Util.Network import Network
from queue import Queue
from Actors.ActorsController import ActorsController
from Actors.Direction import Direction
class NetworkController:
def __init__(self, actorsController : ActorsController):
self.messageQueue = Network().getMessageQueue()
self.actorsCon... | VolodymyrVakhniuk/Pacman | src/Util/NetworkController.py | NetworkController.py | py | 2,400 | python | en | code | 1 | github-code | 36 |
24528496813 | import torch
import random
import numpy as np
from collections import deque
from game import SnakeAI,NSWE
from model import LinearQNet,QTrainer
import matplotlib.pyplot as plt
from IPython import display
Block=20
MAX_MEM=100_000
Batch_Size=1000
Learning_Rate=0.001
class Agent:
def __init__(self):
self.n... | MakisEu/SnakeAI | agent.py | agent.py | py | 5,158 | python | en | code | 0 | github-code | 36 |
20160442598 | from superlink import security
import mysql.connector as sqltor
from tabulate import tabulate
security.security_init() #Starts monitoring people by asking username/password
secure = security.isSecured() #Boolean
#_main_
if secure==True:
conn = sqltor.connect(host="localhost", user="root", passwd="root"... | Project-CS-2022/ProjCS-2022-02-08-Final | CS Proj/Project/collaborators.py | collaborators.py | py | 1,556 | python | en | code | 0 | github-code | 36 |
38650181804 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from math import pi, sin, cos, atan, degrees
from sympy import *
from matplotlib.ticker import MultipleLocator, AutoMinorLocator
DF = True
IS_SCATTER = False
df = pd.read_csv('/Users/shetshield/Desktop/workspace/python_ws/sim_lin_bend/sim_res_1c... | shetshield/src | srm/kinematic_model.py | kinematic_model.py | py | 8,580 | python | en | code | 0 | github-code | 36 |
20450214874 | import singleRepoStats
import datetime
import pandas as pd
import featureMakers
def getPredictionsTrace(repoString, tend = datetime.date.today()):
weeklyData = singleRepoStats.getRepoWeeklyData(repoString)
weeklyTotal = weeklyData.pivot(index='week_start', columns='author_login', values='commits_num').sum(axis=1)... | gauthamnair/repopulse | predictionsVisualizer.py | predictionsVisualizer.py | py | 1,069 | python | en | code | 1 | github-code | 36 |
41211954881 | print("MAKE SURE DON'T USE ANY NUMBER")
email = input("Enter you email the following pattern : (firstname.lastname@example.com)")
result = email.split(".")
if "@" in result[1]:
index = result[1].index('@')
last_name = result[1][:index]
first_name = result[0]
print("Hi, "+first_name.capita... | ankan-das-2001/test | Name_finding.py | Name_finding.py | py | 355 | python | en | code | 0 | github-code | 36 |
1648346728 | # canvas = widget that is used to draw graphs, plots, images in a window
from tkinter import *
window =Tk()
canvas = Canvas(window,height=500,width=500)
# canvas.create_line(0,0,500,500,fill='brown',width=5)
# canvas.create_line(0,500,500,0,fill='pink',width=5)
# canvas.create_rectangle(50,50,250,250,fill='gray... | seemannsgarn/templates | python/86_canvas.py | 86_canvas.py | py | 758 | python | en | code | 0 | github-code | 36 |
33512502317 | from math import sqrt, fabs
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from numpy import genfromtxt
# Grid configurations
plt.grid(True, linewidth=0.2, c='k')
def get_near_psd(A_matrix):
A_sym = (A_matrix + A_matrix.T) / 2
eigval, ... | optimization-for-data-driven-science/RIFLE | RIFLE_via_ADMM/ADMM_Synthetic.py | ADMM_Synthetic.py | py | 17,963 | python | en | code | 8 | github-code | 36 |
15685242927 | import pygame
import glob
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.player_walk_right = []
self.player_walk_left = []
self.player_walk = self.player_walk_left
for player_frame in glob.glob('Static/Character/walk_right/*.png'):
... | SlimeyTurtles/GameJam1 | player.py | player.py | py | 1,900 | python | en | code | 0 | github-code | 36 |
1607792294 | from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
# from pdfminer.pdfdevice import PDFDevice
# 获取需要读取的PDF文档对象
pdfFile = open("一种折叠屏上使用的付款码使用方式.pdf", "rb... | BianDongLei/study_demo | Python/PythonDemo/PythonTest/pdfreader.py | pdfreader.py | py | 1,196 | python | zh | code | 0 | github-code | 36 |
4062869368 | import turtle
def main():
#switzerland
t = turtle.Turtle()
t.hideturtle()
drawRectangle2(t, (0,0), 100, 100, "red")
drawRectangle2(t, (20,40), 60, 20, "white")
drawRectangle2(t, (40,20), 20, 60, "white")
def drawRectangle2(t, startPoint, width, height, color):
t.up()
t.setheading(0)
... | guoweifeng216/python | python_design/pythonprogram_design/Ch6/6-3-E24.py | 6-3-E24.py | py | 587 | python | en | code | 0 | github-code | 36 |
27628264577 | class Solution:
def addBinary(self, a: str, b: str) -> str:
# Not using In-Built methods
max_len = max(len(a), len(b))
a = a.zfill(max_len)
b = b.zfill(max_len)
carry = 0
result = ''
for i in range(max_len-1, -1, -1):
r = carry
if a[i... | ArramBhaskar98/LeetCode | Concepts/Bit_Manipulation/Add_Binary.py | Add_Binary.py | py | 1,171 | python | en | code | 0 | github-code | 36 |
73186863145 | # You dont need to run this script.
# It will be executed by the GradeScope Autograder
# Do not input anything else other than the instructions given in comments, remember that python is tab and caps sensitive.
# In the place of *, input your answer.
import unittest # Import the gradescope autograder library. No actio... | angmavrogiannis/24677-Linear-Control-Systems | HW3/hw3_theory.py | hw3_theory.py | py | 2,969 | python | en | code | 2 | github-code | 36 |
2556587569 | from bs4 import BeautifulSoup
import requests
from time import sleep
import re
from collections import OrderedDict
from utils import save_csv , URL_RESOURCES
# Separar chamadas de cada página usando asyncio
def get_parsed_content(url):
content = requests.get(url).content
parsed_content = BeautifulSoup(co... | Marlysson/craw | core/resources/crawlers/countries_infos.py | countries_infos.py | py | 1,950 | python | en | code | 0 | github-code | 36 |
33717929549 | """
● 문제 : https://school.programmers.co.kr/learn/courses/30/lessons/12909
괄호가 바르게 짝지어졌다는 것은 '(' 문자로 열렸으면 반드시 짝지어서 ')' 문자로 닫혀야 한다는 뜻입니다. 예를 들어
"()()" 또는 "(())()" 는 올바른 괄호입니다.
")()(" 또는 "(()(" 는 올바르지 않은 괄호입니다.
'(' 또는 ')' 로만 이루어진 문자열 s가 주어졌을 때, 문자열 s가 올바른 괄호이면 true를 return 하고, 올바르지 않은 괄호이면 fal... | ayocado/algorithm-study | ayocado/스택,큐/PGS level2 12909 올바른 괄호.py | PGS level2 12909 올바른 괄호.py | py | 1,836 | python | ko | code | 0 | github-code | 36 |
70517474343 | #字典
alien_0 = {'color':'green','points':'5'}
print(alien_0['color'])
print(alien_0['points'])
alien_0['x_postion'] = 0
alien_0['y_postion'] = 25
print(alien_0)
alien_0['color'] = 'yellow'
alien_0['speed'] = 'medium'
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] =='medium':
x_increment = 2
els... | CN-COTER/python_test | t009.py | t009.py | py | 2,787 | python | en | code | 0 | github-code | 36 |
30285193715 | import random
def handler(major_sentiment):
positive_response_list = ["That's very nice", "I'm happy you are feeling good"]
negative_response_list = ["I'm sorry to hear that", "Tell me about that"]
neutral_response_list = [
"Thank you for sharing",
"Well I'm happy we have time to talk",
... | aaryanDhakal22/Mycompanion | homepage/sentiment_handler.py | sentiment_handler.py | py | 620 | python | en | code | 1 | github-code | 36 |
34358988987 | import SECRETS
import os
import openai
openai.organization = "org-0iQE6DR7AuGXyEw1kD4poyIg"
# openai.api_key = os.getenv(SECRETS.open_ai_api_key)
openai.api_key = SECRETS.open_ai_api_key
# print(openai.Model.list())
print("starting test")
def get_roast_str_from_username(username):
completion = openai.Completio... | Brandon-Valley/tik_live_host | src/open_ai_api_test.py | open_ai_api_test.py | py | 1,931 | python | en | code | 0 | github-code | 36 |
74267287785 | # -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | line/line-bot-sdk-python | examples/fastapi-echo/main.py | main.py | py | 2,424 | python | en | code | 1,739 | github-code | 36 |
18924484365 | import pytest
from base.webdriverfactory import WebDriverFactory
from pages.home.login_page import LoginPage
@pytest.yield_fixture()
def setUp():
print("Running method level setUp")
yield
print("Running method level tearDown")
@pytest.yield_fixture(scope="class")
def oneTimeSetUp(request, browser):
p... | PacktPublishing/-Selenium-WebDriver-With-Python-3.x---Novice-To-Ninja-v- | CODES/S31 - Automation Framework -_ Practice Exercise/1_conftest.py | 1_conftest.py | py | 976 | python | en | code | 11 | github-code | 36 |
2945906050 | import streamlit as st
import math
st.title("Caesar Cipher")
message = st.text_input("Enter the plaintext: ")
key = math.floor(st.number_input("Enter the secret key: "))
def CaesarCipher(message: str, key: int) -> str:
if not message:
return "Please enter a message."
key %= 26
val =... | GowthamNats/CaesarCipher | CaesarCipher.py | CaesarCipher.py | py | 954 | python | en | code | 0 | github-code | 36 |
21334697627 | import unittest
import numpy as np
import pandas as pd
from os.path import join, dirname
from pandas import read_csv
from sostrades_core.execution_engine.execution_engine import ExecutionEngine
class GHGEmissionDiscTest(unittest.TestCase):
def setUp(self):
self.name = 'Test'
self.ee = Execution... | os-climate/witness-core | climateeconomics/tests/l0_test_ghgemissions_discipline.py | l0_test_ghgemissions_discipline.py | py | 3,374 | python | en | code | 7 | github-code | 36 |
14980635082 | import cv2
import os
import Predict as p
subjects = ["", "Ranbir", "Elvis Presley","Change it with your name"]
#load test images
test_img1 = cv2.imread("test-data/1.1.jfif")
test_img2 = cv2.imread("test-data/1.2.jfif")
test_img3 = cv2.imread("test-data/1.3.jpg")
#perform a prediction
predicted_img1 =... | ankitvarma604/Face-Detection | face_detection.py | face_detection.py | py | 693 | python | en | code | 0 | github-code | 36 |
10154909522 | from date import Date
""" CORE REQUIREMENTS """
class Assignment:
def __init__(self,
name="Untitled",
start=Date(),
due=Date(),
end=Date()):
self.name = name
self.start = start
self.due = due
self.end = end
def prompt(self):
self.na... | AnastasiaYazvinskaya/CS-241-Survey-Obj-Ort-Prog--Data-Struct | team/teamW04/assignment.py | assignment.py | py | 1,012 | python | en | code | 0 | github-code | 36 |
139802964 | import os
import sys
import logging
from datetime import datetime
from mongoengine.errors import ValidationError
sys.path.insert(1, os.path.join(os.getcwd(), '../', 'src'))
from flaskapp.model import User
logger = logging.getLogger()
def create_user():
new_user = User(lastAccess=datetime.utcnow(), documents=[]... | bangjh0730/asdf | src/flaskapp/user.py | user.py | py | 2,029 | python | en | code | 0 | github-code | 36 |
3195540576 | import requests
import re
#Obtendo html
nothing = 44827
divide = False
while nothing:
print(f'----------------------------------------\ncurrent nothing is: {nothing}')
url = f"http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing={nothing}"
html = requests.get(url).text
print(html)
numbers =... | TassioS/Python-Challenge | 4.py | 4.py | py | 560 | python | en | code | 0 | github-code | 36 |
12551393018 | #!/usr/bin/python2.7
# _*_ coding:utf-8 _*_
#py2.7不用转码
import socket
host=''
port=50000
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #s为套接字(服务器间网络通信,for TCP流式socket)
s.bind((host,port)) #将s套接字绑定ip地址,在端口
s.listen(2) #开始监听,接受客户端的连接
while 1:
conn,addr=s.accept() #接受了连接,并且返回conn对象和addr地址
print('我被... | SuneastChen/socket_demo | server端/socket_server.py | socket_server.py | py | 809 | python | zh | code | 0 | github-code | 36 |
26605607209 | from db_client import cursor, db
from datetime import date, datetime
from random import randint, randrange
from queries.insert_queries import *
from insert_tables import insert_sample_rows
from create_tables import create_tables
from utils import delete_all_rows_from_database, list_of_tables
def select_sample_rows()... | SpeedyFoods/database | utils/select_tables.py | select_tables.py | py | 2,646 | python | en | code | 0 | github-code | 36 |
33257008973 | #Q4. 3번 문제까지 해결하셨다면, 이제 학습을 위한 준비는 거의 끝났다고 볼 수 있습니다. 위 구현 함수들을 이용해 학습 Loop를 구현해보세요.
#위에서 구현한 모델, optimzer, loss fn 등을 이용해 학습을 구현해주세요.
for epoch in range(training_epochs):
for i, (imgs, labels) in enumerate(train_loader):
#input 데이터 얻음
imgs, labels = imgs.to(device), labels.to(device)
# MNI... | oguuk/AI_Basic | 5주차 미션/A4.py | A4.py | py | 1,742 | python | ko | code | 0 | github-code | 36 |
12233028834 | from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
import os
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time
from datetime import date
from pandas_datareader import data as pdr
import yfinance as yf
yf.pdr_override()
i... | markb2575/AI-Stock-Predicter | predict-weekly/weekly.py | weekly.py | py | 4,674 | python | en | code | 0 | github-code | 36 |
36505762158 | import numpy as np
import matplotlib.pyplot as plt
print('Enter n')
n = int(input())
print('Enter 0 if Left Riemann Sum')
print('Enter 1 if Midpoint Riemann Sum')
print('Enter 2 if Right Riemann Sum')
i = int(input())
f = lambda x: x ** 2
a, b = 1, 2
dx = 1 / n
x_left = np.linspace(a, b - dx, n)
x_midpoint = np.linspa... | alekseevavlada/Laba_Math | main.py | main.py | py | 1,871 | python | en | code | 0 | github-code | 36 |
12534507732 | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import datetime
df = pd.read_csv("D-GROWTH.csv")
df['Date'] = pd.to_datetime(df["Date"])
all_years = df['Date'].dt.year.unique()
temp = {'Date': [], 'Growth': []}
for i in all_years:
for j in range(12, 0, -1):
data = df[(df[... | icyboguyaman/Python-Small-Projects | hw1.py | hw1.py | py | 1,139 | python | en | code | 0 | github-code | 36 |
19650964596 | # ExperimentDetails is for collecting all the experiment-related details
class ExperimentDetails(object):
def __init__(self, ExperimentName=None, EngineName=None, ChaosDuration=None, ChaosInterval=None, RampTime=None, Force=None, ChaosLib=None,
ChaosServiceAccount=None, AppNS=None, AppLabel=None, AppKind=None, Inst... | litmuschaos/litmus-python | pkg/generic/pod_delete/types/types.py | types.py | py | 1,403 | python | en | code | 10 | github-code | 36 |
11149235900 | from math import floor
import os
import sys
os.system("cls")
with open('day15.txt',"r") as f:
inp1 = f.read().split("\n")
inp1 = [[int(xx) for xx in x] for x in inp1]
orows = len(inp1)
ocols = len(inp1[0])
rows = orows*5
cols = ocols*5
inp = [[0 for column in range(cols)]
for row in range(row... | VarunDandekar/adventOfCode2021 | day15-Chiton.py | day15-Chiton.py | py | 2,980 | python | en | code | 0 | github-code | 36 |
28798495371 | #Saumit Madireddy
#I pledge my honor that I have abided by the Stevens Honor System.
def main():
is_correct = True
months_with_31_days = [1, 3, 5, 7, 8, 10, 12]
date = input("Enter a date in the month/day/year format (xx/xx/xxxx): ")
date_list = date.split("/")
if len(date_list) !=3:
is_c... | Eric-Wonbin-Sang/CS110Manager | 2020F_hw6_submissions/madireddysaumit/Date.py | Date.py | py | 877 | python | en | code | 0 | github-code | 36 |
21150674567 | from django.shortcuts import render, get_object_or_404, get_list_or_404
from django.http import HttpResponseRedirect, Http404
from django.urls import reverse
from django.contrib import messages
# import model from another module
# import Users model from authentication module
from authentication.models import Users, ... | Optisoftdev/S5 | administrator/views.py | views.py | py | 2,765 | python | en | code | 0 | github-code | 36 |
25364145372 | import cv2 as cv
import numpy as np
'''
Tranformação geometrica:
Rotação:
>getRotationMatrix2D(center, angle, scale) -> Obtem uma matriz de rotação.
==>center -> Indica o centro da imagem (X, Y)
==>angle -> Define o ângulo desejado para rotacionar [0, 360]
==>scale -> Escala para imagem
>warpAffine(src, matriz, dsize)... | abelsco/PyExerciciosOpencv | transformacaoGeo.py | transformacaoGeo.py | py | 1,210 | python | pt | code | 0 | github-code | 36 |
16147247734 | from app.settings import PLAYER_1, PLAYER_2
def verify_start(data):
player_1_moves = "".join(data['player1']["moviminetos"])
player_2_moves = "".join(data['player2']["moviminetos"])
player_1_golpe = "".join(data['player1']["golpes"])
player_2_golpe = "".join(data['player2']["golpes"])
player_1_tot... | FranciscoAczayacatl/GameRPG | app/game/start.py | start.py | py | 939 | python | en | code | 0 | github-code | 36 |
19036931812 | import logging
import zmq
from cifsdk.actor.manager import Manager as _Manager
from cifsdk.actor import Actor as Enricher
from .constants import TRACE, ENRICHER_ADDR, ENRICHER_SINK_ADDR, \
LOGLEVEL
logger = logging.getLogger(__name__)
logger.setLevel(LOGLEVEL)
if TRACE:
logger.setLevel(logging.DEBUG)
clas... | csirtgadgets/cif-v5 | cif/enricher/manager.py | manager.py | py | 765 | python | en | code | 61 | github-code | 36 |
74647178343 | import logging
import os
from wafl.connectors.bridges.llm_task_extractor_bridge import LLMTaskExtractorBridge
from wafl.extractors.dataclasses import Answer
_path = os.path.dirname(__file__)
_logger = logging.getLogger(__file__)
class TaskExtractor:
def __init__(self, config, interface, logger=None):
se... | fractalego/wafl | wafl/extractors/task_extractor.py | task_extractor.py | py | 1,268 | python | en | code | 6 | github-code | 36 |
36652176172 |
"""
This is meant to be executed using mpirun. It is called as a subprocess
to run an MPI test.
"""
if __name__ == '__main__':
import sys
import os
import traceback
from mpi4py import MPI
from testflo.test import Test
from testflo.cover import setup_coverage, save_coverage
from testflo.... | naylor-b/testflo | testflo/mpirun.py | mpirun.py | py | 1,731 | python | en | code | 8 | github-code | 36 |
867921304 | from random import choice
# Suit Element Attribute Description
# ==== ====== ======== ==========
# WANDS Fire Physical incarnation of physical strength and resilience
# SWORDS Air Mental mental aspects of life
# CUPS Water Emotional/Creative ... | nephitejnf/fortune-engine-rpg | tarot_cards.py | tarot_cards.py | py | 3,668 | python | en | code | 0 | github-code | 36 |
1306942751 | import turtle
import math
r = int(input("Enter the radius:"))
turtle.hideturtle()
turtle.circle(r)
turtle.done()
c = 2 * math.pi * r
s = math.pi * r * r
print("Chu vi của hình tròn có bán kính = {r} là {c}".format(r=r, c=c))
print("Diện tích của hình tròn có bán kính = {r} là {s}".format(r=r, s=s)) | tholuongduc/mypython3 | Day6/Tinh_chu_vi_dien_tich_hinh_tron.py | Tinh_chu_vi_dien_tich_hinh_tron.py | py | 322 | python | vi | code | 0 | github-code | 36 |
74384441065 | if __name__ == "__main__":
import __fixDir__
import tkinter
class MenuBar(tkinter.Frame):
def __init__(self, clide, activebackground="#4B6EAF", textColor="white", *args, **kwargs):
tkinter.Frame.__init__(self, clide, *args, **kwargs)
fileButton = tkinter.Menubutton(self, text="File", bg=self... | zlmonroe/CLIDE | CLIDElib/MenuBar.py | MenuBar.py | py | 2,179 | python | en | code | 1 | github-code | 36 |
3533175991 | import gym
from random import sample
from keras import optimizers, Sequential
from keras.layers import Dense
from numpy import random, argmax
import numpy as np
from gym.spaces import Box, Discrete
import logging
from keras.utils import to_categorical
import sys
import pickle
import logging
from actor_evaluator impor... | nsragow/RlGym | dqn_frozen_categorical.py | dqn_frozen_categorical.py | py | 6,297 | python | en | code | 0 | github-code | 36 |
69957139306 | def birthday(s, d, m):
"""_summary_
Args:
s (_type_): Chocolate array
d (_type_): Number to sum to
m (_type_): Number of squares of chocolate
Returns:
_type_: _description_
"""
num_days = 0
if len(s) == 0:
return 0
print(s, d, m)
for cnt, val i... | acatejr/hackerrank | subarray_division.py | subarray_division.py | py | 709 | python | en | code | 0 | github-code | 36 |
36860255897 | __author__ = 'Jonny'
__date__ = '2018-03-07'
__location__ = '西安'
# -*- coding: utf-8 -*-
import time
import login
import check
import requests
import station
import booking
#---------------------------- 登录账户--------------------------------------------------
def logIn(request):
state = 1
while(state != 0):
... | JonnyLe/Python-12306- | 12306.py | 12306.py | py | 3,866 | python | zh | code | 0 | github-code | 36 |
4897008783 | from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import Group
from django.contrib.auth.models import PermissionsMixin
from django.core.exceptions import ValidationError
from django.core.validators import FileExtensionValidator
from django.core.validators import RegexValidator
f... | veresen01/django-shop | ___shop___/app_users/models.py | models.py | py | 2,768 | python | en | code | 0 | github-code | 36 |
22226448679 | import numpy as np
import pandas as pd
import argparse
def get_tail(hmm, ncRNA, strict=False):
expression = [int(x) for x in hmm.loc[ncRNA].score.split(',')]
if (np.mean(expression) > 1.5) and (len(expression) > 1000):
trim_length = trim_expression(expression, strict)
return trim_length
els... | bfairkun/ChromatinSplicingQTLs | code/scripts/NonCodingRNA/trim_ncRNAs.py | trim_ncRNAs.py | py | 14,065 | python | en | code | 0 | github-code | 36 |
8089350142 | class Solution:
def transpose(self, A: List[List[int]]) -> List[List[int]]:
row = len(A)
col = len(A[0])
if row == col:
for i in range(1, len(A)):
for j in range(i):
A[i][j], A[j][i] = A[j][i], A[i][j]
return A
else:
... | alankrit03/LeetCode_Solutions | 867. Transpose Matrix.py | 867. Transpose Matrix.py | py | 518 | python | en | code | 1 | github-code | 36 |
13989507368 | from collections import deque
class Solution:
def averageOfLevels(self, root):
queue = deque([(root, 0)])
prev_lev = -1
sum_lev = 0
cnt_lev = 0
avg_lev = []
while queue:
node, lev = queue.popleft()
if lev != prev_lev:
if cnt_le... | dariomx/topcoder-srm | leetcode/zero-pass/facebook/average-of-levels-in-binary-tree/Solution.py | Solution.py | py | 716 | python | en | code | 0 | github-code | 36 |
17240859097 | import sys
import math
import numpy as np
# UNCERTAINTY FUNCTIONS written by Adrian Alcolea ("https://github.com/AdrianAlcolea") for the work presented in:
"https://github.com/universidad-zaragoza/BNN_for_hyperspectral_datasets_analysis"
# =========================================================================... | universidad-zaragoza/ML-for-the-diagnosis-of-Wilson-s-Disease-via-ICP-MS | analysis_uncertainty.py | analysis_uncertainty.py | py | 3,926 | python | en | code | 1 | github-code | 36 |
70183489063 | from decimal import Decimal, InvalidOperation
from typing import TYPE_CHECKING, Any, List, Optional, TypedDict
from django.db import models, transaction
if TYPE_CHECKING:
from senda.core.models.clients import ClientModel
from senda.core.models.localities import LocalityModel, StateChoices
from senda.core.... | UNPSJB/SendaAlquiler | backend/senda/core/managers.py | managers.py | py | 14,222 | python | en | code | 1 | github-code | 36 |
74572677542 | # Implement user-defined window size for the play. For example, an user
# could use a keyboard to input different values of widths and heights.
# Accordingly, the screen will display in different sizes regarding the user's input.
import cv2
print(cv2.__version__)
cam = cv2.VideoCapture(0)
width = int(input('Desired w... | Gabrielmbl/csci380 | lab3/lab3b_gl.py | lab3b_gl.py | py | 623 | python | en | code | 0 | github-code | 36 |
6700441105 | import os
import subprocess
class CPPInterop:
__cpp_file = None
_command_str = None
def __init__(self, file):
assert os.path.exists(file)
self.__cpp_file = file
self._command_str = self.__cpp_file
def build_command(self, use_equals=False, **kwargs):
"""
Builds... | h3nok/MLIntro | Notebooks/interop/cpp_interop.py | cpp_interop.py | py | 1,524 | python | en | code | 0 | github-code | 36 |
18291729121 | from PIL import Image
import numpy as np
def calculate_apl(filename):
"""Calculate the average picture level (APL) from an image.
Keyword arguments:
filename -- path of image
"""
# load the image
image = Image.open(filename)
# convert image to numpy array
data = np.asarray(image)
... | jdbremer/scripts | APL.py | APL.py | py | 698 | python | en | code | 0 | github-code | 36 |
32034767120 | # Вводятся данные в формате ключ=значение в одну строчку через
# пробел. Значениями здесь являются целые числа (см. пример ниже).
# Необходимо на их основе создать словарь d с помощью функции dict()
lst = list(map(str, input().split()))
for i in range(len(lst)):
lst[i] = lst[i].split('=')
for j in range(len(ls... | jon13doe/PythonLearnGit | SB_Python/8 dif lessons/0010.py | 0010.py | py | 7,177 | python | ru | code | 0 | github-code | 36 |
11168278407 | import csv
import json
from collections import defaultdict
import itertools
import os
import sys
import argparse
## NB update relevant config file name here
#from config2019 import *
# Mr Gorbachev, tear down etc etc
# Generate booth data structure (combinations hardcoded):
NPP_FIELDS = ["ID", "Division", "Booth", "L... | alexjago/nPP-Senate | src/SA1s_Multiplier.py | SA1s_Multiplier.py | py | 5,812 | python | en | code | 1 | github-code | 36 |
4022925396 | import requests
from requests.structures import CaseInsensitiveDict
import base64
import json
from django.conf import settings
requests.packages.urllib3.disable_warnings(
requests.packages.urllib3.exceptions.InsecureRequestWarning
)
GITHUB_TOKEN = getattr(settings, "GITHUB_TOKEN", None)
def deploy_done(
git... | kakaocloudschool/Multi_ojigo | api_utils/github_api.py | github_api.py | py | 6,199 | python | en | code | 2 | github-code | 36 |
30537139211 | from tkinter import *
from tkinter import messagebox
from openpyxl import *
import cv2
import pickle
import cvzone
import numpy as np
import os
root = Tk()
root.title("ParkiN")
root.geometry('925x500+300+200')
root.configure(bg='#fff')
root.resizable(False, False)
def book():
vehicleno = user.ge... | FrostPrince003/Book2Park | parkin.py | parkin.py | py | 8,405 | python | en | code | 0 | github-code | 36 |
30467024197 | from collections import deque
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [... | dundunmao/LeetCode2019 | 353. Design Snake Game.py | 353. Design Snake Game.py | py | 2,425 | python | en | code | 0 | github-code | 36 |
24549535365 | import logging
from pytest import raises, fixture
from kiwi_keg.image_definition import KegImageDefinition
from kiwi_keg.exceptions import KegError
class TestKegImageDefinition:
@fixture(autouse=True)
def inject_fixtures(self, caplog):
self._caplog = caplog
def setup(self):
self.keg_defi... | SUSE-Enceladus/keg | test/unit/image_definition_test.py | image_definition_test.py | py | 3,122 | python | en | code | 8 | github-code | 36 |
3930994654 |
age = 20
if age >= 6:
print('teen')
elif age >=18:
print('adult')
else:
print('kid')
# input
str = input('birth: ')
birth = int(str)
if birth < 2000:
print('00前')
else:
print('00后')
| chuancw/python_project1 | learn_lxf_python3/if.py | if.py | py | 213 | python | en | code | 3 | github-code | 36 |
8365518894 | from enum import Enum
from typing import Dict, TYPE_CHECKING, List, Union, cast
from ..types import TealType, require_type
from ..errors import TealInputError, verifyTealVersion
from ..ir import TealOp, Op, TealBlock
from .expr import Expr
from .txn import TxnField, TxnExprBuilder, TxnaExprBuilder, TxnObject
from .seq... | gconnect/voting-dapp-pyteal-react | venv/lib/python3.8/site-packages/pyteal/ast/itxn.py | itxn.py | py | 8,116 | python | en | code | 6 | github-code | 36 |
72182864424 | import Utils
from KernelNPRegression import KernelNPRegression
from RobustNPRegression import RobustNPRegression
from matplotlib import pyplot as plt
def draw_scatter(points, color):
plt.scatter([point[0] for point in points],
[point[1] for point in points],
c=color)
def draw_graphic(po... | DimaPhil/ML-Hometasks | HW5/main.py | main.py | py | 1,815 | python | en | code | 0 | github-code | 36 |
24733297429 | """
Contains the base map class.
"""
from .transformation import ImageTransformation
class Map:
"""The map is the basic class governing map generation.
Args:
width (int): The width of the map in pixels/
height (int): The height of the map in pixels.
crs (pyproj.crs.crs.CRS): The map c... | dolfandringa/pymapper | pymapper/map.py | map.py | py | 1,675 | python | en | code | 0 | github-code | 36 |
41214604531 | from Cell import Cell
import random
class Grid:
def __init__(self, xAmt, yAmt, gridID):
self.xAmt = xAmt
self.yAmt = yAmt
self.cells = [[Cell(False) for y in range(yAmt)] for x in range(xAmt)]
self.tCells = [[Cell(False) for y in range(yAmt)] for x in range(xAmt)]
self.las... | noside1231/MachineLearningCellularAutomata | Grid.py | Grid.py | py | 5,163 | python | en | code | 0 | github-code | 36 |
30850268568 | from BaseClasses.SpaceClass import Space
from BaseClasses.PlaneClass import Plane
from BaseClasses.VectorClass import Vector
from BaseClasses.SetClass import Set
class StaticSpace(Space):
def __init__(self, size: Vector, coors: Vector) -> None:
super().__init__(size)
self.coors = coors
def r... | AlexVorobushek/truckAndBoxesProblem | BaseClasses/StaticSpaceClass.py | StaticSpaceClass.py | py | 1,738 | python | en | code | 0 | github-code | 36 |
15204139120 | """import os
os.environ["KERAS_BACKEND"] = "theano"
import keras"""
import keras
print(keras.backend.backend())
from flask import request, render_template, redirect, url_for, Flask
import numpy as np
import time, random
from selenium import webdriver
from tensorflow.keras.models import load_model
from s... | siddhant230/Fun_Projects | activity_recognition/backend.py | backend.py | py | 2,059 | python | en | code | 4 | github-code | 36 |
19262690162 | from __future__ import print_function
import json
import logging
import os
import datetime
import calendar
import sys
from collections import OrderedDict
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
'''
Helper class for updating/retrieving Inventory ... | PokemonGoF/PokemonGo-Bot | pokemongo_bot/inventory.py | inventory.py | py | 53,475 | python | en | code | 3,815 | github-code | 36 |
75287914345 | son= int(input("Son kiriting: "))
temp= str(son)
list1=[]
show=[]
for i in range(0, len(temp)):
h=int(temp[i])
list1.append(h)
for i in range(0, len(list1)):
foo=0
for j in range(0, len(list1)):
if i!=j:
if list1[i]>list1[j]:
foo=foo+list1[i]-list1[j]
else... | Golibbek0414/PYTHON | imtihonfoundation/2-problem.py | 2-problem.py | py | 413 | python | en | code | 0 | github-code | 36 |
462183229 | from bot_base import ActivatableSimpleBot
from bot_util import *
import re
import random
class MemeBot(ActivatableSimpleBot):
P_REPLY = re.compile("^\\*\\*__What type of meme do you want to post?__\\*\\*\n")
P_NO_ITEM = re.compile("^oi you need to buy a laptop in the shop to post memes" + P_EOL)
P_MEME_DO... | Sadtrxsh/Mathboi | bot_meme.py | bot_meme.py | py | 3,426 | python | en | code | 0 | github-code | 36 |
10787931148 | from math import sqrt
def read_data(file_name):
# :param file_name: name of blogs file
# :return: row_names[]: blog names, col_names[]: blogs words, data[]: words occurrence in float
in_file = open(file_name, 'r')
print(in_file)
lines = in_file.readlines() # lines becomes a list of lists.
p... | Dawtt/collective_intelligence | clustering01/clusters.py | clusters.py | py | 4,956 | python | en | code | 0 | github-code | 36 |
428329513 | from django.shortcuts import render,redirect
# importamos la libreria generic
from django.views import View
from .models import *
from .forms import *
# Create your views here.
class AlumnoView(View):
def get(self,request):
listaAlumnos = TblAlumno.objects.all()
formAlumno = AlumnoForm()
... | Angellvz/DAE-2022-02-LAVENTURA | djangoApp07/django_panel/web/views.py | views.py | py | 689 | python | en | code | 0 | github-code | 36 |
15731209645 | from __future__ import annotations
from typing import Any
from typing import Dict
from typing import Set
from sqlalchemy import CHAR
from sqlalchemy import CheckConstraint
from sqlalchemy import Column
from sqlalchemy import event
from sqlalchemy import ForeignKey
from sqlalchemy import Index
from sqlalchemy import i... | sqlalchemy/alembic | alembic/testing/suite/_autogen_fixtures.py | _autogen_fixtures.py | py | 9,880 | python | en | code | 2,219 | github-code | 36 |
29247518148 | # Run 'discoronode.py' program to start processes to execute computations sent
# by this client, along with this program.
# This example is similar to 'discoro_client6.py', except it uses broadcasting
# over Channel to send messages to remote coroutines to process, and uses
# 'deque' module to implement circular buffe... | pgiri/asyncoro | examples/discoro_client6_channel.py | discoro_client6_channel.py | py | 5,369 | python | en | code | 51 | github-code | 36 |
8380776575 | import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (15, 5)
def plot_temperature(m, a, b, min, max):
"""
This function will plot the temperatures for a given month m, within the time range a-b and temperature range min-max.
m: The month the user chooses as a number... | cjiang94/INF3331-Python | assignment6/temperature_CO2_plotter.py | temperature_CO2_plotter.py | py | 2,116 | python | en | code | 0 | github-code | 36 |
43688718516 | import torch
from torch import nn
from torch.nn import Sequential as Seq, Linear as Lin, Conv2d
##############################
# Basic layers
##############################
def act_layer(act, inplace=False, neg_slope=0.2, n_prelu=1):
"""
helper selecting activation
:param act:
:param inplace:
:... | lightaime/sgas | gcn/gcn_lib/dense/torch_nn.py | torch_nn.py | py | 2,774 | python | en | code | 157 | github-code | 36 |
205686342 | import tensorflow as tf
import numpy as np
import gym
from gym.wrappers import Monitor
import random
import os
import time
def Policy(action_cnn,state,sess,epsilon, num_actions=4):
preds = sess.run(action_cnn.preds,{action_cnn.input:state[np.newaxis,:]})
p = np.ones(num_actions)*epsilon/num_actions
greedy_action =... | kabirahuja2431/DeepQLearning | dql.py | dql.py | py | 3,990 | python | en | code | 3 | github-code | 36 |
10829381285 | #!/usr/bin/env python
import os, sys
import json
import messytables
import subprocess
from dgitcore.helper import cd
from dgitcore.plugins.instrumentation import InstrumentationBase
from dgitcore.config import get_config
def run(cmd):
output = subprocess.check_output(cmd,
std... | pingali/dgit | dgitcore/contrib/instrumentations/executable.py | executable.py | py | 3,917 | python | en | code | 15 | github-code | 36 |
26676660869 | s = str(input())
a = s[0]
c = s[len(s)-1]
b = ""
for i in range(len(s)):
if s != 0 and s!= len(s) - 1:
b += s[i]
if a.isupper() == True and c.isupper() == True and b.isnumeric() == True:
b = int(b)
if b >= 100000 and b <= 999999 :
print("Yes")
exit()
print("No")
| MasaIshi2001/atcoder | ABC/ABC281_2.py | ABC281_2.py | py | 304 | python | en | code | 0 | github-code | 36 |
2303254132 | import os
import sys
from os.path import join, dirname
from dotenv import load_dotenv
import datetime
import time
import schedule
import logging
import iso8601
from googleapiclient.discovery import build
import functools
logger = logging.getLogger('autosnap')
logging.basicConfig(stream=sys.stdout, level=logging.INFO... | rehive/autosnap-docker | app.py | app.py | py | 2,996 | python | en | code | 0 | github-code | 36 |
33082220746 | import detectron2
from detectron2.utils.logger import setup_logger
import numpy as np
import os, json, cv2, random
from detectron2.data import MetadataCatalog, DatasetCatalog
from detectron2.structures import BoxMode
from detectron2.utils.visualizer import Visualizer
setup_logger()
# if your dataset is in COCO format... | sangminwoo/Temporal-Span-Proposal-Network-VidVRD | detectron/vidor_anno_to_coco_format.py | vidor_anno_to_coco_format.py | py | 4,815 | python | en | code | 14 | github-code | 36 |
33628626994 | from django.http.response import HttpResponse
from django.shortcuts import redirect, render
from django.contrib import messages
from .models import *
# Create your views here.
def index(request):
#put in something to see if the user is already logged in
if "user" in request.session:
context ={
... | chatbot6000/Troop44 | forumapp/views.py | views.py | py | 5,835 | python | en | code | 0 | github-code | 36 |
34145540015 | msg = "good"
import traceback
import os
try:
import os
import pickle
import onnxruntime as rt
from time import time
from transformers import RobertaForSequenceClassification, RobertaTokenizer
import numpy as np
import urllib
except Exception as e:
msg = traceback.format_exc()
tmp = "/tmp/"
cold = True... | COS-IN/iluvatar-faas | src/load/functions/python3/gpu-functions/onnx-roberta/main.py | main.py | py | 2,058 | python | en | code | 8 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.