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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
3357675588 | from numpy.lib.polynomial import RankWarning
import torch as pt
import numpy as np
from dataset.GuidedBraTSDataset3D import GuidedBraTSDataset3D
from model.PFSeg import PFSeg3D
import cv2
import SimpleITK as sitk
lr=0.0001
epoch=100
batch_size=1
model_path='/path/to/Saved_models'
img_size=(64,96,96)
model=PFSeg3D().... | Dootmaan/PFSeg-ABR | step2_generateCoraseMask.py | step2_generateCoraseMask.py | py | 5,166 | python | en | code | 3 | github-code | 6 |
35411640384 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Update map explorers
--------------------
"""
import logging
from os.path import join
from hdx.data.dataset import Dataset
from hdx.data.resource import Resource
from src.acled import update_lc_acled, update_ssd_acled
from src.cbpf import update_cbpf
from src.fts import ... | OCHA-DAP/hdx-scraper-mapexplorer | mapexplorer.py | mapexplorer.py | py | 4,508 | python | en | code | 0 | github-code | 6 |
32414340113 | from flask import Flask, send_file, request, abort
from pathlib import Path
import youtube_dl
import json
app = Flask(__name__)
@app.route('/queuemp3', methods=['GET', 'POST'])
def queuemp3():
if request.method == 'POST':
try:
data = request.get_json()
url = data['url']
... | BK-Modding/youtube-2-mp3 | flask server/app.py | app.py | py | 1,961 | python | en | code | 2 | github-code | 6 |
33561633117 | import typing as t
import json
import re
from pathlib import Path
from PIL import Image
from torch.utils.data import Dataset
from .types.marked_image \
import MarkedImage, MarkedImageTensor
from .transforms import (
ToTensor
)
from ..utils import coord
class BdcDataSet(Dataset):
def __init__(self, img_p... | daikon-oroshi/court-detection | court_detection/data/data_set.py | data_set.py | py | 1,789 | python | en | code | 0 | github-code | 6 |
11004197028 | class Solution:
def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]],
initialBoxes: List[int]) -> int:
n = len(status)
can_open = [status[i] for i in range(n)]
has_box, used = [False] * n, [False] * n
q... | xixihaha1995/CS61B_SP19_SP20 | temp/toy/python/1298. Maximum Candies You Can Get from Boxes.py | 1298. Maximum Candies You Can Get from Boxes.py | py | 1,118 | python | en | code | 0 | github-code | 6 |
31632214544 |
import os
import sys
import random
import tables as tb
import numpy as np
import pandas as pd
import invisible_cities.reco.paolina_functions as plf
import invisible_cities.reco.dst_functions as dstf
from invisible_cities.io.mcinfo_io import load_mchits
from invisible_cities.io.mcinfo_io ... | paolafer/next_analysis | reco/topology2019/tracking_trueMC_part.py | tracking_trueMC_part.py | py | 8,998 | python | en | code | 0 | github-code | 6 |
2348487124 | import os
import sys
import logging
if sys.version_info >= (3, 0):
from io import StringIO
else:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
assert StringIO
from pylint import lint
from pylint.__pkginfo__ import numversion
class PyLinter(... | blizzrdof77/Sublime-Text-3-Packages | Anaconda/anaconda_lib/linting/anaconda_pylint.py | anaconda_pylint.py | py | 3,368 | python | en | code | 1 | github-code | 6 |
14077597352 | from lk.utils.config_util import ConfigUtil
from lk.utils.shell_util import run_and_confirm, run, run_and_return_output
from furl import furl
bitbucket = 'bitbucket'
bitbucket_domain = 'bitbucket.org'
github = 'github'
github_domain = 'github.com'
class SourceCodeRepo(object):
def __init__(self, url=None, serv... | eyalev/lk | lk/classes/source_code_repo.py | source_code_repo.py | py | 4,401 | python | en | code | 0 | github-code | 6 |
3439809361 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def widthOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype:... | cuiy0006/Algorithms | leetcode/662. Maximum Width of Binary Tree.py | 662. Maximum Width of Binary Tree.py | py | 957 | python | en | code | 0 | github-code | 6 |
5024929632 | from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError
import requests, json
from app_comments.models import RedditPost, Comment
from annoying.functions import get_object_or_None
from app_comments.lib.comments import CommentBuilder, RedditPostBuilder
from bs4... | daviddennis/comments | app_comments/management/commands/get_links.py | get_links.py | py | 2,264 | python | en | code | 0 | github-code | 6 |
72014598908 | import json
import sys
import argparse
sys.path.append("../evaluation")
from evaluate import tuple_f1, convert_opinion_to_tuple
def get_args():
"""
Helper function to get the gold json, predictions json and negation jsons
"""
parser = argparse.ArgumentParser()
parser.add_argument("gold")
pars... | jerbarnes/semeval22_structured_sentiment | analysis/domain_analysis.py | domain_analysis.py | py | 1,950 | python | en | code | 71 | github-code | 6 |
810789082 | from __future__ import division
import numpy as np
from scipy import sparse
from sklearn.metrics.pairwise import euclidean_distances
import time
# Produce grid points for a 2d grayscale image
def get_points_2d(image, res):
rows, columns = image.shape
grid_x, grid_y = np.mgrid[0:columns:res, 0:rows:res]
gri... | polaschwoebel/NonLinearDataAugmentation | vector_fields.py | vector_fields.py | py | 3,499 | python | en | code | 2 | github-code | 6 |
8092333942 | from vector import Vector
import turtle
scale = 40
def print_vector(vector, color):
turtle.pencolor(color)
turtle.penup()
turtle.home()
turtle.pendown()
turtle.goto(vector.elements[0]*scale,vector.elements[1]*scale)
def print_system(x,y):
turtle.home()
for i in range(x):
turtle.do... | sashokbg/python-exercises | vector/draw.py | draw.py | py | 760 | python | en | code | 0 | github-code | 6 |
21836154529 | import sys
sys.stdin = open('../input.txt', 'r')
N = int(input())
numbers = list(map(int, sys.stdin.readline().split()))
min_num, max_num = 1000000, -1000000
for number in numbers:
if number < min_num:
min_num = number
if number > max_num:
max_num = number
print(min_num, max_num) | liza0525/algorithm-study | BOJ/boj_10818_min_max.py | boj_10818_min_max.py | py | 308 | python | en | code | 0 | github-code | 6 |
72683621307 | from matplotlib import pyplot as plt
from numpy import loadtxt, zeros
from skimage.measure import label
from os import path
if __name__ == '__main__':
current_dir = path.dirname(__file__)
file_names = ['mat_p0.70.dat', 'mat_p0.72.dat']
for file_name in file_names:
file_path = path.join(current_di... | tee-lab/patchy-ecosterics | temp_actions/CSD/plotter.py | plotter.py | py | 1,513 | python | en | code | 2 | github-code | 6 |
30301888432 | import os
import sys
import unittest
from pathlib import Path
import coverage
from mpi4py import MPI
def main(path, parallel):
cov = coverage.coverage(
branch=True,
include=str(Path(path).parent) + '/ignis/executor/*.py',
)
cov.start()
import ignis.executor.core.ILog as Ilog
Ilog.enable(False)
tests = unit... | andreasolla/core-python | ignis_test/Main.py | Main.py | py | 1,575 | python | en | code | 1 | github-code | 6 |
13954467913 | '''Indicarle al usuario que ingrese un número entero e informar si es primo o no,
utilizando una función booleana que lo decida.'''
import os
if os.name == "posix":
os.system('clear')
else:
os.system('cls')
def primos(X):
if X<2:
return False
else:
for i in range(2,X):
... | eSwayyy/UCM-projects | python/catedra/lab_funciones/ejercicio6.py | ejercicio6.py | py | 463 | python | es | code | 1 | github-code | 6 |
7091903997 | import database
from datetime import datetime
import db_pyMySQL
conn = database.connection
# Thêm tài khoản "user": User sẽ không mã hoá mkhau do xài 2 ngôn ngữ khác nhau,
# nên khi mã hoá xong NodeJS sẽ ko hỗ trợ để giải mã => sẽ không đăng nhập được.
# INSERT:
# Thêm tài khoản khách hàng:
def insert_user(name, e... | letrinhan1509/FashionShop | api_admin/model_insert.py | model_insert.py | py | 8,813 | python | vi | code | 0 | github-code | 6 |
21916878669 | #!/usr/bin/env python2
import logging
import os
import shutil
import tempfile
from test_utils import TESTS_DIR, qsym, check_testcase
SCHEDULE_DIR = os.path.join(TESTS_DIR, "schedule")
logging.getLogger('qsym.Executor').setLevel(logging.DEBUG)
def get_testcases(exe, bitmap, input_binary):
output_dir = tempfile.mk... | sslab-gatech/qsym | tests/test_schedule.py | test_schedule.py | py | 2,236 | python | en | code | 615 | github-code | 6 |
72532823229 | # pylint: disable=protected-access
# pylint: disable=redefined-outer-name
# pylint: disable=too-many-arguments
# pylint: disable=unused-argument
# pylint: disable=unused-variable
from typing import Any
from urllib.parse import parse_qs
import pytest
from aiohttp.test_utils import make_mocked_request
from models_libr... | ITISFoundation/osparc-simcore | services/web/server/tests/unit/isolated/test_studies_dispatcher_models.py | test_studies_dispatcher_models.py | py | 5,342 | python | en | code | 35 | github-code | 6 |
5619484190 | # Backend function in order to the system
# check the credentials of users inside the system
# from mainGUI import *
# from mainGUI import adminMenu, customerMenu
import os
import tkinter as tk
def check_credentials(identity, password, choice,
admin_access): # checks credentials of admin/cust... | prince749924/banking-system | backend.py | backend.py | py | 7,923 | python | en | code | 0 | github-code | 6 |
71817771068 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# mid2sheet.py
# Midi-Files -> Sheets for Musicbox (30 notes, starting from F)
# (c) 2017 Niklas Kannenberg <kannenberg@airde.net> and Gunnar J.
# Released under the GPL v3 or later, see file "COPYING"
#
# ToDo
# - Use 'pypdf' instead of external 'pdfjam' for PDF m... | flylens/mid2sheet | mid2sheet.py | mid2sheet.py | py | 14,949 | python | en | code | 27 | github-code | 6 |
70285712189 | """
SWF
"""
from __future__ import absolute_import
from .tag import SWFTimelineContainer
from .stream import SWFStream
from .export import SVGExporter
from six.moves import cStringIO
from io import BytesIO
class SWFHeaderException(Exception):
""" Exception raised in case of an invalid SWFHeader """
def __init_... | timknip/pyswf | swf/movie.py | movie.py | py | 5,642 | python | en | code | 154 | github-code | 6 |
5517603024 | #python3
from math import floor
class HeapBuilder():
def __init__(self):
self._swaps = []
self._data =[]
def ReadInput(self):
#manual input
#n = 5
#self._data = [5, 4, 3, 2, 1]
#auto input
n = int(input())
self._data = [int(s) for s in input().... | craigpauga/Data-Structure-and-Algorithms | 2. Data Structures/Assignment 2 - Priority Queues & Disjoint Disjoint Sets/make_heap/build_heap.py | build_heap.py | py | 1,658 | python | en | code | 0 | github-code | 6 |
7573771770 | import os
import logging
from dotenv import load_dotenv
from flask import Flask, jsonify, request
from flask_cors import CORS
from flask_restful import Api, Resource, reqparse
from models.db.postgresDB import PostgresDB
from models.services.logger import get_module_logger
import models.services.flask_service as flask_s... | Mariusz94/Knowledge-base | backend/app.py | app.py | py | 4,372 | python | en | code | 0 | github-code | 6 |
10936847432 | def funcaoI(n):
i = 1
lista = []
while i <= n:
lista.append(i)
print(lista)
i += 1
def funcaoJ(n):
#solução com range
for i in range(n):
i += 1
print(f'{str(i) * i}')
#solução sem range
# i = 1
# while i <= n:
# print(f'{str(i) * i}')
#... | thallesbruno/logica-de-programacao | exercicios/lista_aula03/funcoesUteis.py | funcoesUteis.py | py | 785 | python | pt | code | 0 | github-code | 6 |
27735122824 | from scipy import integrate
import math
def func1(x):
return 1 / ((3*x - 1)**0.5)
def func2(x):
return math.log(x**2 + 1) / x
def func3(x):
return 1 / (0.2*x**2 + 1)**0.5
def rectangle_method(func, a, b, n):
h = (b - a)/n
integral_sum = sum(func(a + i * h) for i in range(n))
result = ... | Alisa7A/Numerical-methods-of-programming | Pr11 Шамігулової Аліси.py | Pr11 Шамігулової Аліси.py | py | 1,152 | python | en | code | 0 | github-code | 6 |
3325344481 | #SIMPLY READING A FILE
file = open("../files/essay.txt")
content = file.read()
print(content.title())
file.close()
# Return the numbers of characters in the file
file = open("../files/essay.txt", 'r')
content = file.read()
n_char = len(content)
print(n_char)
#ADDING MEMBERS IN THE FILE
member = input("Add a new membe... | ramhors/todo-app | A-MegaPython/exercises/readingFile.py | readingFile.py | py | 555 | python | en | code | 0 | github-code | 6 |
70793816827 | from pathlib import Path
import re, pickle, os
import pickle, win32net
from time import sleep
class Scanner:
wordList = ""
ignored_type = ""
ignored_dir = ""
# this will store all of the file dictionsaries
files = []
# This is the path that will be scanned
p = ''
... | thang41/OpenSourceSecurityCheck | scanner.py | scanner.py | py | 9,244 | python | en | code | 0 | github-code | 6 |
20507256803 | import pandas as pd
import csv
#This function initializes the DataFrame
def resetDf():
df = pd.read_csv("./Scoreboard.csv")
df.index += 1
return df
#This function adds a new player if it does not exist
def newPlayer(player):
create = True
with open('Scoreboard.csv', newline='', encoding='utf-8') a... | RafaelM4gn/TicTacToe | Scoreboard.py | Scoreboard.py | py | 953 | python | en | code | 0 | github-code | 6 |
70724549309 | from django.urls import path
from .views import RegiaoCreate, EmpresaCreate, AgendamentoColetaCreate, AgendamentoDescarteCreate
from .views import RegiaoUpdate, EmpresaUpdate, AgendamentoColetaUpdate, AgendamentoDescarteUpdate
from .views import RegiaoDelete, EmpresaDelete, AgendamentoColetaDelete, AgendamentoDescarte... | micaelhjs/PIUnivesp02 | cadastros/urls.py | urls.py | py | 1,948 | python | pt | code | 0 | github-code | 6 |
1448273356 | """This file is to run the model inference here's the command
python run_inference.py -i trainval/images/image_000000001.jpg -m model/model.pt"""
# import the necessary packages
import argparse
import cv2
import numpy as np
from PIL import Image
import torch
from torchvision import transforms
import config
from utils... | Pradhunmya/pytorch_faster_rcnn | run_inference.py | run_inference.py | py | 3,143 | python | en | code | 0 | github-code | 6 |
15354136781 | #使用unittest测试代码
import unittest
'''下面的函数用作示例,接下来将对它进行测试'''
def get_formatted_name(first,last):
'''格式化姓名'''
full_name = f'{first} {last}'
return full_name.title()
#单元测试,核实某函数某方面没有问题
class NamesTestCase(unittest.TestCase): #这里的类名可以随意命名,但必须继承unittest.TestCase类
'''测试示例的函数'''
def test_first_last_name(... | krau/py-learn | basics/10_testcode.py | 10_testcode.py | py | 773 | python | zh | code | 0 | github-code | 6 |
40686482793 | import time
import unittest
import swagger_client
from integ_tests.cloud import cloud_manager, fixtures
from integ_tests.cloud.cloud_manager import CloudManager
from integ_tests.gateway import rpc
class TestConfigUpdates(unittest.TestCase):
"""
Test that a newly-registered gateway receives updated configurat... | magma/magma | lte/gateway/python/integ_tests/cloud_tests/config_test.py | config_test.py | py | 4,232 | python | en | code | 1,605 | github-code | 6 |
35572141881 | command = ""
started = False
stopped = True
while True:
command = input("> ").lower()
if (command == 'help'):
print("""
Start - to start the car
Stop - to stop the car
quit - to exit the program
""")
elif (command == 'start'):
if started:
... | abdallauno1/python | car_game.py | car_game.py | py | 926 | python | en | code | 0 | github-code | 6 |
75108014908 | # from unicodedata import lookup
from django.urls import path, include
from rest_framework.routers import SimpleRouter, DefaultRouter # This for the viewset models in the views
from rest_framework_nested import routers # This is for the nested routers
from store.models import Product
# from pprint import pprint
from... | Auracule/e_commerce_api | store/urls.py | urls.py | py | 2,718 | python | en | code | 0 | github-code | 6 |
35919740986 |
print('''
||QURTZ||
============
hello participants, welome! to the "QURTZ" platform.
[instruction: you have total 5 question. Read each statement carefuly and place " True " for right answer & " False " for wrong answer. Every question giveS you 1 mark .]
let's start!
''')
i... | Vaishnavimaury2222/Vaishnavimaury2222 | PYTHON__PROJECT_@1.py | PYTHON__PROJECT_@1.py | py | 1,691 | python | en | code | 0 | github-code | 6 |
22852667916 | class Solution(object):
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
res = []
self.check(1, n, res, [], k)
return res
def check(self, start, target, res, pre, k):
if target == 0 and len(pre) == ... | yuweishi/LeetCode | Algorithms/Combination Sum III/solution.py | solution.py | py | 572 | python | en | code | 0 | github-code | 6 |
36992069067 | from tkinter import *
clicks = 0
def click_button():
global clicks
clicks += 1
root.title("Clicks {}".format(clicks))
root = Tk()
root.geometry("300x250")
btn = Button(text="клик",background="blue",foreground="lime",
padx="3100", pady="1000", font="1000", command=cli... | vitaminik2/programme | 0раторh.py | 0раторh.py | py | 371 | python | en | code | 0 | github-code | 6 |
811999536 | # Convert Sorted Array to Binary Search Tree - https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
'''Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of... | Saima-Chaity/Leetcode | Tree/convertSortedArrayToBinarySearchTree.py | convertSortedArrayToBinarySearchTree.py | py | 2,392 | python | en | code | 0 | github-code | 6 |
19416798117 | """Determine the fration of non-built-up land area needed to become autarkic."""
import click
import pandas as pd
import geopandas as gpd
from src.potentials import Potential
@click.command()
@click.argument("path_to_demand")
@click.argument("path_to_potential")
@click.argument("path_to_footprint")
@click.argument("... | timtroendle/possibility-for-electricity-autarky | src/necessary_land.py | necessary_land.py | py | 4,031 | python | en | code | 10 | github-code | 6 |
655296277 | import json
import os
from concurrent import futures
import luigi
import numpy as np
import nifty.tools as nt
import z5py
from cluster_tools.inference import InferenceLocal
from cluster_tools.inference.inference_embl import InferenceEmbl
OFFSETS = [
[-1, 0, 0],
[0, -1, 0],
[0, 0, -1],
[-2, 0, 0],
... | constantinpape/torch-em | experiments/unet-segmentation/mitochondria-segmentation/mito-em/challenge/segmentation_impl.py | segmentation_impl.py | py | 14,203 | python | en | code | 42 | github-code | 6 |
10522399200 | from src.common.database import Database
class Main(object):
@classmethod
def start_service(cls):
card_number = input("Enter card Number: ")
check_card_number = Database.find_one(query={"card_number": card_number})
if check_card_number is not None:
pin = input("Enter Pin:... | Ankomahene/Terminal_ATM_Banking | src/models/main.py | main.py | py | 5,680 | python | en | code | 0 | github-code | 6 |
10758898663 | import uvicorn
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Welcome to basic math operations api!"}
@app.get("/add")
async def add(a: int, b: int):
return {"result": a + b}
@app.get("/subtract")
async def subtract(a: int, b: int):
ret... | pawelcich/rest_api | web/app.py | app.py | py | 722 | python | en | code | 0 | github-code | 6 |
19631761443 | from FACE_VERIFICATION.validation import Verify
from utils.encrypt import Encrypt
from utils.calling import caller
import pickle
obj1 = Verify()
obj2 = Encrypt()
obj3 = caller()
class RUN:
def __init__(self):
pass
def controller(self,data):
mode = data['mode']
if mode == "verify":
... | saquibquddus/Face-Unlock-Web-Application | STREAMLIT/utils/run.py | run.py | py | 1,503 | python | en | code | 0 | github-code | 6 |
15560664217 |
def call_repeatmasker(fasta, lib, engine = "ncbi", cores = 1, dir = "./"):
# RepeatMasker -e ncbi -pa 28 -s
# -lib dmel_repbase_lib.fasta
# -no_is -nolow
# -dir .
# dmel-all-chromosome-r6.22.fasta
import subprocess
from rwt.checkers import check_installation
if not (check_i... | mal2017/reference-with-transposons | rwt/callers.py | callers.py | py | 854 | python | en | code | 0 | github-code | 6 |
27545085038 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Cube centring, detects bad frames, crops and bins
@author: Iain
"""
__author__ = 'Iain Hammond'
__all__ = ['calib_dataset']
from os import makedirs, system
from os.path import isfile, isdir
import numpy as np
from pyprind import ProgBar
import matplotlib
from matpl... | IainHammond/NACO_pipeline | naco_pip/NACO_preproc.py | NACO_preproc.py | py | 25,286 | python | en | code | null | github-code | 6 |
29451178686 | from selenium import webdriver
import time, re, urllib, requests
from telethon.sync import TelegramClient
from config import api_id, api_hash
client = TelegramClient('name', api_id, api_hash)
client.start()
dlgs = client.get_dialogs()
tegmo = None
for dlg in dlgs:
if dlg.title == "LTC Click Bot":
te... | Sofron80/coin_bot | main2.py | main2.py | py | 2,611 | python | en | code | 0 | github-code | 6 |
10254372975 | from multiprocessing import context
from django.shortcuts import render, redirect
from .models import *
# Create your views here.
def produk_list(request):
template_name = "produk_list.html"
group_produk = Circle_produk.objects.all()
context ={
"produk" : group_produk,
}
return render(reque... | RenalPutra/kasir-django | produk/views.py | views.py | py | 2,103 | python | tr | code | 0 | github-code | 6 |
22609873896 | from django.contrib.auth.decorators import user_passes_test, login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.http import JsonResponse
from django.shortcuts import render, redirect
from apps.rfid.models import GeneralAssembly
from hybridjango.utils import group_test
class Ballot:
... | hybrida/hybridjango | apps/ballot/views.py | views.py | py | 5,402 | python | en | code | 4 | github-code | 6 |
28177824191 | import os
def nystudent():
funnet=False
nyregistrering=True
while nyregistrering==True:
print()
print('Du har valgt å registrere ny student.')
print()
inndata = input('Skriv inn studentnummer: ')
#åpne studentfilen
studentfil=open('s... | meliakos/portfolio | Studentregistrering.py | Studentregistrering.py | py | 7,746 | python | no | code | 0 | github-code | 6 |
23515346720 | # First Solution
import sys
input = sys.stdin.readline
def Solution():
N = int(input().rstrip())
M = int(input().rstrip())
S = input().rstrip()
cnt, ans, i = 0, 0, 0
while i < M - 2:
if S[i:(i+3)] == "IOI":
cnt += 1
if cnt == N:
cnt -= 1
... | Soohee410/Algorithm-in-Python | BOJ/Silver/5525.py | 5525.py | py | 784 | python | en | code | 6 | github-code | 6 |
15287712724 | from PyQt4.QtCore import pyqtSignal
from PyQt4.QtGui import QCursor, QPixmap, QColor
from qgis.core import (QgsPoint, QgsRectangle, QgsTolerance,
QgsFeatureRequest, QgsFeature, QgsGeometry,
QgsVectorLayer, QGis)
from qgis.gui import QgsMapTool, QgsRubberBand
class Inspect... | NathanW2/qmap | src/qmap/maptools/inspectiontool.py | inspectiontool.py | py | 4,200 | python | en | code | 20 | github-code | 6 |
73739270588 | #!/usr/bin/env python3
import argparse
import os
import re
import subprocess
import sys
LOG_FILE_OPTION = 'log_file'
OUTPUT_PATH_OPTION = '--output-path'
ONLY_FAILED_OPTION = '--only-failed'
HUMAN_READABLE_OPTION = '--human-readable'
USE_RUBY_PARSER_OPTION = '--use-ruby'
FIND_COREDUMPS_OPTION = "--find-coredumps"
WRI... | dA505819/maxscale-buildbot | master/parser-tests/parser/parser.py | parser.py | py | 4,117 | python | en | code | 0 | github-code | 6 |
5188174924 | # 1. Check if the root is empty, hence if the tree is empty.
# 2. We are going to use queues to solve this problem as the queue FIFO property works well here.
# 3. Initialize a queue to hold the current root node
# 4. level is going to be an empty list/queue which we use to add in all the nodes at the particular lev... | IshGill/DSA-Guides | Trees/BFS_Level_order_traversal.py | BFS_Level_order_traversal.py | py | 1,908 | python | en | code | 9 | github-code | 6 |
73503536508 | from tianshou.data import Batch, ReplayBuffer, to_numpy, to_torch, to_torch_as
import stable_baselines3.common.logger as L
import functools
import gym
import numpy as np
from torch.nn import functional as F
from einops.layers.torch import Rearrange
from encoder import *
import einops
class RNEncoder(nn.Module):
def... | albertcity/OCARL | relation_net.py | relation_net.py | py | 4,818 | python | en | code | 1 | github-code | 6 |
3910734213 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Fri 14 09:34:03 2018
@author: MariusD
"""
#Server
from flask import Flask, jsonify
server = Flask("phonebook")
phonebook={"Mum":"0173240", "Dad":"01717374", "Pepe":"01773849", "IE":"01"}
# Add contact
@server.route("/add_contact/<number>/<name>",... | Mariusxz/Indidivdual_Assignment_3 | Individual-Assignment-3/Phonebook/Server.py | Server.py | py | 1,759 | python | en | code | 0 | github-code | 6 |
1926135601 | # 1921. Eliminate Maximum Number of Monsters
class Solution:
def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:
if(len(dist) == 0):
return 0
time = list()
for i in range(len(dist)):
time.append(ceil(dist[i]/speed[i]))
time... | yash-gada/LeetCode | Python/Eliminate_Maximum_Number_of_Monsters.py | Eliminate_Maximum_Number_of_Monsters.py | py | 495 | python | en | code | 0 | github-code | 6 |
74387576189 | cap = input('Masukkan kapasitas kendaraan: ')
pel = input('Masukkan jumlah pelanggan (N): ')
jml = input('Masukkan banyak data: ')
if int(cap) < int(pel):
print('Data tidak benar')
else:
arr = [0 for i in range(int(jml))]
itung = [0 for i in range(int(jml))]
for i in range(int(jml)):
arr[i] = i... | xmriz/kuliah-main | tesAsprak/seleksi_18221071_2.py | seleksi_18221071_2.py | py | 484 | python | id | code | 0 | github-code | 6 |
9836414156 | import sys
from collections import deque
n = int(sys.stdin.readline());
board = [];
for _ in range(n):
board.append(list(map(int, list(sys.stdin.readline())[:-1])));
dx = [0, 0, -1, 1];
dy = [1, -1, 0, 0];
def bfs(board, x, y):
if board[x][y] == 0: return 0;
area = 1;
q = deque([]);
board[x][y] =... | woasidh/algorithm | python/BOJ/그래프_탐색/2667.py | 2667.py | py | 932 | python | en | code | 0 | github-code | 6 |
40462981449 | '''Menu Driven program to implement encryption and decryption using hill cipher'''
def encrypt_2(plain_text,key):
'''
Purpose of the function is to encrypt the even length plain text using 2x2 matrix.
Input : plain_text - text to be encoded
key - 2x2 matrix used for encryption
Output :... | himanshi-gupta/Information_Security_Assignment | Hill_cipher.py | Hill_cipher.py | py | 5,252 | python | en | code | 0 | github-code | 6 |
13663867321 | import gzip
import os
import json
import random
from tqdm import tqdm
import numpy as np
from more_itertools import chunked
def format_str(string):
for char in ['\r\n', '\r', '\n']:
string = string.replace(char, ' ')
return string
def extract_test_data(DATA_DIR, language, target, file_name, test_b... | suda1927406040/BackdoorCodeSearch | utils/attack_code/attack/extract_data.py | extract_data.py | py | 5,136 | python | en | code | 0 | github-code | 6 |
36545155158 | from django.http import Http404, JsonResponse
from django.shortcuts import render
from . import fsop
from .models import Directory, File, NotFoundError
def root(request):
return index(request, '')
def index(request, path):
path = _split_path(path)
try:
directory = Directory.from_path(path)
... | joshsteiner/MyDrive | drive/views.py | views.py | py | 1,606 | python | en | code | 0 | github-code | 6 |
44344581625 | import sys
sys.stdin = open('input/4873.txt', 'r')
def len(word):
cnt = 0
for w in word:
cnt += 1
return cnt
T = int(input())
for tc in range(1, T + 1):
s = input()
stack = []
for char in s:
if not stack or stack[-1] != char:
stack.append(char)
else:
... | nayeonkinn/algorithm | swea/[D2] 4873. 반복문자 지우기.py | [D2] 4873. 반복문자 지우기.py | py | 370 | python | en | code | 0 | github-code | 6 |
38269716845 | import tensorflow as tf
from tensorflow.keras import layers
import pickle
import tarfile
import numpy as np
import scipy as sc
import cv2
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import math
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
def extract(... | RSpe/Keras-Tensorflow-Cifar10-Model | model.py | model.py | py | 6,107 | python | en | code | 0 | github-code | 6 |
72528402109 | import os, csv
import nltk as nlp
from nltk.probability import FreqDist
import pandas as pd
import matplotlib.pyplot as plt
hapaxList = []
with open('hapaxList.csv', 'w', newline='') as wordsCSVfile:
write = csv.writer(wordsCSVfile)
write.writerow(["Year", "Chart", "Hapax Count", "Hapaxes"])
# Iterate through w... | stkeller/Replication-Thesis | Code/LexicalHapax.py | LexicalHapax.py | py | 1,106 | python | en | code | 0 | github-code | 6 |
25033146898 | import decimal
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from annoying.functions import get_o... | csloan29/HES-e-33a-web-django | commerce/auctions/views.py | views.py | py | 9,574 | python | en | code | 0 | github-code | 6 |
14475582891 | from django import forms
from django.forms import modelformset_factory
from dashboard.forms.educator_account_form import EducatorAccountForm
from dashboard.models.educator_model import Educator
class EducatorForm(forms.ModelForm):
class Meta:
model = Educator
fields = ['photo', 'name', 'title', '... | EslamTK/Students-Performance-System | dashboard/forms/educator_form.py | educator_form.py | py | 1,367 | python | en | code | 7 | github-code | 6 |
45386300266 | from __future__ import unicode_literals
import importlib
import os
import sys
from theory.apps import apps
from theory.utils import datetimeSafe, six
from theory.utils.six.moves import input
from .loader import MIGRATIONS_MODULE_NAME
class MigrationQuestioner(object):
"""
Gives the autodetector responses to qu... | grapemix/theory | theory/db/migrations/questioner.py | questioner.py | py | 5,492 | python | en | code | 1 | github-code | 6 |
31026372746 | import bme280
import smbus2
import time
import datetime
port = 1
address = 0x77 # Adafruit BME280 address. Other BME280s may be different
bus = smbus2.SMBus(port)
bme280.load_calibration_params(bus,address)
while True:
bme280_data = bme280.sample(bus,address)
humidity = bme280_data.humidity
pressure =... | drozden/smartCities | archive/weather1.py | weather1.py | py | 643 | python | en | code | 0 | github-code | 6 |
13058283715 | from datetime import timezone
import pytest
from util.file_util import FileUtil
class TestFileUtil:
@pytest.mark.parametrize('file', ('/etc/hosts', '/etc/profile'))
def test_get_last_file_change_ts(self, file: str):
ts = FileUtil.get_last_file_change_ts(file)
assert ts is not None
a... | mbogner/imagination | tests/util/test_file_util.py | test_file_util.py | py | 644 | python | en | code | 0 | github-code | 6 |
31533956916 | start = int(input())
finish = int(input())
number_to_reach = int(input())
combinations = 0
matches = 0
for first_number in range(start, finish + 1):
for second_number in range(start, finish + 1):
combinations += 1
if first_number + second_number == number_to_reach:
matches += 1
... | iliyan-pigeon/Soft-uni-Courses | programming_basics_python/nested_loops/sum_of_two_numbers.py | sum_of_two_numbers.py | py | 529 | python | en | code | 0 | github-code | 6 |
73076335867 | #!/usr/bin/env python3
import os
import sys
import subprocess
cd = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
locale_path = os.path.join(cd, "locale")
pot_file_path = os.path.join(locale_path, "TTMediaBot.pot")
source_paths = [os.path.join(cd, "bot"), os.path.join(cd, "TTMediaBot.py")]
babel_prefix ... | gumerov-amir/TTMediaBot | tools/compile_locales.py | compile_locales.py | py | 1,236 | python | en | code | 52 | github-code | 6 |
15710053369 | from fastapi import APIRouter, Depends, Response
from typing import List, Union
from queries.cover import CoverIn, CoverOut, CoverRepository, Error
router = APIRouter()
@router.post("/covers", response_model=Union[CoverOut, Error])
def create_cover(
cover: CoverIn,
repo: CoverRepository = Depends()
):
re... | oliviaxu0528/narrative-dojos | nd/routers/cover.py | cover.py | py | 1,501 | python | en | code | 0 | github-code | 6 |
4582050726 | import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
from scipy import stats
import collections
import time
from sklearn import cluster
from sklearn.metrics import adjusted_rand_score
import scipy as sp
from tqdm import tqdm
from sklearn.manifold import MDS
from run_dist_mat... | pdavar/Analysis-of-3D-Mouse-Genome-Organization | bin_resample_analysis.py | bin_resample_analysis.py | py | 3,912 | python | en | code | 0 | github-code | 6 |
72296990589 | import doctest
"""Morse Code Translator"""
LETTER_TO_MORSE = {
'A': '.-', 'B': '-...', 'C': '-.-.',
'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H': '....', 'I': '..',
'J': '.---', 'K': '-.-', 'L': '.-..',
'M': '--', 'N': '-.', 'O': '---',
'P': '.--.', 'Q': '--.-', 'R': '.-.',
'S': '...... | janemur/HW5 | issue-01/main.py | main.py | py | 2,058 | python | ru | code | 0 | github-code | 6 |
38986389406 | #!/usr/bin/env python
import wifi
import socket
import subprocess
import re
import time
while True:
seekers = filter(lambda cell: cell.ssid == 'OracleSeeker', wifi.Cell.all('wlan0'))
if len(seekers) > 0:
print('Found seeker', seekers[0])
cell = seekers[0]
scheme = wifi.Scheme.find('wlan0', 'seeker')
# sche... | raboof/SHA2017Game-oracle | oracle.py | oracle.py | py | 789 | python | en | code | 0 | github-code | 6 |
39346916658 | import pandas as pd
import fasttext
class LanguageDetector:
def __init__(self):
self.model = fasttext.load_model('lid.176.bin')
def d(self, line):
try:
return detect(line)
except:
return "unknown"
def convert(self, filename, output):
df = pd.read_cs... | hackartists/social-data-aggregator | detector.py | detector.py | py | 1,183 | python | en | code | 0 | github-code | 6 |
3490973159 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 31 00:40:46 2020
@author: Rashidul hasan (student id-1512027)
depertmant of naval architucture and marine engineering
Bangladesh university of engineering and technology
By using this moddule we can see our desiarbale design which is created by using design modu... | rashedhasan007/A-topology-and-optimisation-software- | A-topology-and-optimisation-software--main/view.py | view.py | py | 954 | python | en | code | 0 | github-code | 6 |
43291543351 | import math
import os
import cv2
from ultralytics import YOLO
from people import People
from car import Car
video = os.path.join('.', 'videos', 'Casa-Ch.mp4')
video_cap = cv2.VideoCapture(video)
fps = video_cap.get(cv2.CAP_PROP_FPS)
pixels = int((24/fps)*15)
ret, frame = video_cap.read()
altura, largura, canais = fr... | serjetus/Projeto | src/main.py | main.py | py | 3,473 | python | en | code | 0 | github-code | 6 |
18110173657 | from django.contrib import admin
from django.urls import path, include, re_path as url
# 스웨거 설정
from rest_framework.permissions import AllowAny
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from django.conf import settings
from django.conf.urls.static import static
# 스웨거 설정
schema_url_patte... | Kim-Link/drfLogin | drfLogin/drfLogin/urls.py | urls.py | py | 1,437 | python | en | code | 0 | github-code | 6 |
20825994964 | import json
from pandas import DataFrame
import pandas as pd
import requests
import emails
file_name = 'teste.csv'
def getJson():
r = requests.get('https://api.biscoint.io/v1/ticker?base=BTC"e=BRL')
df_new = pd.DataFrame()
df = pd.DataFrame(json.loads(r.text))
date = pd.Timestamp.date(pd.Timesta... | HumbertoLimaa/mysite | utils.py | utils.py | py | 1,135 | python | en | code | 0 | github-code | 6 |
4769430747 | #!/usr/bin/env python
import sys
import glob, os
import argparse
def insert_track_id(label_file, track_ids):
labels_with_track = []
with open(label_file, 'r') as yolo_f:
labels = yolo_f.readlines()
for i, label in enumerate(labels):
split_label = label.split()
if len(split_label) < 6:
... | Salmon-Computer-Vision/salmon-computer-vision | utils/scribe_yolo_track.py | scribe_yolo_track.py | py | 2,022 | python | en | code | 4 | github-code | 6 |
811294756 | '''Swapping Nodes in a Linked List - https://leetcode.com/problems/swapping-nodes-in-a-linked-list/
You are given the head of a linked list, and an integer k.
Return the head of the linked list after swapping the values of the kth node
from the beginning and the kth node from the end (the list is 1-indexed).
Example... | Saima-Chaity/Leetcode | LinkedList/Swapping Nodes in a Linked List.py | Swapping Nodes in a Linked List.py | py | 1,108 | python | en | code | 0 | github-code | 6 |
39688113614 | # 102. Binary Tree Level Order Traversal
# Time: O(size(Tree))
# Space: O(size(Tree))
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[... | cmattey/leetcode_problems | Python/lc_102_binary_level_order_traversal.py | lc_102_binary_level_order_traversal.py | py | 863 | python | en | code | 4 | github-code | 6 |
28999549212 | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
import safygiphy
from response import Response
giief = safygiphy.Giphy()
def getgif(mattermost_request):
text = mattermost_request.text
search = ''.join(text).encode('latin1')
jif = giief.random(tag=search)
if jif['data']:
t = u'' +jif['data... | rehwanne/wannbot | gif.py | gif.py | py | 434 | python | en | code | 1 | github-code | 6 |
29432109275 | from collections import defaultdict, Counter
class Solution:
def groupAnagrams(self, strs):
ana_dict = defaultdict(list)
for s in strs:
# ana_dict[tuple(sorted(Counter(s)))].append(s)
count = [0]*26
for c in s:
count[ord(c)-ord('a')] += 1
... | mintaewon/coding_leetcode | 0909/P53_hoin.py | P53_hoin.py | py | 478 | python | en | code | 0 | github-code | 6 |
17996077237 | # -*- coding:utf-8 -*-
# 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
# 说明:
# 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
num = nums[0]
for i in range(1,len(nu... | shirleychangyuanyuan/LeetcodeByPython | 136-只出现一次的数字.py | 136-只出现一次的数字.py | py | 625 | python | zh | code | 0 | github-code | 6 |
3020675145 | import os
DEFAULT_TIMEZONE = 'US/Eastern'
DEFAULT_START_DATE = '2012-01-01'
DEFAULT_END_DATE = '2018-03-31'
S3_DATA_BUCKET = 'com.estimize.production.data'
CURRENT_QUARTER = '2018q1'
ROOT_DATA_URL = 'https://s3.amazonaws.com/{}/research/{}'.format(S3_DATA_BUCKET, CURRENT_QUARTER)
def data_dir():
if os.path.base... | Estimize/estimize-research-py | estimize/config.py | config.py | py | 473 | python | en | code | 10 | github-code | 6 |
27049794168 |
cmd = 'call function'
cmd2 = 'Test!'
if cmd.split(" ")[1] == "function":
print(f"{cmd}")
x = cmd.split(" ")[0]
x2 = cmd.split(" ")[0] + " " + cmd.split(" ")[1]
cmd = cmd.split(" ")[1]
print(cmd) # split the cmd var and look and index 1, 'function'.
print(x... | Digitwidgit/Code-Snippets-for-Socket-Programming | Function_Calling_Outside_TheFunction.py | Function_Calling_Outside_TheFunction.py | py | 656 | python | en | code | 0 | github-code | 6 |
30970218925 | from euphorie.client import model
from euphorie.client.tests.test_model import createSurvey
from osha.oira.testing import OiRAIntegrationTestCase
class NoCustomRisksFilterTests(OiRAIntegrationTestCase):
def query(self):
return self.session.query(model.SurveyTreeItem).filter(
model.NO_CUSTOM_RI... | euphorie/osha.oira | src/osha/oira/client/tests/test_custom_risks.py | test_custom_risks.py | py | 1,458 | python | en | code | 4 | github-code | 6 |
3238675482 | """Contains the class single_object.
Used to compute single thermal objects.
"""
from .. import solvers
from . import Object
import matplotlib.pyplot as plt
import numpy as np
class SingleObject:
"""Single_object class.
This class solves numerically the heat conduction equation for 1 dimension
of a si... | djsilva99/heatrapy | heatrapy/dimension_1/objects/single.py | single.py | py | 17,265 | python | en | code | 51 | github-code | 6 |
19116408556 | N = int(input())
V = list(map(int, input().split()))
T = []
A = []
V.reverse()
print(V)
for i in range(N):
d = V(0)
T.append(d)
V.pop(0)
print(T)
c = statistics.median(V)
A.append(c)
V.remove(c)
print(sum(T))
| NPE-NPE/activity | python/Atcoder/couldn't/AGC/053/b.py | b.py | py | 231 | python | en | code | 0 | github-code | 6 |
32563261250 | """
HTTP endpoints for `station_store`
"""
from fastapi import HTTPException, status
from screfinery import schema
from screfinery.crud_routing import EndpointsDef, RouteDef, \
crud_router_factory
from screfinery.stores import station_store
from screfinery.util import is_user_authorized
def authorize(user, scope... | fre-sch/sc-refinery-api | screfinery/routes/station.py | station.py | py | 1,371 | python | en | code | 0 | github-code | 6 |
71567841467 | number_of_open_tabs = int(input())
salary = int(input())
salary_condition = True
for _ in range(number_of_open_tabs):
name_of_website = input()
if name_of_website == 'Facebook':
salary -= 150
elif name_of_website == 'Instagram':
salary -= 100
elif name_of_website == 'Reddit':
s... | lorindi/SoftUni-Software-Engineering | Programming-Basics-with-Python/8.For Loop - Exercise/salary.py | salary.py | py | 486 | python | en | code | 3 | github-code | 6 |
30513158454 | import os
import datetime
from django.conf import settings
date = datetime.datetime.now()
filename_secrets_bx24 = os.path.join(settings.BASE_DIR, 'reports', 'report.txt')
class Report:
def __init__(self):
self.date = None
self.filename = None
self.fields = None
# self.encoding = '... | Oleg-Sl/Quorum_merge_contacts | merge_contacts/api_v1/service/report/report_to_html.py | report_to_html.py | py | 7,159 | python | en | code | 0 | github-code | 6 |
27568079162 | from sys import platform
from pathlib import Path
from clang.cindex import Config
# -- Project information -----------------------------------------------------
project = 'zenoh-pico'
copyright = '2017, 2022 ZettaScale Technology Inc'
author = 'ZettaScale Zenoh team'
release = '0.11.0.0'
# -- General configuration --... | eclipse-zenoh/zenoh-pico | docs/conf.py | conf.py | py | 1,328 | python | en | code | 63 | github-code | 6 |
40160808434 | import openpyxl
import os
from setting import get_file_path, get_file_name
file_path = get_file_path()
file_name = get_file_name()
# 切換到指定路徑
os.chdir(file_path)
# 讀進Excel檔案
wb = openpyxl.load_workbook(file_name)
# 取的Excel的第一個工作表
sheet = wb.worksheets[0]
etf_all = dict()
# 彙整全部的ETF清單
for columnNum in range(1, she... | ShengUei/Stock | etf_analysis.py | etf_analysis.py | py | 1,419 | python | en | code | 0 | github-code | 6 |
26796673166 | '''
11. Container With The Most Water
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container cont... | LySofDev/LeetCode-Solutions | P11-ContainerWithTheMostWater.py | P11-ContainerWithTheMostWater.py | py | 1,637 | python | en | code | 0 | github-code | 6 |
70732810747 | import struct
import numpy as np
# функции для чтения заголовка
def uint32_type(uint32_type): # функция преобразовывет bin и возвращает uint32
uint32_type_1 = struct.unpack('<I', uint32_type)
return uint32_type_1[0]
def float_type(float_type): # функция преобразовывет bin и возвращает float
float_... | churillov/Scattering_Matrix_Calculation | zagolovok.py | zagolovok.py | py | 3,584 | python | ru | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.