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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
4313160628 | from decouple import config
from etria_logger import Gladsheim
from src.domain.validator.webhook.validator import WebHookMessage
from src.infrastructure.mongo_db.infrastructure import MongoDBInfrastructure
class UserRepository:
infra = MongoDBInfrastructure
@classmethod
async def __get_collection(cls):
... | sam-ve-m/webhook.onboarding | func/src/repositories/user/repository.py | repository.py | py | 1,773 | python | en | code | 0 | github-code | 50 |
23287441547 | __author__ = "Vanessa Sochat"
__copyright__ = "Copyright 2021-2023, Vanessa Sochat"
__license__ = "MPL 2.0"
import os
import contributor_ci.utils as utils
# Replacements can currently be made for the database_file and lmod_base
install_dir = utils.get_installdir()
reps = {"$install_dir": install_dir, "$root_dir": os... | vsoch/contributor-ci | contributor_ci/defaults.py | defaults.py | py | 470 | python | en | code | 3 | github-code | 50 |
44033324144 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import time
import os
import lib.Product as p
import lib.Productlist as l
# schreiben Sie eine Abfrage die die zu verarbeitende Datei abfragt.
# Dabei soll das Suffix .csv für CSV Dateien stehen und das Suffix .json für JSON Dateien.
# schreiben Sie eine Abfrage als was die ... | itadh-jz/ita3-2020-04 | neue_einkaufsliste.py | neue_einkaufsliste.py | py | 2,658 | python | de | code | 0 | github-code | 50 |
74727431835 | from rest_framework import status
# internal
from .base import BaseTestCase
class ProteinViewsetTestCase(BaseTestCase):
def setUp(self) -> None:
super().setUp()
def test_list_proteins(self):
endpoint = f"{self.url_api_prefix}proteins/"
res = self.client.get(endpoint)
self.ass... | donscara/Bioscience-Application-Project | api/tests/test_protein.py | test_protein.py | py | 2,620 | python | en | code | 0 | github-code | 50 |
17271641219 | import numpy as np
import pandas as pd
def main():
df = pd.read_csv('raw_data/winemag.csv')
np.random.seed(555)
split_maks = np.random.rand(len(df)) < 0.8
train_df = df[split_maks]
test_df = df[~split_maks]
train_df.to_csv('processed_data/train.csv', index=False)
test_df.to_csv('processe... | mindsdb/mindsdb-examples | classics/wine_quality/data_processing.py | data_processing.py | py | 359 | python | en | code | 29 | github-code | 50 |
10287857 | # Import necessary libraries
import sys
from utils.file_utils import FileUtils
from utils.code_parser_interface import CodeParser
from stores.function_store import FunctionStore
from core.open_ai import OpenAI as AI
from utils.request_transformer import RequestTransformer
def generate_ai_unit_tests(file_path):
p... | killswitchh/ai-unit-test | .github/unit-test/add_unit_tests.py | add_unit_tests.py | py | 1,490 | python | en | code | 0 | github-code | 50 |
27334403900 | """Specify all CLI-accessible modules and their configurations, the pipeline to run by default, and define special functions for the `config` and `pipeline` CLI option trees."""
import argparse
from typing import Callable, Final, Optional
import nhssynth.cli.module_arguments as ma
import nhssynth.modules as m
from nhs... | nhsengland/NHSSynth | src/nhssynth/cli/module_setup.py | module_setup.py | py | 7,892 | python | en | code | 2 | github-code | 50 |
4644450389 | import os
from asr_model.audio import AudioFile
from asr_model.utils import extract_audio, convert_audio, write_to_file
from pydub import AudioSegment as am
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
import os
import torch
import torchaudio
from asr_model.variabels import *
V... | BarryZM/Dialog_generate_tool | STT/asr_model/transcript_dialog.py | transcript_dialog.py | py | 4,076 | python | en | code | 0 | github-code | 50 |
20497572613 | import os
from waflib import Logs
def build(bld):
platform = bld.env['PLATFORM']
spec = bld.options.project_spec
configuration = bld.env['CONFIGURATION']
if platform and not platform == 'project_generator' and not bld.cmd == 'generate_uber_files' and 'CryAudioImplWwise' in bld.spec_modules(spec, platform, configu... | MibuWolf/CryGame | Code/CryEngine/CryAudioSystem/implementations/CryAudioImplWwise/wscript | wscript | 9,786 | python | en | code | 2 | github-code | 50 | |
11697945116 | import operator
import random
import math
def calcShannonEnt(dataSet): # 计算数据的熵(entropy)
numEntries = len(dataSet) # 数据条数
labelCounts = {}
for featVec in dataSet:
currentLabel = featVec[-1] # 每行数据的最后一个字(类别)
if currentLabel not in labelCounts.keys():
labelCounts[currentLabel] ... | Carrot97/MachineLearning | EnsenbleLearning/RandomForest/TreeofForest.py | TreeofForest.py | py | 4,509 | python | en | code | 1 | github-code | 50 |
25160036554 | import numpy
from cost import hypothesis
def gradient(theta, X, Y, alpha):
m, n = X.shape
for j in range(0, len(theta)):
derivative = 0
for x, y in zip(X, Y):
derivative += (hypothesis(theta, x) - y)*x[j]
theta[j] = theta[j] - (alpha/m) * derivative
return theta
| andrelbol/IA | IC/LogicalRegression/gradient.py | gradient.py | py | 295 | python | en | code | 0 | github-code | 50 |
26182680397 | from PIL import Image
import os
import imageio
import datetime
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
plt.rcParams['font.size']=16
import os
pd = os.path.dirname(os.getcwd())
inDir = '/fits'
outDir = inDir
os.chdir(pd + inDir)
images = np.load('image_array.npy')
num... | microncubed/diffusivity | scripts/08_line_scan.py | 08_line_scan.py | py | 1,602 | python | en | code | 0 | github-code | 50 |
9371337100 | import requests
from bs4 import BeautifulSoup
def getHomeData(data):
data.clear()
data['middlePosts'] = []
data['leftPosts'] = []
data['today'] = []
# data['todayEvents'] = []
# data['tomorrowEvents'] = []
# data['weekendEvents'] = []
data['futureEvents'] = []
data['inCinema'] = []
... | kwolarz/epoznan-backend | home.py | home.py | py | 6,291 | python | en | code | 0 | github-code | 50 |
69946475675 | from openerp.osv.orm import Model, BaseModel, fields, except_orm, FIELDS_TO_PGTYPES, LOG_ACCESS_COLUMNS # MetaModel, Model, TransientModel, AbstractModel
import types
import openerp.tools as tools
import logging
_logger = logging.getLogger(__name__)
_schema = logging.getLogger(__name__ + '.schema')
Model._sequence ... | BorgERP/edifact | server_base/osv/orm.py | orm.py | py | 14,968 | python | en | code | 0 | github-code | 50 |
19666717613 | import win32com.client
from pywintypes import com_error
from tkinter.filedialog import askopenfilenames
from pathlib import PurePath
o = win32com.client.Dispatch("Excel.Application")
wb_path = askopenfilenames(title = "Select Excel file")
o.Visible = False
i = 0
try:
wb = o.Workbooks.Open(PurePath(wb_path[i]))
... | cesarandres8911/Python_exercises | Facturacion_Expa/PrintToPdf.py | PrintToPdf.py | py | 861 | python | en | code | 0 | github-code | 50 |
9073798892 | """
"""
from processing_components.calibration.calibration_control import calibrate_function
from processing_components.calibration.operations import apply_gaintable
from processing_components.visibility.gather_scatter import visibility_gather_channel
from processing_components.visibility.operations import divide_vis... | rtobar/algorithm-reference-library | workflows/serial/calibration/calibration_serial.py | calibration_serial.py | py | 1,996 | python | en | code | null | github-code | 50 |
38292239949 |
# normalized vocabulary for evidence_label
# 'FDA guidelines', 'preclinical', 'trials', 'NCCN guidelines', or
# 'European LeukemiaNet Guidelines'
# see https://docs.google.com/spreadsheets/d/1j9AKdv1k87iO8qH-ujnW3x4VusbGoXDjdb5apUqJsSI/edit#gid=1415903760
def evidence_label(evidence, association, na=False):
# ... | ohsu-comp-bio/g2p-aggregator | harvester/evidence_label.py | evidence_label.py | py | 3,746 | python | en | code | 48 | github-code | 50 |
36392048280 | from pwn import *
host, port = '10.10.147.219',3404
s = remote(host,port)
s.recvline()
while 1:
op = s.recvline()
op = op.decode('utf-8')
print(op)
if 'flag' in op:
print(op)
msg = s.recvall()
msg = msg.decode('utf-8')
print(msg)
break
solve = op.split(' ')
... | AlionGreen/python-scripts | flag83.py | flag83.py | py | 586 | python | en | code | 1 | github-code | 50 |
13146243692 | import io_utils
import numpy as np
import pandas as pd
import shutil
"""
DataSets.load(data_set_name)->data, labels
DataSets.save_artificial(data, labels, features_labels)
load the already computed rank/weight by feature selector using cv strategy on data set(cv,D)
PrecomputedData.load(data_set_name, cv, assessment... | WYBupup/EnsembleMethodsForFeatureSelection | data_sets.py | data_sets.py | py | 8,594 | python | en | code | null | github-code | 50 |
2579283470 | import dash
from dash import Dash, html, dcc, Input, Output, callback, State
import plotly.express as px
from dash import dash_table
import pandas as pd
import dash_bootstrap_components as dbc
import plotly.graph_objects as go
import sys
import json
import numerize
from numerize import numerize
from flask_caching impo... | josephine-amponsah/retail-demand-forecaster | dash_app/pages/dashboard.py | dashboard.py | py | 21,375 | python | en | code | 2 | github-code | 50 |
26570349832 | """
convergence.py
script contains functions to determine the convergence time of indus
CREATED ON: 12/10/2020
AUTHOR(S):
Bradley C. Dallin (brad.dallin@gmail.com)
** UPDATES **
TODO:
"""
##############################################################################
## IMPORTING MODULES
###################... | atharva-kelkar/hydrophobicity-features | sam_analysis/indus/convergence.py | convergence.py | py | 7,275 | python | en | code | 0 | github-code | 50 |
25779239585 | #!/usr/bin/python3
"""a Rectangle Class that models a rectangle"""
from models.base import Base
class Rectangle(Base):
"""a model of a rectangle"""
def __init__(self, width, height, x=0, y=0, id=None):
"""initialise a Rectangle instance"""
self.width = width
self.height = height
... | gisconesheri2/alx-higher_level_programming | 0x0C-python-almost_a_circle/models/rectangle.py | rectangle.py | py | 4,388 | python | en | code | 0 | github-code | 50 |
15917277332 | from django.conf import settings
from . import constants
import json
import requests
import webbrowser
import base64
import datetime
import os
class XeroAuthManager:
refresh_token = ''
access_token = ''
refresh_timestamp = 0
refresh_timeout = 1800
token_filename = ''
b64_id_secret = ''
... | simonfroggatt/medusa_plinks | apps/xero_toolkit/xeromanager.py | xeromanager.py | py | 9,096 | python | en | code | 0 | github-code | 50 |
13746146054 | from time import sleep
import pytest
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
# Test 3A (arrange, act, assert)
@pytest.mark.parametrize("env", ["dev"])
def test_selenium_google(setup_function, env):
# ... | CommonMarvel/full-stack-testing-starter | tests/selenium/demo/selenium_google_test.py | selenium_google_test.py | py | 1,449 | python | en | code | 3 | github-code | 50 |
2188934878 | '''
给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
说明:不要使用任何内置的库函数,如 sqrt。
示例 1:
输入:16
输出:True
示例 2:
输入:14
输出:False
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-perfect-square
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
# 二分查找
class Solution:
def ... | sunxinzhao/LeetCode_subject | simple/number/367.py | 367.py | py | 1,857 | python | zh | code | 0 | github-code | 50 |
4140086112 | import numpy as np
import matplotlib.pyplot as plt
from skimage import color
from sklearn.cluster import KMeans
import argparse
def change_format(img, back=False): # change picture from rgb to lab
if back:
return color.lab2rgb(img)
return color.rgb2lab(img)
def run_trans( # transform each cluster
... | cyzkrau/DIP_2021f | Color_Transfer/color_transfer.py | color_transfer.py | py | 2,975 | python | en | code | 0 | github-code | 50 |
22795758008 |
"""
THIS CODE IS REALLY SLOPPY AND BAD
I just wanted to solve this problem as fast as possible
I ranked 4,869 for both problems solved, in like 38 minutes
I just wanted to code it as fast as possible to see how quick
I could come up with a solution
"""
data = open("input.txt").read().splitlines()
test = data[0]
syn... | mattbruv/advent-of-code | src/2021/day10/day10.py | day10.py | py | 1,751 | python | en | code | 0 | github-code | 50 |
38719597675 | from googleplaces import GooglePlaces
from config import GOOGLE_API_KEY
from logic.nearby_util import address_to_latlng
class NearbySearchGoogle(object):
def __init__(self):
self.google_places = GooglePlaces(GOOGLE_API_KEY)
def find_nearby_places(self, search_keyword, address):
nearby_places... | gkeswani92/live-review-places | logic/google_places/nearby.py | nearby.py | py | 1,068 | python | en | code | 1 | github-code | 50 |
13722078540 | import sys
import os
sys.path.insert(
0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src"))
)
import torch
import torch.nn.functional as F
import numpy as np
import imageio
import util
import warnings
from data import get_split_dataset
from render import NeRFRenderer
from model import make_mode... | omniobject3d/OmniObject3D | benchmarks/sparse_view_reconstruction/_pixelnerf/eval/gen_results.py | gen_results.py | py | 11,388 | python | en | code | 365 | github-code | 50 |
38942092957 | from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from evalcompsite.models import Application, Apartment, House, Land, Comment
# Create your views here.
def home (request):
comments_list = Comment.objects.order_by('-id')[:10]
return render(request, 'hom... | Ant1Hero3/Evalcompsite | mysite/apps/evalcompsite/views.py | views.py | py | 1,600 | python | en | code | 0 | github-code | 50 |
2497937870 | import pco
import cv2
# Start a live preview
CONFIGURATION = {
'exposure time': 10e-3,
'delay time': 0,
'roi': (0, 0, 2048, 2048),
'timestamp': 'ascii',
'pixel rate': 100_000_000,
'trigger': 'auto sequence',
'acquire': 'auto',
'noise filter': 'on',
'metadata': 'on',
'binning': (... | asoronow/py-isi | camera.py | camera.py | py | 1,289 | python | en | code | 0 | github-code | 50 |
26536310566 | import requests
from bs4 import BeautifulSoup
import csv
import os
topics = ["love","inspirational","life","humor","books","reading","friendship","friends","truth"]
for topic in topics:
url = requests.get(f"http://quotes.toscrape.com/tag/{topic}")
quotes_deatils=[]
def main(url):
src = url.content
... | nourmuhammed20/Web_Scrapping | Beautiful Soup/QuotesScrapper/Quotes_Scrapping.py | Quotes_Scrapping.py | py | 1,262 | python | en | code | 0 | github-code | 50 |
19502019669 | from abc import ABC, abstractmethod
from random import shuffle
import tensorflow as tf
from core.Log import log
from datasets import DataKeys
from datasets.Augmentors import parse_augmentors
from datasets.Resize import resize, ResizeMode, jointly_resize
from datasets.util.BoundingBox import encode_bbox_as_mask, get_b... | VisualComputingInstitute/TrackR-CNN | datasets/Dataset.py | Dataset.py | py | 14,251 | python | en | code | 511 | github-code | 50 |
24088044734 | # Tutorial - Detect and Recognize Car License Plates Using Python
#
# First, you need to install Tesseract OCR on your Mac or PC
# On Mac: brew install tesseract
#
# Path to tesseract on Mac:
# /opt/homebrew/Cellar/tesseract/5.3.0/bin/tesseract
#
# pip install OpenCV-Python
# You will use this library for preprocessing... | wacastel/python-license-reader | license_reader.py | license_reader.py | py | 3,576 | python | en | code | 0 | github-code | 50 |
1436741061 | import asyncio
class B(object):
def __init__(self):
self._value = 0
def value(self):
return self._value
class Counter1(B):
async def add(self):
value = self._value + 1
asyncio.sleep(1)
self._value = value
class Counter2(B):
async def add(self):
self... | YuanXianguo/Python-IT-Heima | 网络编程/3、多任务编程/07协程/asyncio_demo/anheng.py | anheng.py | py | 729 | python | en | code | 1 | github-code | 50 |
34524954211 | # with open('file/pi_digits.txt') as file_object:
# contents=file_object.read()
# print(contents)
filename = '/Users/zhanghao/code/py-workspace/file_ReadOrWrite/pi_digits.txt'
#read row by row
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
print('----------------... | zhanghao-esrichina/bigdata-project | basic_grammar/file_ReadOrWrite/file_reader.py | file_reader.py | py | 429 | python | en | code | 0 | github-code | 50 |
15250899768 | import os
from googletest.test import gtest_test_utils
# Command to run the googletest-shuffle-test_ program.
COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-shuffle-test_')
# The environment variables for test sharding.
TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'
SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX... | google/googletest | googletest/test/googletest-shuffle-test.py | googletest-shuffle-test.py | py | 11,108 | python | en | code | 31,518 | github-code | 50 |
20755137339 | #!/usr/env/bin python3
# Importing modules
from difflib import Match
from xml.dom import UserDataHandler
import cv2
from cv2 import RANSAC
from matplotlib.pyplot import axis
import numpy as np
import math
import os
from tqdm import tqdm
from scipy import ndimage as ndi
from skimage.feature import peak_local_max, corne... | tanujthakkar/MyAutoPano | Phase1/Code/MyAutoPano.py | MyAutoPano.py | py | 19,697 | python | en | code | 2 | github-code | 50 |
21303784439 | from post_traitement_function import *
#####################################
#Fin des fonctions
#####################################
#chemin d'accès aux fichiers résultats
"""
Cette fonction permet de récuéperer toutes les informations utiles
au post traitement
"""
OptionTrace, OptionMultiTrace, chemin_multi_trace,... | Raphael-Bouchard/etude_granulo | Post_Traitement/posttraitement.py | posttraitement.py | py | 4,121 | python | fr | code | 0 | github-code | 50 |
14875311132 | import abc
import importlib
class Plugins(abc.ABCMeta):
plugins = dict()
def __new__(metaclass, name, bases, namespace):
cls = abc.ABCMeta.__new__(metaclass, name, bases, namespace)
if isinstance(cls.name, str):
metaclass.plugins[cls.name] = cls
return cls
@classmet... | worasit/python-learning | mastering/metaclasses/automatically_registering_a_plugin_system.py | automatically_registering_a_plugin_system.py | py | 812 | python | en | code | 0 | github-code | 50 |
22715176363 | from tkinter import *
from tkinter.font import Font
from PIL import ImageTk, Image # type: ignore
from bot_module import *
import selenium
import time
import sys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support impor... | Ygor-J/bot_whatsapp | gui.py | gui.py | py | 5,846 | python | pt | code | 0 | github-code | 50 |
74541406236 | from string import ascii_lowercase # 알파벳 소문자들
n = int(input()) # 단어의 개수
cnt = 0 # 그룹 단어의 갯수를 세는 변수
for i in range(n):
s = input() # 단어
j = 0 # s 문자열의 인덱스를 위한 변수
alpha_list = list(ascii_lowercase) # 알파벳 소문자들의 리스트
while j < len(s):
if s[j] in alpha_list:
alpha = s[j] # s[j]의 문자를 변수에... | chlgksdbs/Baekjoon-Online-Judge | Python/단계별로 풀어보기/06. 문자열/[1316] 그룹 단어 체커.py | [1316] 그룹 단어 체커.py | py | 1,196 | python | ko | code | 0 | github-code | 50 |
28545062693 | from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView
)
from . import views
# using namespace to avoid url name confilt
app_name = 'blog'
urlpatterns = [
path('', views.index, name='homepage'),
... | PhurbaGyalzen/THE-XLOG | blog/urls.py | urls.py | py | 760 | python | en | code | 1 | github-code | 50 |
32770875146 | import os, sys, re
if len(sys.argv) < 3:
print('python "file_path" "pattern"')
exit(0)
with open(sys.argv[1], 'r', encoding='utf-8') as f:
for line in f.readlines():
if re.search(sys.argv[2], line):
if line[-1] == '\n':
line = line[:-1]
if line[-2:] == " {":... | tanght1994/helptanght | get_go_func_name.py | get_go_func_name.py | py | 377 | python | en | code | 0 | github-code | 50 |
2481999619 | from modules import Json
from datetime import timedelta, timezone, time
from logging import getLevelName, Logger
from os.path import isfile
from pydantic import BaseModel, Field, validator
from typing import Union, Optional
unique_key_list = []
# CRITICAL
# ERROR
# WARNING
# INFO
# DEBUG
# NOTSET
class LoggingConfig(... | AloneAlongLife/ARK-Server-Manager-Plus_3.0 | configs/config.py | config.py | py | 7,800 | python | en | code | 2 | github-code | 50 |
21381824031 | from ReadData import *
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
from sklearn.metrics import accuracy_score
x_train, y_train = readCSVData('data_final2.csv')
x_test, y_test = readTXTData('train.txt')
x_train = x_train + x_test[:450]
y_train = y_train + y_test[:450]
... | VuHoangvn/Nhap-mon-hoc-may | train/tfidf_linearSVM.py | tfidf_linearSVM.py | py | 758 | python | en | code | 0 | github-code | 50 |
24650671602 | def chop(lst):
del lst[0]
del lst[-1]
def middle(lst):
list_changer = lst[1:]
del list_changer[-1]
return list_changer
first_list = [1, 2, 3, 4]
second_list = [1, 2, 3, 4]
chopped_list = chop(first_list)
print(first_list)
print(chopped_list)
mid_list = middle(second_list)
print(... | XEvan-WiseX/CIS-104 | module 8/08_01/ex_08_01.py | ex_08_01.py | py | 353 | python | en | code | 0 | github-code | 50 |
27592687058 | import common.input as input
import algorithm.lightweight.coreset as alc
import common.utils as utils
import matplotlib.pyplot as plt
import numpy as np
import statistics
from sklearn.cluster import KMeans
data = input.parse_txt("dataset/s-set/s3.txt")
opt = input.parse_txt("dataset/s-set/s3-label.pa")
centers = inpu... | piotrhm/coreset | example.py | example.py | py | 1,397 | python | en | code | 2 | github-code | 50 |
25314326878 |
# For testing.
#
# Concept: This module allows to trigger abnormal situations, to test the reaction of the software ("fault insertion testing").
# In the place in the software, where the fault shall be injected, add a condition like
# if (testsuite_faultinjection_is_triggered(TC_MY_TESTCASE_FOR_SOMETHING)):
# ... | uhi22/pyPLC | mytestsuite.py | mytestsuite.py | py | 11,226 | python | en | code | 66 | github-code | 50 |
75122449436 | def BubbleSort(list):
# loop of [len(list)-1] times
for i in range(0,len(list)-1):
# will be changed to False later if swapping occurs
noSwap = True
# loop of [len(list)-1-i] times
for j in range(0,len(list)-i-1):
# swap
if list[j] > list[j+1]:
... | amiralishd/Data-Structures-and-Algorithms | Sorting/BuubleSort.py | BuubleSort.py | py | 699 | python | en | code | 0 | github-code | 50 |
19425085749 | # implementation of disjoint-set data structure (very efficient!)
# each "set" is a tree, and the "set representative" is the tree root
# hence, two nodes are in the same set if root(u) == root(v)
# initially, everything is in its own set. hence parent(node) = node
parent = range(nn)
size = [1]*nn
# to find the r... | navkrishna21/my-algorithm-data-structure-code-snippets | DSU/DSU_implementation.py | DSU_implementation.py | py | 1,184 | python | en | code | 1 | github-code | 50 |
26666624970 | import yaml
import pytest
from pycheron.callPycheronMetric import callPycheron
from pycheron.db.sqllite_db import Database
def load_config_file(config_file):
with open(config_file, "r") as ymlfile:
cfg = yaml.load(ymlfile)
return cfg
def ensure_config_values(config):
for key, val in list(config.... | sandialabs/pycheron | pycheron/test_callPycheronMetric/test_callPycheronMetric.py | test_callPycheronMetric.py | py | 5,805 | python | en | code | 20 | github-code | 50 |
41224875379 | highest = 0
lowest = 1000000
arr = [567,123,76541,2123]
for i in range(len(arr)):
if arr[i] > highest:
highest = arr[i]
if arr[i] < lowest:
lowest = arr[i]
print(highest)
print(lowest)
| jchh1998/practical-2 | q4.py | q4.py | py | 221 | python | en | code | 0 | github-code | 50 |
17945819781 |
from django.urls import path, re_path
from . import views
urlpatterns = [
path('login/', views.LoginPage, name = "login"),
path('logout/', views.LogoutUser, name = "logout"),
path('register/', views.RegisterUser, name = "register"),
path('', views.home, name = "home"),
] | DevSheila/DonationsPlatform | Donor_Login_Register/urls.py | urls.py | py | 295 | python | en | code | 2 | github-code | 50 |
16164109080 | from math import floor
from os import sep
with open(f'inputs{sep}day_1.txt') as rf: components = [int(l) for l in rf.readlines()]
def fuel_from_mass(mass):
return floor(mass / 3) - 2
def fuel_for_mass_including_fuel(mass):
fuel = fuel_from_mass(mass)
fuel_extra = fuel
while fuel_extra >= 0:
f... | Nathansbud/AdventOfCode | 2019/day_1.py | day_1.py | py | 568 | python | en | code | 1 | github-code | 50 |
23360340548 | #給過但會超時,因為此方法為以C++為底來設想的方法
n=int(input())
grid=[2]
for i in range(3,40000,2):
check=1
for j in range(3,int(i**0.5)+1):
if i%j==0:
check=0
break
if check:
grid.append(i)
for i in range(n):
ans=[1,1]
s,e=map(int,input().split())
for j in range(s,e+1):
... | Fergus4506/Mid1_2 | DS_pr/UVA200-299/UVA294_CO.py | UVA294_CO.py | py | 2,085 | python | en | code | 0 | github-code | 50 |
641907812 | #!/usr/bin/python3
import sys
import signal
# Dictionary to store status code counts
status_code_counts = {
200: 0,
301: 0,
400: 0,
401: 0,
403: 0,
404: 0,
405: 0,
500: 0,
}
# Variables to keep track of total file size and line count
total_file_size = 0
line_count = 0
def print_statis... | Butawantemi/alx-higher_level_programming | 0x0B-python-input_output/101-stats.py | 101-stats.py | py | 1,463 | python | en | code | 0 | github-code | 50 |
6991513011 | from . import pluginbase
from . import transport
from twisted.internet import reactor
from twisted.python import log
import sys
def main():
if len(sys.argv) < 2:
print("Usage: %s <config dir>" % sys.argv[0])
sys.exit(1)
transportobj = transport.Transport()
boss = pluginbase.PluginBoss(sys... | brownan/abbott | abbott/entrypt.py | entrypt.py | py | 609 | python | en | code | 9 | github-code | 50 |
42693432422 |
class VRPSolution():
def __init__(self) -> None:
self.objVal = 0
self.vehicleNum = 0
self.pathSet = {}
self.solSet = {}
self.distance = {}
self.travelTime = {}
self.totalLoad = {}
self.pathNum = []
class SPPSolution():
def __i... | clare1456/RL-for-CS | CG_test/solution.py | solution.py | py | 676 | python | en | code | 0 | github-code | 50 |
31038894475 | def add_time(start, duration, show_day = None):
def landing_day(day, days_later) :
# --- When show_day != None this function traverses the list of days and lands on target day
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
day = day.lower(); day = day.... | Packetouille/FCC_Python | Time Calculator/time_calculator.py | time_calculator.py | py | 2,038 | python | en | code | 0 | github-code | 50 |
17439690818 | from functools import partial
from django.db.models import query
from django.db.models.query import QuerySet
from requests.api import request
from rest_framework.decorators import action, authentication_classes
from rest_framework.mixins import ListModelMixin
from rest_framework.response import Response
from rest_frame... | GarnBarn/garnbarn-backend | garnbarn_api/views.py | views.py | py | 12,945 | python | en | code | 0 | github-code | 50 |
39372159355 | import random
from typing import Union
import pandas as pd
from .data_handler import get_interacted_products, DataHandler
from .models import PopularityBasedRecommender, ContentBasedRecommender
from .config import SEED, \
EVAL_RANDOM_SAMPLE_NON_INTERACTED_ITEMS
def hit_top_n(product_id: int, recommended_product... | justleon/IUM-Recommendation-Tool | recommender/model_evaluator.py | model_evaluator.py | py | 3,511 | python | en | code | 0 | github-code | 50 |
42577385818 | '''
FOR PIECES IS QUICKER THAN
'''
class Solution(object):
def licenseKeyFormatting(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
S=list(S.replace("-", "").upper())
ans=[]
a=0
upper = len(S)
lower = len(S)-K
if len... | RamonRomeroQro/ProgrammingPractice | code/LISCENCEKEY.py | LISCENCEKEY.py | py | 708 | python | en | code | 1 | github-code | 50 |
42680711409 | def pgcd(a,b):
if b == 0:
return a
else:
r = a % b
return pgcd(b,r)
def ppcm(a,b):
d = pgcd(a,b)
return int(a*b / d)
p = 1
for i in range(20):
p = ppcm(p,i+1)
print(p)
| IThinkThereforeISuffer/ProjectEuler | Problem005.py | Problem005.py | py | 180 | python | en | code | 0 | github-code | 50 |
28569552447 | def max_subarray_sum(arr, window_size):
left = 0
right = window_size - 1
# Calculate the initial sum
# slicing is inclusive of 'left' index and exclusive of the 'right+1' index
max_sum = sum(arr[left:right + 1])
current_sum = max_sum
# Slide the window
while right < len(arr) ... | aakashmanjrekar11/leetcode | 3. Sliding Window/MaxSubarray.py | MaxSubarray.py | py | 1,013 | python | en | code | 0 | github-code | 50 |
25192975718 | import magma
import coreir
_cache = None
def CoreIRContext(reset=False) -> coreir.Context:
global _cache
if not reset and _cache is not None:
return _cache
if reset:
magma.frontend.coreir_.ResetCoreIR()
c = magma.backend.coreir.coreir_runtime.coreir_context()
if reset:
c.loa... | rdaly525/MetaMapper | metamapper/__init__.py | __init__.py | py | 376 | python | en | code | 4 | github-code | 50 |
30332519273 |
def plot_carpet_ts(timeseries, modules, atlas=None, background_file=None, nskip=0, size=(950, 800),
subplot=None, title=None, output_file="regts.png"):
"""
Adapted from: https://github.com/poldracklab/niworkflows
Plot an image representation of voxel intensities across time also know
... | spisakt/PUMI | plot/timeseries.py | timeseries.py | py | 5,187 | python | en | code | 4 | github-code | 50 |
2864635986 | import turtle, random, time
def polygon(sides, length, color):
turtle.penup()
if sides == 4:
turtle.setposition(-length/2, -length/2)
elif sides == 3:
turtle.setposition(-(length/2), -(length/4*(3**(1/2))))
else:
turtle.setposition(-length/2, -length/2)
turtle.pendown()
t... | mehmetcoban13/deneme | deneme3.py | deneme3.py | py | 783 | python | en | code | 0 | github-code | 50 |
8361252944 | import argparse
import json
import sys
"""
Tries to link within a datacrate by looking for value that reference a known
title or name
"""
parser = argparse.ArgumentParser()
parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), default=sys.stdin)
parser.add_argument(
"outfile", nargs="?", type=argp... | UTS-eResearch/omeka-datacrate-tools | doctor_datacrate.py | doctor_datacrate.py | py | 2,735 | python | en | code | 1 | github-code | 50 |
37386530480 | from typing import List, Optional
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.crud.base import CRUDBase
from app.models.charity_project import CharityProject
class CRUDCharityProject(CRUDBase):
async def get_charity_project_by_name(
self,
chari... | MrGorkiy/QRkot_spreadsheets | app/crud/charity_project.py | charity_project.py | py | 1,105 | python | en | code | 0 | github-code | 50 |
11234697527 | import logging
import time
from selenium import webdriver
from selenium.common.exceptions import *
from reali_web.base_action import base_actions_data
from reali_web.consumer_pages.sign.sign_in import sign_in_page
from reali_web.consumer_pages.buy.homes import homes_page
ba = base_actions_data
si = sign_in_page.SignI... | ErezShamay/WebAutomation | base_action/base_actions.py | base_actions.py | py | 3,541 | python | en | code | 0 | github-code | 50 |
22033385109 | import ontoload as oL
# appends to a file the initial network map
def writeMap(fileString, networkMap):
# opens the file object to append
f = open(fileString, "a")
for i in range(networkMap.arrayYSize):
for j in range(networkMap.arrayXSize):
f.write(networkMap.modArray[i][j].nam... | atomicdork/FinalProject | inputMain.py | inputMain.py | py | 1,970 | python | en | code | 0 | github-code | 50 |
3040956 | def insertion_sort(l):
for i in range(1,len(l)):
pos=i
curr_ele=l[i]
while curr_ele<l[pos-1] and pos>0:
l[pos]=l[pos-1]
pos=pos-1
l[pos]=curr_ele
l=list(map(int,input().split()))
insertion_sort(l)
print(l)
| Indu1115/Searchings-and-Sortings | insertion_sort.py | insertion_sort.py | py | 241 | python | en | code | 0 | github-code | 50 |
3638274714 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 9 06:13:31 2019
@author: lthpkh@umsystem.edu
"""
import sys
import os
import random
import collections
import operator
from collections import OrderedDict
import re, copy, pyperclip, simpleSubCipher, wordPatterns, makeWordPatterns
nonLettersOrSpac... | liemthanhho/FS2019Security | pa02/betterSubCrack.py | betterSubCrack.py | py | 18,650 | python | en | code | 0 | github-code | 50 |
16397307831 | import pandas as pd
from sqlalchemy import create_engine
db_uri = 'mysql+pymysql://root:Cooperboy0071985@localhost/mysql7'
engine = create_engine(db_uri, echo=False) # enter your password and database names here
df = pd.read_csv('C:\Absenteeism_predictions2.csv',sep=',',quotechar='\'',encoding='utf8')
print(df)
sa... | rocooper7/6.CodFac | 1.ORM_MySQL/alchemysql/Ejemplos_Simples/carga_simple.py | carga_simple.py | py | 638 | python | en | code | 0 | github-code | 50 |
73085357595 | from ariadne import MutationType
from api.models import *
from api.types import *
import io
from api.models.pytorch import *
import soundfile as sf
import numpy as np
mutation = MutationType()
@mutation.field("classifyHeatBeatSound")
async def create_session_resolver(obj, info, input):
try:
ext = "."+str(i... | CrispenGari/HBSC | server/api/resolvers/mutations/__init__.py | __init__.py | py | 1,237 | python | en | code | 2 | github-code | 50 |
6956852359 | #removeAndSaveListElements.py
list1 = ["red", "blue", "orange", "black", "white", "golden"]
list2 = ["nose", "ice", "fire", "cat", "mouse", "dog"]
print("lists before deletion: ")
len_list1 = len(list1)
len_list2 = len(list2)
if len_list1 == len_list2:
for i in range(len_list1):
print(list1[i], "\t", list... | MattKrepp1/Econ-411 | Learn-Python-for-Stats-and-Econ-master/In Class Projects/In Class Examples Spring 2019/Section 2/removeAndSaveListElements.py | removeAndSaveListElements.py | py | 692 | python | en | code | 0 | github-code | 50 |
30980467641 | import os
import zipfile
from .preprocessor import Preprocessor
class ZipFeedback(Preprocessor):
def __init__(self):
super(ZipFeedback, self).__init__()
def preprocess(self, path, resources):
self.feedback_zip = os.path.split(resources['feedback_zip'])[-1]
self.src = path... | DigiKlausur/ilias2nbgrader | ilias2nbgrader/preprocessors/zipfeedback.py | zipfeedback.py | py | 798 | python | en | code | 2 | github-code | 50 |
17149426371 | from concurrent.futures import ProcessPoolExecutor
import sys
import numpy as np
from pycocotools.cocoeval import COCOeval
import torch
import torch.distributed as dist
import utils
from dataloaders.dataloader import create_eval_dataloader
from dataloaders.prefetcher import eval_prefetcher
import config
from box_co... | Deep-Spark/DeepSparkHub | cv/detection/ssd/pytorch/base/train/evaluator.py | evaluator.py | py | 4,399 | python | en | code | 28 | github-code | 50 |
589528131 | def findsumofdiv(n):
teiler = []
summe = 0
for i in range(1, n):
if n % i == 0:
teiler.append(i)
for i in range(len(teiler)):
summe += teiler[i]
return summe
def amicable_numbers(eingabe):
numbers = []
for j in range(1, eingabe):
x = findsumofdiv(j)
... | h3Nn35/ProjectEuler | 21 Amicable_Numbers/Amicable_Numbers.py | Amicable_Numbers.py | py | 525 | python | de | code | 0 | github-code | 50 |
35705183638 | import networkx as nx
import matplotlib.pyplot as plt
from random import randint, randrange, shuffle
class GraphGen:
BORNEMIN = 1
BORNEMAX = 10
def __init__(self, min, max):
"""Class generator"""
self.BORNEMIN = min
self.BORNEMAX = max
#Generation for test purposes
def ge... | thomasbarrepitous/Dijkstra_Example | generation.py | generation.py | py | 2,768 | python | en | code | 0 | github-code | 50 |
15974308023 | from pathGenerator import *
class BFS:
x_cord = [0, 1, 0, -1]
y_cord = [1, 0, -1, 0]
def __init__(self,matrix, startX, startY,goalX,goalY,grid,n,size):
self.grid = grid
self.x = startX
self.y = startY
self.goal_x = goalX
self.goal_y = goalY
self.matrix = matri... | pranjalvithlani/maze-runner | BFS.py | BFS.py | py | 1,355 | python | en | code | 1 | github-code | 50 |
23952412165 | def example(Simulator):
from csdl import Model, GraphRepresentation
class ExampleImplicit2(Model):
def initialize(self):
self.parameters.declare('nlsolver')
def define(self):
# define internal model that defines a residual
from csdl import ... | LSDOlab/csdl | csdl/examples/valid/ex_promotions_implicit2.py | ex_promotions_implicit2.py | py | 3,010 | python | en | code | 5 | github-code | 50 |
72051187675 | import requests
import pandas as pd
def fetch_bitcoin_data(api_key):
url = f'https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_DAILY&symbol=BTC&market=USD&apikey={api_key}'
response = requests.get(url)
data = response.json()
# Process the JSON data into a pandas DataFrame
df = pd.DataFr... | stenuuesoo/beatifulbtc | main.py | main.py | py | 933 | python | en | code | 0 | github-code | 50 |
18727133010 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
execute operations between columns and save in a given column
"""
import my_functions as mf
import numpy as np
import pandas as pd
import re
def parse(argv):
"""
This function accept a list of strings, create and fill a parser istance
and return a populated n... | montefra/montefra_PhD_Python | Catalogues/columns_operations.py | columns_operations.py | py | 6,883 | python | en | code | 0 | github-code | 50 |
4639108049 | from typing import Callable, Optional, Sequence, Tuple, Union, overload
from faker import Faker
from faker.generator import Generator
from faker.providers import BaseProvider
from faker.providers.python import Provider
from ..base import DEFAULT_FORMAT_FUNC, BytesValue, FileMixin, StringValue
from ..registry import F... | barseghyanartur/faker-file | src/faker_file/providers/csv_file.py | csv_file.py | py | 6,214 | python | en | code | 74 | github-code | 50 |
33187085436 | #!/usr/bin/python
# coding=utf-8
import sys
import random
from PyQt4 import QtGui,QtCore
from math import *
class GameWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setWindowTitle('24 point game')
self.resize(400, 250)
self... | wuxx/python | 24_point_game/24_point.py | 24_point.py | py | 8,304 | python | en | code | 1 | github-code | 50 |
24360907604 | from typing import Any
start_id_number = 1
last_id_number = 151
stats = ['id', 'height', 'weight']
def get_stats():
return stats
def compare(stat_name, user_stat_value, opponent_stat_value):
if user_stat_value > opponent_stat_value:
return [1, user_stat_value]
elif user_stat_value... | angelRep/CFG-Python-Project | cfg-python-project/pokemon.py | pokemon.py | py | 1,147 | python | en | code | 0 | github-code | 50 |
5164596817 | valor = int(input('Valor a ser sacado: R$'))
total = valor
ced = 50 # comeca com a cedula de 50
totced = 0
while True:
if total >= ced: # se o saque estiver maior que a cedula de 50
total = total - ced # subtrair uma nota de 50 do montante
totced = totced + 1 # somar +1 ao total de cedul... | GabrielBrotas/Python | modulo 2/Exercicios/Ex071.2 - Caixa eletronico.py | Ex071.2 - Caixa eletronico.py | py | 899 | python | pt | code | 0 | github-code | 50 |
34416853907 | import logging
import numpy as np
from abcpy.backends import BackendDummy as Backend
from abcpy.continuousmodels import Uniform
# from abcpy.backends import BackendMPI as Backend # to use MPI
from abcpy.distances import Euclidean
from abcpy.output import Journal
from src.distance import WeightedDistance
from src.mod... | OptimalLockdown/MobilitySEIRD-England | inference_SEI4RD_england_data.py | inference_SEI4RD_england_data.py | py | 8,689 | python | en | code | 2 | github-code | 50 |
37152546209 | #########################################################################
# Dusi's Thesis #
# Algorithmic Discrimination and Natural Language Processing Techniques #
#########################################################################
# This experiment compu... | MicheleDusi/AlgorithmicDiscrimination_MasterThesis | src/experiments/mlm_gender_perplexity.py | mlm_gender_perplexity.py | py | 6,127 | python | en | code | 0 | github-code | 50 |
12408247569 | import fractions
A, B, C, D = map(int, input().split())
def lcm(x, y):
return (x * y) // fractions.gcd(x, y)
LCM_CD = lcm(C, D)
C_Count = B // C - A // C
D_Count = B // D - A // D
CD_Count = B // (LCM_CD) - A // (LCM_CD)
print(C_Count, D_Count, CD_Count)
print(B - A + 1 - C_Count - D_Count + CD_Count)
| ritzcr/AtCoder | practice/abc131_c.py | abc131_c.py | py | 313 | python | en | code | 0 | github-code | 50 |
39098615988 | """
1.6 - String Compression: Implement a method to perform basic string compression using the
counts of repeated characters. For example, the sxtring aabcccccaaa would become a2b1c5a3. If
the "compressed" string would not become smaller than the original string, your method should
return the original string. You ca... | jonahb13/cracking-the-coding-interview | solutions/ch1_arrays_and_strings/1_6.py | 1_6.py | py | 1,170 | python | en | code | 0 | github-code | 50 |
28612035618 | import torch
import torch.optim as optim
import matplotlib.pyplot as plt
from data import get_dataloader
from model import EncoderAndDecoder
from train import train_model
from infer import get_private_pred
train_dataloader, valid_dataloader = get_dataloader()
model = EncoderAndDecoder()
device = torch.device("cuda:0... | Hyonchori/CONTESTS | 북극 해빙예측 AI 경진대회/main.py | main.py | py | 1,163 | python | en | code | 2 | github-code | 50 |
8015886566 | import math
operations = {
'(': -1,
')': 1,
'+': 2,
'-': 2,
'*': 3,
'/': 3,
'^': 4
}
def is_sign(ch: chr) -> bool:
return ch in operations.keys()
def is_bracket(ch: chr) -> bool:
return ch == '(' or ch == ')'
def is_num(ch: chr) -> bool:
return ch in '0123456789.'
def pr... | JoreKut/gui-plotter | util/service/calculator.py | calculator.py | py | 3,587 | python | en | code | 0 | github-code | 50 |
132330470 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 24 12:14:25 2020
@author: paulg
"""
"""
Created on Fri Jun 12 16:23:42 2020
@author: paulg
"""
import pyrealsense2 as rs
import numpy as np
import cv2
import imutils
from skimage.measure import compare_ssim
############################################... | pgredigui/recycleye | object_size/depth_combined_methods2.py | depth_combined_methods2.py | py | 13,337 | python | en | code | 0 | github-code | 50 |
11042381240 | import pygame
from settings import *
from tile import Tile
from player import Player
from debug import debug
from filereader import import_csv_layout
from weapon import weapon
from ui import UI
class Level:
def __init__(self):
self.display_surface=pygame.display.get_surface()
#sprite gr... | NadirAli1403/TreasureHuntOOP | level.py | level.py | py | 4,476 | python | en | code | 0 | github-code | 50 |
22385220928 | from solfege.lib.pattern import Scale
IONIAN = Scale(
[2, 2, 1, 2, 2, 2, 1],
"ionian"
)
ionian = IONIAN
dorian = IONIAN.mode(1, 'dorian')
phrygian = IONIAN.mode(2, 'phrygian')
lydian = IONIAN.mode(3, 'lydian')
mixolydian = IONIAN.mode(4, 'mixolydian')
aeolian = IONIAN.mode(5, 'aeolian')
locrian = IONIAN.mode(... | pvarsh/solfege | solfege/exercises/scales.py | scales.py | py | 689 | python | en | code | 0 | github-code | 50 |
28215338548 | # -*- coding: utf-8 -*-
from odoo import models, fields, api
class Visita(models.Model):
_name = 'hospital.visita'
_rec_name = 'data'
data = fields.Date(required=True)
# MANY TO ONE
historial_id = fields.Many2one('hospital.historial', ondelete='cascade', string='Historial', required=True)
... | unexpectedprojectz/hospital | models/model_visita.py | model_visita.py | py | 1,654 | python | en | code | 0 | github-code | 50 |
40229712570 | import FWCore.ParameterSet.Config as cms
CfgNavigationSchoolESProducer = cms.ESProducer("CfgNavigationSchoolESProducer",
ComponentName = cms.string('CfgNavigationSchool'),
SimpleMagneticField = cms.string(''),
# ... | cms-sw/cmssw | RecoTracker/TkNavigation/python/CfgNavigationSchool_cfi.py | CfgNavigationSchool_cfi.py | py | 956 | python | en | code | 985 | github-code | 50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.