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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
44019738022 | import unittest
"""
Given n non negative integers representing an elevation map where width of each bar is 1,
compute how much water it is able to trap after raining.
Input: 2 0 2
Output: 2
Input: 3 0 0 2 0 4
Output: 10
"""
"""
Approach:
1. A bar can store water if there are taller bars to its left and right.
2. We ca... | prathamtandon/g4gproblems | Arrays/trapping_rain_water.py | trapping_rain_water.py | py | 1,387 | python | en | code | 3 | github-code | 90 |
13657837295 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 26 15:43:41 2019
@author: zqwu
"""
import cv2
import numpy as np
import os
import pickle
import matplotlib
matplotlib.use('AGG')
import matplotlib.pyplot as plt
from scipy.signal import convolve2d
from .instance_clustering import within_range, chec... | mehta-lab/dynamorph | SingleCellPatch/extract_patches.py | extract_patches.py | py | 21,889 | python | en | code | 11 | github-code | 90 |
39635936640 | ##
## Library adapted from Berkeley AIMA GSOC
##
from search import *
# ----------------------------------------------------------------------------
# UTIL FUNCTIONS & CLASSES
# ----------------------------------------------------------------------------
class EightPuzzleProblem(Problem):
'''
A class for the ... | kojirowilliam/advanced_topics | homework_5/8_puzzle.py | 8_puzzle.py | py | 3,558 | python | en | code | 0 | github-code | 90 |
36756829553 | #!/usr/bin/python
import glob;
import re;
class Application:
pass
categories = { 'AudioVideo' : [],
'Audio' : [],
'Video' : [],
'Development': [],
'Education' : [],
'Game' : [],
'Graphics' : [],
... | dbondin/progs | icemenu/icemenu.py | icemenu.py | py | 2,782 | python | en | code | 1 | github-code | 90 |
10224904945 | import unittest
from SpatialDatasetGen.SpatialQueryGen import SpatialQueryGen
import Enums, Obj
from Settings import Settings
from SpatialDatasetGen import SpatialDatasetGen
from SpatialDatasetGen.SpatialRelationship import Relationship
class TestSpatialQueryGen(unittest.TestCase):
def test_gen_captions_1(self):
... | kengjichow/TraVLR | DatasetGen/Tests/test_SpatialQueryGen.py | test_SpatialQueryGen.py | py | 2,189 | python | en | code | 0 | github-code | 90 |
31393838427 | import uuid
from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils import timezone
from .managers import CustomUserManager
# Create your models here.
class User(AbstractBaseUser, PermissionsMixin):
# These... | Firuz-JuraevML/restaurante | restaurante/restaurant/models.py | models.py | py | 2,689 | python | en | code | 0 | github-code | 90 |
74099234218 | import random
array = list(range(10))
random.shuffle(array)
def quicksort(array, first, last):
if first >= last:
return
i, j = first, last
pivot = array[random.randint(first, last)]
while i <= j:
while array[i] < pivot:
i += 1
while array[j] > pivot:
... | danny-hunt/Problems | quicksort_implementation.py | quicksort_implementation.py | py | 572 | python | en | code | 2 | github-code | 90 |
19711515520 | from django.shortcuts import render, HttpResponse
from .models import Docker
# Create your views here.
def index(request):
containerList = Docker.getContainerList()
context = {'containerList' : containerList}
return render(request, 'dockerAPI/index.html', context)
def images(request):
imageList = Docker.getImageL... | nodueck/DockerGUI | dockerAPI/views.py | views.py | py | 715 | python | en | code | 1 | github-code | 90 |
5909501960 | source(findFile("scripts", "dawn_global_startup.py"))
source(findFile("scripts", "dawn_global_plot_tests.py"))
source(findFile("scripts", "dawn_constants.py"))
def main():
#Start using clean workspace
startOrAttachToDAWN()
# Open data browsing perspective
openPerspective("Data Browsing")
... | DawnScience/dawn-test | org.dawnsci.squishtests/suite_tools1d_history/tst_history_and_peakfitting/test.py | test.py | py | 3,522 | python | en | code | 3 | github-code | 90 |
18096173209 | def __main():
mountains = []
numOfMoun = 10
for c in range(numOfMoun):
mountains.insert(c,int(input()))
sorted_mounts = sorted(mountains,reverse=True)
for k in range(3):
print(sorted_mounts[k])
__main()
| Aasthaengg/IBMdataset | Python_codes/p00001/s569701431.py | s569701431.py | py | 253 | python | en | code | 0 | github-code | 90 |
19221136508 |
import telebot
import config
import dbworker
bot = telebot.TeleBot(config.token)
# Начало диалога
@bot.message_handler(commands=['start'])
def cmd_start(message):
bot.send_message(message.chat.id, "Привет! Как я могу к тебе обращаться?")
dbworker.set_state(message.chat.id, config.States.S_ENTER_NAME.value)... | Twishar/Bots | dialog_bot/bot.py | bot.py | py | 2,561 | python | ru | code | 0 | github-code | 90 |
6101320635 | import copy
import logging
import sqlite3
from typing import Optional
from lxml import etree # type: ignore
from prodtools.utils import fs_utils
from prodtools.utils import xml_utils
from prodtools.db.pid_versions import PIDVersionsManager
from . import scielo_id_gen
LOGGER = logging.getLogger(__name__)
def add_... | scieloorg/PC-Programs | src/scielo/bin/xml/prodtools/data/kernel_document.py | kernel_document.py | py | 4,758 | python | en | code | 7 | github-code | 90 |
18483971679 | import sys
stdin = sys.stdin
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()
import itertools
n = ni()
k = -1
for i in range(1,10**7):
if i*(i-1)//2 > n:
break
elif i*(i-1)//2 == n:
... | Aasthaengg/IBMdataset | Python_codes/p03230/s096415732.py | s096415732.py | py | 628 | python | en | code | 0 | github-code | 90 |
20474286388 | from core.bst import BinarySearchTree
from pages.home import home
from pages.manage import ManagePages
from pages.transactions import TransactionPages
def main():
state = 0
database = BinarySearchTree()
manage = ManagePages(database)
transaction = TransactionPages(database)
while state != -1:
... | rizqulloh/sitorsi | main.py | main.py | py | 557 | python | en | code | 0 | github-code | 90 |
23424468568 | import argparse
import os
# args.
parser = argparse.ArgumentParser()
parser.add_argument('--device', type=int, default=0)
parser.add_argument('--scene_id', type=int, default=1)
parser.add_argument('--sequence_id', type=int, default=2)
parser.add_argument('--data_folder_mask', default='/opt/dataset/scene{:02d}/seq{:0... | siyandong/NeuralRouting | run_ransac_icp.py | run_ransac_icp.py | py | 2,237 | python | en | code | 67 | github-code | 90 |
17679314510 | from django.urls import path
from . import views
app_name = "courses"
urlpatterns = [
path("", views.CourseListView.as_view(), name='list'),
path("courses/<int:pk>/", views.CourseDetailView.as_view(), name="detail"),
# path("courses/<int:course_pk>/<int:step_pk>/", views.step_detail, name='step'),
pat... | jeremy886/DjangoBasics | courses/urls.py | urls.py | py | 411 | python | en | code | 0 | github-code | 90 |
18173922279 | #!/usr/bin/env python3
def main():
n = int(input())
s = input()
# print("s: " + s)
# 左に白が存在する赤
# 右に赤が存在する白 <=> これらは交換しても良い
# minimumな個数を交換すればいいはず
# 塗り替えは実はする必要はない
w = 0
r = 0
for i in range(len(s)):
if s[i] == 'R':
r += 1
# print(len(s))
# print(str(... | Aasthaengg/IBMdataset | Python_codes/p02597/s926918694.py | s926918694.py | py | 698 | python | ja | code | 0 | github-code | 90 |
19552331928 | # Copyright (c) 한승은. All rights reserved.
import cv2
import os
import numpy as np
image1_dir = "D:/Dataset/CelebAMask-HQ/CelebA-HQ_256/test/images/00256.jpg"
image2_dir = "C:/Users/USER/Downloads/MAT-main/MAT-main/CelebMaskRendering_256_results/00256_kf94.png"
image1 = cv2.imread(image1_dir, cv2.IMREAD_COLO... | Seungeun-Han/Calculate_Similarity | calculate_similarity.py | calculate_similarity.py | py | 1,154 | python | ko | code | 0 | github-code | 90 |
1025500377 | from flask import request, Flask, render_template
from baidu_cloud import baidu_cloud_main
from xun_lei import xun_lei_main
from youku import youku_main
import json
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
@app.route('/baidu_cloud', methods... | seraph98/super_share | web/index.py | index.py | py | 1,134 | python | en | code | 4 | github-code | 90 |
33581357111 | import tensorflow as tf
from tensorflow import Tensor
from typing import Tuple
def horizontal_flip(image: Tensor, mask: Tensor, probability: float = 0.5) -> Tuple[Tensor, Tensor]:
"""
Apply horizontal flip data augmentation to an input image and its corresponding mask.
Args:
image (Tensor): The ... | amirhosein-ziaei/Semantic_Segmentation_U-Net | data_augmentation/Geometric_Augmentations.py | Geometric_Augmentations.py | py | 6,556 | python | en | code | 1 | github-code | 90 |
43883919999 | import requests
import json
import configparser
from retry import retry
def sendAlert(msg):
url = "https://cqgame.info/API/IMService.ashx"
headers = {
"Content-type": "application/x-www-form-urlencoded",
}
data = {
"ask": "sendChatMessage",
"account": "sysbot",
"api_ke... | dejavu92427/django-vue | django/purgeCdnCache/leacloudNsPurgeCache.py | leacloudNsPurgeCache.py | py | 3,166 | python | en | code | 0 | github-code | 90 |
16364079518 | #!/usr/bin/env python
# Implement DNS inclusion proof checking, see [TBD].
#
# Unfortunately, getting at the SCTs in general is hard in Python, so this
# does not start with an SSL connection, but instead fetches a log entry by
# index and then verifies the proof over DNS.
# You will need to install DNSPython (http:/... | google/certificate-transparency | python/utilities/dnslookup/dnslookup.py | dnslookup.py | py | 3,851 | python | en | code | 862 | github-code | 90 |
28769108590 | import copy
import json
import os
import convlab
from convlab.modules.dst.multiwoz.dst_util import init_state
from convlab.modules.dst.multiwoz.dst_util import normalize_value
from convlab.modules.dst.state_tracker import Tracker
from convlab.modules.util.multiwoz.multiwoz_slot_trans import REF_SYS_DA
class RuleDST(... | ConvLab/ConvLab | convlab/modules/dst/multiwoz/rule_dst.py | rule_dst.py | py | 3,610 | python | en | code | 398 | github-code | 90 |
18438300859 | # ABC120D
import sys
input=sys.stdin.readline
class UnionFind:
def __init__(self, n):
self.p=[-1]*n
self.size=[1]*n
def root(self, x):
st=set()
while self.p[x]>=0:
st.add(x)
x=self.p[x]
for y in st:
self.p[y]=x
return... | Aasthaengg/IBMdataset | Python_codes/p03108/s578884639.py | s578884639.py | py | 1,315 | python | en | code | 0 | github-code | 90 |
29134015080 | import yt_dlp as ydl
opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'outtmpl': '%(title)s.%(ext)s',
}
url = 'https://www.youtube.com/watch?v=V_fYfdXpkx4&list=PLjZkFWu3rWSE2cZ8L2CbiRM... | cleverice007/Chatgpt_Summarizer | download.py | download.py | py | 441 | python | en | code | 0 | github-code | 90 |
28483476397 | import pygame
from pygame.locals import *
import sys
from constantes import *
from gui_form import *
import warnings
from sql import *
warnings.filterwarnings("ignore")
flags = DOUBLEBUF
screen = pygame.display.set_mode((ANCHO_VENTANA,ALTO_VENTANA), flags, 16)
pygame.init()
create_table()
rank_in... | NahuelBarneto3/REPO_PROG1 | mainPpal.py | mainPpal.py | py | 5,072 | python | en | code | 0 | github-code | 90 |
25527341248 | import json
import os
from collections import namedtuple
from subprocess import Popen, PIPE, STDOUT
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.style.use('science')
plt.rcParams.update({
"font.family": "serif",
"font.serif" : ["Times"],
'figure.titlesize' : "Large",
... | EduNetArchive/Finenko_PES-Fitting-MSA | external/svc-plotter/plotter.py | plotter.py | py | 5,330 | python | en | code | null | github-code | 90 |
16465734533 | class Invoice(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
class InvoiceEmail(object):
def __init__(self, subject, text, emails_to, emails_cc, emails_bcc):
self.subject = subject
self.text = text
self.emails_to = InvoiceEmail.to_email_list(emails_to)
... | sommalia/moco-wrapper | moco_wrapper/models/objector_models/invoice.py | invoice.py | py | 855 | python | en | code | 2 | github-code | 90 |
32593051188 | # %%
import pandas as pd
import numpy as np
import glob as gb
import re
# 最大表示行数を設定
pd.set_option('display.max_rows', 1000)
# 最大表示列数の指定
pd.set_option('display.max_columns', 1000)
# %%
flowers_labels = [re.split('[\\\.]',path)[-1] for path in gb.glob('D:/OpenData/flowers/raw/*')]
flowers_labels
# %%
f... | furu8/blogress | 2021-11/scripts/blog.py | blog.py | py | 1,395 | python | en | code | 0 | github-code | 90 |
18182554489 | from collections import defaultdict
m = defaultdict(int)
n = int(input())
for _ in range(n):
m[input()] += 1
for k in ["AC", "WA", "TLE", "RE"]:
print(f"{k} x {m[k]}") | Aasthaengg/IBMdataset | Python_codes/p02613/s623977845.py | s623977845.py | py | 175 | python | en | code | 0 | github-code | 90 |
599189256 | def recur_fib(n):
if n <= 1:
return n
else:
return recur_fib(n-1) + recur_fib(n-2)
nterm = int(input("Enter the input integer value :"))
if nterm <= 0:
print("Please enter the positive integer")
else:
print("Fibonacci sequence:", end=" ")
for i in range(nterm):
print(recur_... | Nakulan89/Automation_practice | Topics/Fibonacci_recursive.py | Fibonacci_recursive.py | py | 337 | python | en | code | 0 | github-code | 90 |
10757102542 | import abc
from collections import deque
import numpy as np
import random
class QLearningAgent:
def __init__(self, state_size, action_size, gamma=0.95, epsilon=1.0, epsilon_decay=0.995, epsilon_min=0.1, batch_size=32):
self.state_size = state_size
self.action_size = action_size
# hyperpar... | Rowing0914/OpenAI_ROS_dev | openai_examples_projects/cartpole_openai_ros_examples/scripts/q_learning_agent.py | q_learning_agent.py | py | 1,979 | python | en | code | 5 | github-code | 90 |
26889204708 | class HackerLanguage:
def __init__(self):
self.text = ''
def delete(self, n):
self.text = self.text[:-n]
def write(self, msg):
self.text += msg
def send(self):
def encrypt(to_encrypt):
to_encrypt = bin(ord(to_encrypt))
return to_encrypt[2:]
... | Naethaniel/learn-python | checkIO/scientific_expedition/hacker_language.py | hacker_language.py | py | 1,880 | python | en | code | 0 | github-code | 90 |
12751280398 | """This module is used for computing social and map features for motion forecasting baselines.
Example usage:
$ python compute_features.py --data_dir ~/val/data
--feature_dir ~/val/features --mode val
"""
import os
import shutil
import tempfile
import time
from typing import Any, Dict, List, Tuple
impor... | mithunnj/Capstone-Feature-LSTM | compute_features.py | compute_features.py | py | 12,468 | python | en | code | 1 | github-code | 90 |
7911217041 | import string
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
def remove_punct(tranascript):
"""
Remove punctuations from a given transcript
input : sentence string.
output : processed string.
"""
puct_to_remove = string.punctuation.replace(".", "")
puct_to... | avinash-chaluvadi-dev/pratilipi-ana | soa-nlp/app/ml/text_normalization/preprocess.py | preprocess.py | py | 1,415 | python | en | code | 0 | github-code | 90 |
14227579148 | #
# Imports
#
import os
from turtle import Turtle, Screen
from paddle import Paddle
#
# Classes
#
#
# Global variables
#
#
# Private functions
#
# clear_console
def clear_console():
"""
Clears console.
"""
command = "clear"
if os.name in ("nt", "dos"): # If Machine is r... | fjpolo/Udemy100DaysOfCodeTheCompletePyhtonProBootcamp | Day022/main002.py | main002.py | py | 1,157 | python | en | code | 8 | github-code | 90 |
27057012440 | # encoding: utf-8
import tensorflow as tf
import inference
import math
import eval
import os
import numpy as np
# 配置神经网络参数
BATCH_SIZE = 32 # batch大小
# LEARNING_RATE_BASE = 0.8 #最开始的学习率
# LEARNING_RATE_DECAY = 0.99 #学习率削减率
LEARNING_RATE = 1e-6
# REGULARIZATION_RATE = 0.0001 #正则化的lambda
EPOCH = 30000 # 总的训练轮数
DEV_RAT... | Vivienfanghua/nlp | train.py | train.py | py | 3,894 | python | en | code | 0 | github-code | 90 |
40058142739 | import sys
import ssl
import urllib.request
#利用浏览器,播放视频,查看network,捕获到请求,保留requests-headers
"""
GET /upgcxcode/98/96/38759698/38759698-1-64.flv?e=ig8euxZM2rNcNbNMhWKVhoMMnwN3hwdEto8g5X10ugNcXBlqNxHxNEVE5XREto8KqJZHUa6m5J0SqE85tZvEuENvNC8xNEVE9EKE9IMvXBvE2ENvNCImNEVEK9GVqJIwqa80WXIekXRE9IB5QK==&deadline=1526313999&dynam... | soloBike/bilibiliDownload | downloadFlv.py | downloadFlv.py | py | 2,682 | python | en | code | 0 | github-code | 90 |
73225295658 | """
URL configuration for dream11 project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home... | Seelammahesh/parimatch | dream11/urls.py | urls.py | py | 1,800 | python | en | code | 0 | github-code | 90 |
71847081896 | import string
import sys
from functools import cache
from itertools import count
moves = None
@cache
def dance(programs):
programs = list(programs)
for move in moves:
if "s" in move:
x = int(move[1:])
programs = programs[-x:] + programs[:-x]
pass
if "x" in ... | alfredgamulo/advent_of_code | 2017/16/main.py | main.py | py | 1,166 | python | en | code | 2 | github-code | 90 |
21775466355 | from prsaw import RandomStuffV2
# initiate the object
rs = RandomStuffV2()
while True:
input_user=input("> ")
response =rs.get_ai_response(input_user)
print(response)
# close the object once done (recommended)
rs.close() | Dharmendra-ojha/Chatbot-projects | ai friend v1.0.py | ai friend v1.0.py | py | 251 | python | en | code | 1 | github-code | 90 |
9726308151 | import sys
sys.path.append('.')
import os
import random
import torch
import torch.utils.data as data
import numpy as np
import open3d as o3d
class ShapeNet(data.Dataset):
"""
ShapeNet dataset in "PCN: Point Completion Network". It contains 28974 training
samples while each complete samples corresponds t... | qinglew/PCN-PyTorch | dataset/shapenet.py | shapenet.py | py | 3,669 | python | en | code | 113 | github-code | 90 |
36118715906 | from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
i = 0
with PiCamera() as camera:
camera.resolution = (480,360)
camera.framerate = 15
stream = PiRGBArray(camera)
ts = time.time()
for frame in camera.capture_continuous(stream, format='bgr', use_video_port=Tr... | mtfitz/cv-chessboard | monitor_picamera.py | monitor_picamera.py | py | 612 | python | en | code | 0 | github-code | 90 |
9215977338 | import os
from datetime import datetime
import time
import math
from linenotipy import Line
line = Line(token='4nQRXaFFmESdQTv1dU0ItnPSpwuQBmggtDGsVg3ZbVe') #G5UrvYGMVkFuRpDad7YXALaxMwlxwpqIlAcugAuWDpP
datetime1 = datetime.now().second
datetime2 = datetime.now().second
print("========[ Check_responding ]========")
... | rimand/PythonCheckResponding | PythonCheckResponding/Check_responding.py | Check_responding.py | py | 1,885 | python | en | code | 0 | github-code | 90 |
18375069719 | n = int(input())
p = list(map(int,input().split()))
ans = int()
for num in range(1,len(p)-1):
p1 = p[num - 1]
p2 = p[num]
p3 = p[num + 1]
p_list = [p1,p2,p3]
p_list.sort()
if p_list[1] == p2:
ans += 1
print(ans) | Aasthaengg/IBMdataset | Python_codes/p02988/s187649599.py | s187649599.py | py | 249 | python | en | code | 0 | github-code | 90 |
73820338537 | class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
if not word1:
return len(word2)
if not word2:
return len(word1)
row_size = len(word1) + 1
col_si... | HarrrrryLi/LeetCode | 72. Edit Distance/Python 2/solution.py | solution.py | py | 1,022 | python | en | code | 0 | github-code | 90 |
18319478100 | #!/usr/bin/env python
# coding: utf-8
# ## Taking filename as input and reading data from it
# ## Importing necessary tools
import nltk
# nltk.download('movie_reviews')
from textblob import TextBlob as tb
from textblob.sentiments import NaiveBayesAnalyzer
import plotly.express as px
import plotly
import pandas as pd
... | anuran-roy/OpnEco | OpnEmo/scripts/emocheck.py | emocheck.py | py | 5,388 | python | en | code | 20 | github-code | 90 |
10657744779 | #!/usr/bin/python3
"""
function that determines the fewest number of coins to make change
"""
def makeChange(coins, total):
"""
parameters:
coins : list of available coins
total : total value to return
returns:
least amount of coins possible
"""
if total <= 0:... | sevensquad7/holbertonschool-interview | 0x19-making_change/0-making_change.py | 0-making_change.py | py | 780 | python | en | code | 0 | github-code | 90 |
19419674574 | import bpy
class MyPanel(bpy.types.Panel):
bl_idname = "OBJECT_PT_my_panel"
bl_label = "My Panel"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "Connect Animation"
def draw(self, context):
layout = self.layout
row = layout.row()
row.label(text="First Ar... | CamiloFajardo200/BKP | main.py | main.py | py | 6,473 | python | en | code | 0 | github-code | 90 |
18106524329 | def selectionSort(A, N):
global cnt
for i in range(N):
minj = i
for j in range(i, N):
if A[j] < A[minj]:
minj = j
if i != minj:
tmp = A[i]
A[i] = A[minj]
A[minj] = tmp
cnt = cnt + 1 #
return A
if __name__ == '__main__':
n = int(input())
R = list(map(int, input().split()))
cnt = 0
R = ... | Aasthaengg/IBMdataset | Python_codes/p02260/s399167655.py | s399167655.py | py | 381 | python | en | code | 0 | github-code | 90 |
34871204040 | import datetime
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestConvertDtypes:
@pytest.mark.parametrize(
"convert_integer, expected", [(False, np.dtype("int32")), (True, "Int32")]
)
def test_convert_dtypes(self, convert_integer, expected, string_storag... | pandas-dev/pandas | pandas/tests/frame/methods/test_convert_dtypes.py | test_convert_dtypes.py | py | 7,565 | python | en | code | 40,398 | github-code | 90 |
8473397526 | a, b, c = map(int, input().split())
count = 1
sub = a - b
final = c - a
t = 0
if b < a and a == c: # b가 a보다 크고 a와 c가 같을때
print(count)
elif final // sub == 0: # 한번에 올라갈 경우?
count += 1
print(count)
else:
t = int(round((final / sub), 0)) # final 에서 올라갔다 내려갔다 횟수
if (t < (final / sub)): # 만약 t보다 크면 증가.
... | ji-hun-choi/Baekjoon | 07.기본_수학1/02869.py | 02869.py | py | 444 | python | ko | code | 1 | github-code | 90 |
24451540228 | from cloudbot import hook
import textwrap
import re
from bs4 import BeautifulSoup
import urllib
import urllib.request
headers = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)',
'Referer': 'http://www.thereeftank.com/forums/'}
n... | CrushAndRun/Cloudbot-Fluke | plugins/qdb.py | qdb.py | py | 2,027 | python | en | code | 0 | github-code | 90 |
18469590939 | N = int(input())
even = 0
A = []
for i in range(N):
a = int(input())
if not a%2:
even += 1
A.append(a)
if N == 1:
print("sfeicrosntd"[(A[0]%2)::2])
elif sum(A) == N:
print("first")
else:
if even == N:
print("second")
else:
print("first") | Aasthaengg/IBMdataset | Python_codes/p03197/s358119565.py | s358119565.py | py | 291 | python | en | code | 0 | github-code | 90 |
73778355176 | import os
import csv
import statistics
months = 0
net_total = 0
PL_change = []
average_change = 0
maxdate = []
mindate = []
previousmonth = 0
date = []
budget_csv = os.path.join('Pybank', 'Resources', 'budget_data.csv')
budget_csv_output = os.path.join('PyBank', 'Analysis', 'budget_output.txt')
with open(budget_csv) ... | stjohnson14/Financial-Data-Analysis-with-Python | PyBank/Pybank_code.py | Pybank_code.py | py | 1,732 | python | en | code | 0 | github-code | 90 |
19998393261 | from flask import Flask,jsonify,request,Response
import json
from settings import *
from BookModel import *
import jwt, datetime
app.config['SECRET_KEY'] = 'meow'
@app.route('/login')
def get_token():
exp_date = datetime.datetime.utcnow() + datetime.timedelta(seconds=100)
token = jwt.encode({'exp':exp_date},app... | dkarthi/book_app | app.py | app.py | py | 2,192 | python | en | code | 0 | github-code | 90 |
10302105337 | import json
from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404
from django.views.decorators.http import require_POST
from .common.decorators import ajax_required
from .models import Music, MusicViewsHit, PlayList
from Singer.models import Singer
from Album.models import Album
fr... | amir77daliri/MahMusic | Music/views.py | views.py | py | 3,721 | python | en | code | 0 | github-code | 90 |
14331007110 | #!/usr/bin/env python
from distutils.core import setup, Extension
zformod = Extension('zfor',
sources = ['src/zfor.c'], library_dirs = ['/usr/local/lib'], libraries = ['zfor']
)
setup(name = 'zfor',
version = '0.1',
description = 'Python zfor binding',
... | chaoslawful/zfor | priv/client/python_zfor/setup.py | setup.py | py | 523 | python | en | code | 51 | github-code | 90 |
17419406792 | import math
import cv2
import lekaloConture
import lecaloUtils
import lekaloDraw
import numpy as np
import arucoSize
import lekaloSvg
import lekaloFilter
def saveToSvg(img, nameSvg):
findCtr, imgUpd, cnt, imgConture, imgFiltered ,_ ,_ = doFrame(img, False, 200, 1, 0.2, 8)
if findCtr == True:
lekaloSvg.... | andkir1024/converter | lekaloMain.py | lekaloMain.py | py | 6,314 | python | ru | code | 0 | github-code | 90 |
2110178397 | from django.urls import path
from .views import index, create, delete, update
urlpatterns = [
path('', index, name='index'),
path('create/', create, name='create'),
path('delete/<int:pk>', delete, name='delete'),
path('update/<int:pk>', update, name='update'),
] | MiniJez/TP_Django | Frameworks/urls.py | urls.py | py | 280 | python | en | code | 0 | github-code | 90 |
24552450197 | import inspect
import functools
from .eudtypedfuncn import EUDTypedFuncN, applyTypes
from ... import utils as ut
def EUDTypedFunc(argtypes, rettypes=None, *, traced=False):
def _EUDTypedFunc(fdecl_func):
argspec = inspect.getargspec(fdecl_func)
argn = len(argspec[0])
ut.ep_assert(
... | phu54321/eudplib | eudplib/core/eudfunc/eudf.py | eudf.py | py | 1,253 | python | en | code | 13 | github-code | 90 |
73225958377 | import numpy as np
import tflearn.datasets.oxflower17 as oxflower17
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from keras.callbacks import TensorBoard
def fit_alexnet(epochs=1, verbose=1):
X,... | ilyarudyak/cs230-deep-learning | dltf-krohn/convolutional_nn/alexnet_oxford_flowers.py | alexnet_oxford_flowers.py | py | 1,736 | python | en | code | 2 | github-code | 90 |
18463258679 | def solve():
Ss = input().rstrip()
Ts = input().rstrip()
lenS, lenT = len(Ss), len(Ts)
dp = [[0]*(lenT+1) for _ in range(lenS+1)]
for iS, S in enumerate(Ss, start=1):
dp0 = dp[iS-1]
dpi = dp[iS]
for jT, T in enumerate(Ts, start=1):
if S == T:
dpi... | Aasthaengg/IBMdataset | Python_codes/p03165/s532620308.py | s532620308.py | py | 799 | python | en | code | 0 | github-code | 90 |
22555934818 | f = open("input.txt", "r")
line = ""
for x in f:
line = line + " " + x.strip()
parts = line.strip().split()
s = 0
for i in parts:
s = s + int(i)
print(s) | Beisenbek/PP2Summer2020 | week 2/day 3/N/input_variants.py | input_variants.py | py | 163 | python | en | code | 0 | github-code | 90 |
13581129262 | from django.conf.urls import url
from biogps.ext_plugins import views
urlpatterns = [
url(r'^geneviewer/$',
views.grGeneViewer,
name='grGeneViewer'),
url(r'^description/$',
views.grDescription,
name='grDescription'),
url(r'^function/$',
views.grFunction,
n... | SuLab/biogps_core | src/biogps/biogps/ext_plugins/urls.py | urls.py | py | 539 | python | en | code | 0 | github-code | 90 |
9109012251 | import ast
import os
from pathlib import Path
import shutil
from pandas import DataFrame
from py2neo import Graph
#
# DIRECTORY = 'autobots/tests/scenario'
# ENTITIES = ['asset', 'dataimport', 'issue', 'portfolio', 'project', 'resource', 'rollups',
# 'schedule', 'task',
# 'timeadmin', 'timesheet... | git4rajesh/python-learnings | AST_GraphDB/study/testcase_graph.py | testcase_graph.py | py | 12,485 | python | en | code | 0 | github-code | 90 |
4239237928 | #
# @lc app=leetcode id=382 lang=python3
#
# [382] Linked List Random Node
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
import numpy as np
class Solution:
def __init__(self, head: Optiona... | wangyerdfz/python_lc | 382.linked-list-random-node.py | 382.linked-list-random-node.py | py | 875 | python | en | code | 0 | github-code | 90 |
7079859246 | from enum import Enum
from db import commit_transaction
from cabin.cabin_repository import CabinNotFoundError
class ReviewService:
def __init__(self, review_repository, cabin_repository):
self._review_repository = review_repository
self._cabin_repository = cabin_repository
def add_review(self... | mjjs/tsoha-2021-cabin-browser | cabin-browser/review/review_service.py | review_service.py | py | 1,035 | python | en | code | 0 | github-code | 90 |
28381756581 | from odoo import api, fields, models
from odoo.exceptions import UserError
#
from bs4 import BeautifulSoup
class ProjectTask(models.Model):
_inherit = 'project.task'
@api.model
def change_image_size(self, html, new_size):
soup = BeautifulSoup(html, 'html.parser')
new_width = "width: " + st... | SyentysDevCenter/Fprs_old | project_extend/models/project_task.py | project_task.py | py | 2,231 | python | en | code | 0 | github-code | 90 |
27308734491 | import ast
from collections import OrderedDict
from copy import copy
import numpy
from gold.statistic.MagicStatFactory import MagicStatFactory
from gold.statistic.Statistic import Statistic
from gold.util.CommonFunctions import isIter
from quick.util.CommonFunctions import silenceRWarnings
class ClusterMatrixStat(M... | uio-bmi/track_rand | lib/hb/quick/statistic/ClusterMatrixStat.py | ClusterMatrixStat.py | py | 12,019 | python | en | code | 1 | github-code | 90 |
23250944806 | from setuptools import setup, find_packages
import sys, os
version = '0.1'
setup(
name='ckanext-datanl',
version=version,
description="Example themeb for customising CKAN",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author=... | okfn/ckanext-datanl | setup.py | setup.py | py | 801 | python | en | code | 0 | github-code | 90 |
325392909 | n=int(input())
a=list(map(int, input().split()))
count=0
if 1 in a:
a.remove(1)
for i in a:
for j in range(2,i):
if i==2:
count+=1
if i%j==0:
break
else:
count+=1
print(count)
| dufwn1234/Python-Algorithm | Mathematics/beakjoon-1316.py | beakjoon-1316.py | py | 257 | python | en | code | 0 | github-code | 90 |
107707272 | #Random lib for selecting random cards
import random
def check(a):
"""To check if user has ace card i.e '11' and sum is greater than 21
then consider value of ace as '1' """
for i in a:
if i==11 and sum(a)>21:
a[a.index(11)]=1
return a
def checkcom(a,deck):
"""TO check is computer ... | Nilesh-Thote/Blackjack_game | Blackjack.py | Blackjack.py | py | 2,676 | python | en | code | 1 | github-code | 90 |
37817873241 | from tracemalloc import start
import requests
from datetime import datetime
import json
import os
from dotenv import load_dotenv
load_dotenv()
import urllib
def get_commute_time(starting_location, ending_location):
MAPBOX_API_KEY = os.getenv('MAPBOX_API_KEY')
# geocode your start and end points
# star... | cole-seph/home-search | get_commute_mapbox.py | get_commute_mapbox.py | py | 2,545 | python | en | code | 0 | github-code | 90 |
70760762856 | import datetime
import requests
current_datetime = datetime.datetime.now()
print("Current date and time:", current_datetime)
apiKey = "your_api_key"
mintuesDisconnectFor = 10
url = "https://console.automox.com/api/servers"
headers = {"Authorization": "Bearer " + apiKey}
response = requests.get(url, headers=headers)... | adamwhitman/python | removeDupOfflineDevices.py | removeDupOfflineDevices.py | py | 1,827 | python | en | code | 0 | github-code | 90 |
42592192757 | import glob
import json
import os
import pandas as pd
ANALYSIS_ID = "179f9bb9-dd28-4d2c-84f7-5bdfd8f4d421"
DOWNLOAD_NAME = "dc_medium_office_v3"
base_dir = os.path.join(os.path.dirname(__file__), "simulations", DOWNLOAD_NAME)
json_variable_file = os.path.join(base_dir, 'selected_json_variables.json')
if not os.path.... | nllong/dc-metamodeling | bem/process_data.py | process_data.py | py | 3,527 | python | en | code | 2 | github-code | 90 |
14316341230 | from django.apps import apps
from django.db.models import Q
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.response import Response
from rest_framework.perm... | Chaoslecion123/Diver | saleor/rest/views/product/product.py | product.py | py | 11,292 | python | en | code | 0 | github-code | 90 |
17352374602 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 22 19:55:10 2022
@author: ROG
"""
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
tempcount = 0
total= 0
for i in nums:
if i == 1:
tempcount = tempcount +1
if total... | ZyadHassan096/LEETCODE | MaxConsecutiveOnes.py | MaxConsecutiveOnes.py | py | 586 | python | en | code | 0 | github-code | 90 |
29017917445 | # data path and log path
TRAIN_DATA_PATH = '../data/imgs'
TEST_DATA_PATH = '../data/test'
TEST_GENERATOR_TRUTH = '../data/generator'
INFERENCES_SAVE_PATH = '../imgs'
TRAIN_SUMMARY_PATH = '../summary'
CHECKPOINTS_PATH = '../checkpoints'
reconstruction_loss_weight = 40
# 避免出现 log(0)
EPS = 1e-12
BATCH_SIZE =... | zxyjfj/SRGAN_AE | src/configs.py | configs.py | py | 803 | python | en | code | 0 | github-code | 90 |
20303468771 | '''Download audio and/or video from youtube'''
import sys
from workflow import Workflow
def main(wf):
'''Main function. This is where the magic happens'''
options = ['Audio', 'Video', 'Both']
# Loop through the returned posts and add an item for each to
# the list of results for Alfred
for option... | kyrelldixon/Alfred-Youtube-Workflow | youtube.py | youtube.py | py | 571 | python | en | code | 0 | github-code | 90 |
34998876979 | """
Type descriptions of Twitterverse and Query dictionaries
(for use in docstrings)
Twitterverse dictionary: dict of {str: dict of {str: object}}
- each key is a username (a str)
- each value is a dict of {str: object} with items as follows:
- key "name", value represents a user's name (a str)
... | chenjie/twitter-like-data-query | twitterverse_functions.py | twitterverse_functions.py | py | 16,402 | python | en | code | 0 | github-code | 90 |
69926836138 | import json
from flask_cors import CORS
from flask import Flask, jsonify
from flask import request
import Classification.SpaCyClassifier as classification
import Classification.sub_event_classifier.sub_event_classifier as sub_classifier
import LocationExtraction.LocationExtracter as locationExtractor
import DataPrepara... | AnujDutt2701/EventSummarizer | SampleFlask.py | SampleFlask.py | py | 5,952 | python | en | code | 0 | github-code | 90 |
9309137488 | #-*- coding:utf-8 -*-
# @author: qianli
# @file: thirdMax.py
# @time: 2019/09/17
def thirdMax(nums):
nums = list(set(nums))
min1, min2, min3 = float('-inf'), float('-inf'), float('-inf')
for i in range(len(nums)):
if nums[i] > min1:
min1, min2, min3 = nums[i], min1, min2
elif num... | RanranYang1110/LEETCODE11 | thirdMax.py | thirdMax.py | py | 518 | python | en | code | 0 | github-code | 90 |
4129803422 | import sys
import numpy as np
p = (2**np.arange(9))[::-1]
def apply_lut(lut, img):
v = np.lib.stride_tricks.sliding_window_view(np.pad(img, [2, 2]), [3, 3])
return lut[(np.reshape(v, (v.shape[0], v.shape[1], -1)) * p).sum(axis=2)]
lut = np.array([x == '#' for x in sys.stdin.readline().strip()], dtype=int)
sys.... | folded/aoc-2021 | 20/20.py | 20.py | py | 575 | python | en | code | 0 | github-code | 90 |
28292696218 | import numpy as np
import tsplib95
import random
import copy
from TSP_homochain import *
### DATA ###
problem = tsplib95.load('TSP-Configurations/a280.tsp.txt')
cities = list(problem.node_coords.values())
### FUNCTIONS FOR ACCEPTANCE RATE TESTING ###
def init_temp_scanner(route_0, cities, temp_range, MCLen=500, c... | lendobo/Stochastic_Simulation_3 | param_search.py | param_search.py | py | 9,404 | python | en | code | 0 | github-code | 90 |
4958390591 | '''
There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays.
Have you met this question in a real interview?
Clarification
The definition of the median:
The median here is equivalent to the median in the mathematical definition.
The median is the middl... | boxu0001/practice | py3/S4_medianTwoSortedArray.py | S4_medianTwoSortedArray.py | py | 2,518 | python | en | code | 0 | github-code | 90 |
22017230109 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.patches import Circle
# get data
data = np.genfromtxt("../build/bin/example_ppo.csv", delimiter=",")
def animate():
# plot everything
#epochs = np.array([1,5,10])
epochs = np.array([1])
for e ... | mhubii/nmpc_pattern_generator | plot/plot_ppo.py | plot_ppo.py | py | 4,483 | python | en | code | 2 | github-code | 90 |
18106088549 | #coding: UTF-8
import sys
import math
class Algo:
@staticmethod
def bubbleSort(r, n):
flag = 1
count = 0
while flag:
flag = 0
for j in range(n-1, 0, -1):
if r[j] < r[j-1]:
r[j], r[j-1] = r[j-1], r[j]
count += 1
flag = 1
for i in range(0, n):
... | Aasthaengg/IBMdataset | Python_codes/p02259/s858986861.py | s858986861.py | py | 498 | python | en | code | 0 | github-code | 90 |
74500114217 | from tkinter import ttk, Tk, END, EW
from frames.fr_decimal import Fr_decimal
from frames.fr_binario import Fr_binario
from frames.fr_octal import Fr_octal
from frames.fr_hexadecimal import Fr_hexadecimal
from frames.fr_duodecimal import Fr_duodecimal
class App(Tk):
def __init__(self):
super().__init__()
... | jonasht/python | 19-conversorNumerico/0.oldVersionWithForestTheme/main.py | main.py | py | 3,472 | python | pt | code | 0 | github-code | 90 |
399634142 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# metadataic\test\test_data_transform.py
import subprocess
import shlex
import socket
import unittest
from unittest.mock import patch
import elasticsearch
from pyspark import SparkConf, SparkContext
import data_transform
import index_settings
import conf
class DataTransfo... | kalgumaei/europeana-mdic | src/test/test_data_transform.py | test_data_transform.py | py | 24,349 | python | en | code | 1 | github-code | 90 |
25210093411 | numeros = [5, 2, 9, 1, 7]
numeros.sort()
print(numeros) # Resultado: [1, 2, 5, 7, 9]
numeros.sort(reverse=True)
print(numeros) # Resultado:[9, 7, 5, 2, 1]
muebles = ["mesa", "silla", "lámpara", "estantería"]
muebles.sort()
print(muebles) # Resultado: ['estantería', 'lámpara', 'mesa', 'silla']
muebles.sort(re... | Marcombo/Programacio_per_batxillerat | 7-DatosFicheros/7.09-Ordenar.py | 7.09-Ordenar.py | py | 655 | python | es | code | 1 | github-code | 90 |
37151143290 | n= int(input())
array = []
for _ in range(n):
input_arr = map(int,input().split())
arr = []
for i in range(1,len(input_arr)):
arr.append(input_arr[i])
average = sum(arr)/len(arr)
result = 0
for i in arr:
if i>average:
result+=1
array.append(round(result/len(arr... | camel-man-ims/coding-test-python | problems/backjoon_혼자풀어보기/구현/정리3/평균은넘겠지.py | 평균은넘겠지.py | py | 338 | python | en | code | 0 | github-code | 90 |
13662423665 | # This is a series of functions that were implemented during Fall 2022 in
# MATH 3320: Error-Correcting Codes and Cryptography at Vanderbilt University
import math
from regex import D
from sympy import N
def error_pattern(codeword1, codeword2):
if len(codeword1) != len(codeword2):
print("Codewords must b... | delgadjd/ECC_Cryptography | main.py | main.py | py | 2,316 | python | en | code | 0 | github-code | 90 |
35899131126 | import face_recognition
import cv2
from openpyxl import Workbook
import datetime
# Get a reference to webcam #0 (the default one)
video_capture = cv2.VideoCapture(0)
# Create a woorksheet
book = Workbook()
sheet = book.active
# Load images.
image_1 = face_recognition.load_image_file('valid_images/1.... | himanshishrivas/Attendance-Management-System | attendance_marker01.py | attendance_marker01.py | py | 6,943 | python | en | code | 0 | github-code | 90 |
24396718029 | def street_fighter_selection(fighters, initial_position, moves):
cur_pos = [initial_position[0], initial_position[1]]
selected_fighters = []
for move in moves:
if move == "up":
cur_pos[0] = 0
elif move == "down":
cur_pos[0] = 1
elif move == "right":
... | ModimoESTEBAN/100-days-of-code-with-python | Street Fighter/main.py | main.py | py | 531 | python | en | code | 0 | github-code | 90 |
22917382045 | import requests
import json
def write():
url = ('https://newsapi.org/v2/top-headlines?'
'country=us&'
'apiKey=490529578a034be7aa774834b08fce87')
response = requests.get(url)
w=requests.get(url).json()
with open('data.json','w') as outfile:
json.dump(w,outfile)
def read_fromfile():
with open('... | siditrix17/desktop_news-app | new.py | new.py | py | 634 | python | en | code | 1 | github-code | 90 |
7658421678 | import schedule
import time
import threading
from FileSyncer import FileSyncer
def parse_daily(daily_sync):
return daily_sync.split(",")
class SyncScheduler:
def __init__(self, source, replica, daily_sync, sync_period, log_path):
self.source = source
self.replica = replica
self.file_... | antlionbug/folder-sync-python | scheduler.py | scheduler.py | py | 1,107 | python | en | code | 0 | github-code | 90 |
11206418627 | import pandas as pd
import matplotlib.pyplot as plt
# Read the csv file into a pandas dataframe
df = pd.read_csv('quantity.csv')
# Extract the medicine names and corresponding quantities
medicine_names = df['medicine_name'].tolist()
quantities = df['quantity'].tolist()
# Calculate the total quantity
total_quantity =... | Mokshithsaigit/pharma1 | scroll.py | scroll.py | py | 623 | python | en | code | 0 | github-code | 90 |
28265607921 | import numpy as np
import torch
import torch.nn as nn
from data import data_prep
def training(mnist_net):
loss = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(mnist_net.parameters(), lr=1.0e-3)
test_loss_all = []
test_accuracy_all = []
batch_size = 300
x_train, y_train, x_... | maypink/MNIST | training.py | training.py | py | 1,454 | python | en | code | 0 | github-code | 90 |
34872064840 | from pandas import timedelta_range
import pandas._testing as tm
class TestPickle:
def test_pickle_after_set_freq(self):
tdi = timedelta_range("1 day", periods=4, freq="s")
tdi = tdi._with_freq(None)
res = tm.round_trip_pickle(tdi)
tm.assert_index_equal(res, tdi)
| pandas-dev/pandas | pandas/tests/indexes/timedeltas/test_pickle.py | test_pickle.py | py | 302 | python | en | code | 40,398 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.