seq_id stringlengths 7 11 | text stringlengths 156 1.7M | repo_name stringlengths 7 125 | sub_path stringlengths 4 132 | file_name stringlengths 4 77 | file_ext stringclasses 6
values | file_size_in_byte int64 156 1.7M | program_lang stringclasses 1
value | lang stringclasses 38
values | doc_type stringclasses 1
value | stars int64 0 24.2k ⌀ | dataset stringclasses 1
value | pt stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
22634264076 |
side=[]
for x in range(0,3):
a=int(input(f"Enter side{x+1}: "))
side.append(a)
if side[2]+side[1]>side[0] and side[0]+side[2]>side[1] and side[0]+side[1]>side[2]:
print("This is a Prefect Triangle")
else:
print("Thius is Not a triangle")
| arironman/MSU-Python | ex-7/25.py | 25.py | py | 270 | python | en | code | 0 | github-code | 6 |
34215736207 | import logging
import os
import gzip
import filetype
import multiprocessing as mp
import pandas as pd
from moonstone.normalization.reads.read_downsize import DownsizePair
logger = logging.getLogger(__name__)
def pair_up(seq_files_info):
paired_list = []
query = None
for key in seq_files_info:
if... | motleystate/moonstone | moonstone/normalization/reads/downsize_dir.py | downsize_dir.py | py | 7,336 | python | en | code | 0 | github-code | 6 |
12153147067 | import matplotlib.pyplot as plt
import numpy as np
with open('scores.txt', 'r') as f:
scores = f.read().splitlines()
scores = list(map(int, scores))
mean = []
max_list = []
for i,j in enumerate(scores):
if i % 1000 == 0:
mean.append(np.average(scores[i:i+1000]))
max... | Mike-Teng/Deep_Learning | lab/lab2/plot.py | plot.py | py | 798 | python | en | code | 0 | github-code | 6 |
29188042884 | """
Problem Statement
A zero-indexed array A of length N contains all integers from 0 to N-1.
Find and return the longest length of set S,
where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below.
Suppose the first element in S starts with the selection of element A[i]
of index = i, the next e... | walterjgsp/algorithms | Python/problems/problem_0008_array_nesting.py | problem_0008_array_nesting.py | py | 1,388 | python | en | code | 6 | github-code | 6 |
31734423723 | import sqlite3
class sqlcommands:
def Open(self):
if self.bOpen is False:
self.conn = sqlite3.connect(self.db)
self.curs = self.conn.cursor()
self.bOpen = True
return True
def __init__(self, table):
self.db = './~newsqlcommands.sqlt3'
s... | Loondas/PythonGameTimer | GameTimer/cgi-bin/newsqlcommands.py | newsqlcommands.py | py | 4,718 | python | en | code | 0 | github-code | 6 |
72652196027 | from Core import Core
class IN:
def __init__(self):
self.identifier = ""
def parse(self, S): #should not output anything unless error case
if S.currentToken() == Core.INPUT:
S.nextToken()
else:
print("ERROR: Token should be 'input'")
quit()
... | hm0416/CSE-3341 | Project1/IN.py | IN.py | py | 768 | python | en | code | 1 | github-code | 6 |
27413490238 |
def reversedInt(num: int) -> int:
result = 0
while num:
lastDigit = num % 10
result = result * 10 + lastDigit
if result < -2 ** 31 or result > 2 ** 31:
return 0
num //=10
return result
print(reversedInt(1534236469))
print(reversedInt(2147483641)) | irvandindaprakoso/online-test-py | LeetCode/reverseInt.py | reverseInt.py | py | 316 | python | en | code | 0 | github-code | 6 |
28888632365 | import sys
import os
import subprocess
#### SETTINGS ####
CC = "gcc"
DEFAULT_INCLUDES = [
"stdio.h",
"stdbool.h",
"stdlib.h",
"unistd.h",
"string.h",
]
TRY_USE_BAT = True
#### -------- ####
# This marker is used to remove any included code from the output,
# and only display the expanded macros given as the... | mrchip42k/preprocessor-util | preproc.py | preproc.py | py | 2,139 | python | en | code | 0 | github-code | 6 |
21550234357 | #!/usr/bin/env python3
"""
Main file for program
"""
import parser, sys, setup, functions
import time
FOLDERS = {
"result": "Result",
"finished": "Finished",
"unfinished": "Unfinished",
"video": "Video",
"unsorted": "Unsorted"
}
def main():
"""
Main function.
"""
options = parser.p... | lewenhagen/fileSorter | main.py | main.py | py | 861 | python | en | code | 0 | github-code | 6 |
26213424744 | from hw2.datasets.train import TrainDataset
from hw2.models.base import Model
from hw2.models.catboost_model import CatBoostModel
from hw2.models.embeddings_model import EmbeddingModel
import numpy as np
class CombinedModel(Model):
def __init__(self, loss_function: str, iterations: int, embedding_dim: int,
... | Sushentsev/recommendation-systems | hw2/models/combined_model.py | combined_model.py | py | 1,319 | python | en | code | 0 | github-code | 6 |
19208567957 | '''
Helps the user calculate the price that they should charge the customer
'''
def tax():
#Checks if the user is from ontario or not
location = input("Are you shopping from Ontario? Enter Y or N: ")
#Makes the user input a tax rate if they are not from ontario
if location == "n" or location == "N... | kelvincaoyx/UTEA-PYTHON | Week 2/PythonUnitTwoPractice/shop.py | shop.py | py | 1,160 | python | en | code | 0 | github-code | 6 |
32681042902 | import numpy as np
from .BaseNB import BaseNaiveBayes
# 高斯贝叶斯
class GaussianNaiveBayes(BaseNaiveBayes):
# 训练
def fit(self, X: np.ndarray, y: np.ndarray):
"""
X: train dataset, shape = (n_samples, n_features)
y: target, shape = (n_samples, )
"""
# 计算 y 的先验概率
y_pr... | HuipengXu/Statistical-learning-method | naive_bayes/GaussianNB.py | GaussianNB.py | py | 2,327 | python | en | code | 7 | github-code | 6 |
21884536797 | """Calculate the expected detection rates for apertif."""
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from frbpoppy import CosmicPopulation, Survey, SurveyPopulation, hist
from tests.convenience import plot_aa_style, rel_path
from alpha_real import EXPECTED, poisson_interval
N_DAYS = 1 #... | TRASAL/frbpoppy | tests/rates/apertif_dist.py | apertif_dist.py | py | 2,026 | python | en | code | 26 | github-code | 6 |
6264519181 | import matplotlib.pyplot as plt
class Drawer():
def __init__(self,y_pred, y_test, target_names,X_test,eigenfaces):
self.y_pred=y_pred
self.y_test=y_test
self.target_names=target_names
self.X_test=X_test
self.eigenfaces=eigenfaces
def plot_gallery(self,images, titles, h... | bartekskrabacz/python_project | src/python_project/Drawer.py | Drawer.py | py | 1,774 | python | en | code | 0 | github-code | 6 |
5456868264 | print("\n Bem-vindo ao menu de gerenciamento!\n")
esc = int(input('Digite 1 para criar um ônibus: '))
class Onibus:
def __init__(self, nome, parada, motorista, fiscal):
self.nome = nome
self.parada = parada
self.motorista = motorista
self.fiscal = fiscal
def __str__(se... | nand5a/Entrega-02 | Entrega-02.py | Entrega-02.py | py | 4,204 | python | pt | code | 0 | github-code | 6 |
42168409282 | from typing import List
class Solution:
def optimalArray(self, n : int, ar : List[int]) -> List[int]:
# code here
res = []
half, full = 0, 0
for i in range(n):
full += ar[i]
if i&1:
res.append(full - 2*half)
else:
... | shane-Coder/DailyCode | Optimal Array - GFG/optimal-array.py | optimal-array.py | py | 1,007 | python | en | code | 0 | github-code | 6 |
9224654424 | # Usage
# python scripts/collect_pickle_states.py -i PICKLE_DATA_PATH
import argparse
import numpy as np
import tqdm
import structs
def collect_stats(args):
data = structs.load(args.input_path)
sample_count = []
for key in tqdm.tqdm(data):
sample_count.append(data[key]['rst'].shape[0])
val... | Tsinghua-MARS-Lab/InterSim | simulator/prediction/M2I/guilded_m_pred/scripts/collect_pickle_stats.py | collect_pickle_stats.py | py | 816 | python | en | code | 119 | github-code | 6 |
12950721382 | import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as spy
from . import AstroLib_Basic as AL_BF
################################################################################
# CREATE BODY WITH ITS CHARACTERISTICS
################################################################################... | veronicasaz/AstrodynamicsScripts | AstroLib_2BP.py | AstroLib_2BP.py | py | 26,889 | python | en | code | 1 | github-code | 6 |
42860322967 | #
#
# Font Lato https://fonts.google.com/specimen/Lato
# https://opengameart.org/content/4-chiptunes-adventure
#
# scanlines less mem
## https://www.reddit.com/r/pygame/comments/6yk6zk/least_memory_intensive_way_to_implement_scanlines/
# Not used:
# Audio Voices by MadamVicious (https://freesound.org/people/MadamViciou... | Sprachmensch/wordle_clone | wordle.py | wordle.py | py | 22,197 | python | en | code | 0 | github-code | 6 |
30500996966 | # ---------------------------------J.A.R.V.I.S.----------------------------------
import datetime
import pyttsx3
import speech_recognition as sr
import __name__
import comtypes.client
# -----------------------------------------------------------------------------
engine = pyttsx3.init("sapi5")
voices = engi... | ArcTix-09/codes | python/J.A.R.V.I.S..py | J.A.R.V.I.S..py | py | 1,509 | python | en | code | 1 | github-code | 6 |
8328914063 | from DataInit import *
from AuxiliaryFunctions import *
# Initialize the map of game.
listOfCountries, NACountries, SACountries, CACountries, EUCountries, AFRCountries, ASIACountries, OCECountries = initCountryStruct()
# Initialize the list of possible colors.
listOfColors = ["Green", "Yellow", "Blue", "White"... | MacMullen/TegBOT | main.py | main.py | py | 3,249 | python | en | code | 0 | github-code | 6 |
20921339256 | from clustering_algorithms.spectral_clustering import *
from clustering_algorithms.louvain import *
from clustering_algorithms.paris import *
from dendrogram_manager.homogeneous_cut_slicer import *
from dendrogram_manager.heterogeneous_cut_slicer import *
from dendrogram_manager.distance_slicer import *
from experiment... | sharpenb/Multi-Scale-Modularity-Graph-Clustering | Scripts/ppm_experiments.py | ppm_experiments.py | py | 4,027 | python | en | code | 2 | github-code | 6 |
35903985700 | def carga_numeros(n):
total=int(0)
lista=list()
porcentaje=int(0)
ultimo_digito=int(0)
n_menor=int(0)
menores_7=str("Si")
while n!=0:
total+=1
if n%2==0: porcentaje+=1 # a) Determinar el porcentaje que cantidad de números pares representa en la cantidad total de números ingr... | UrielMaceri/Python-Principiante | guia 5/ejercicio2.py | ejercicio2.py | py | 1,458 | python | es | code | 0 | github-code | 6 |
14365099168 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 17 20:55:15 2020
@author: Emmanuel
"""
def unique(list1):
# intilize a null list
unique_list = []
# traverse for all elements
for x in list1:
# check if exists in unique_list or not
if x not in unique_list:
... | avefenix798/Ejemplos | Buscar Palabra en Query.py | Buscar Palabra en Query.py | py | 677 | python | en | code | 0 | github-code | 6 |
37686877312 | # declare dictionary
banner = {}
# fill dictionary
banner['os'] = 'Ubuntu Server 13.04'
banner['server'] = 'ProFTPd 1.3.4'
banner['up'] = 315.5
banner[200] = 'OK'
print(banner)
# iterate through dictionary
for key, value in banner.items():
print(key, value)
# delete item based on key
del banner['up']
print(... | studiawan/network-programming | bab01/dictionary.py | dictionary.py | py | 327 | python | en | code | 10 | github-code | 6 |
19528126460 | # coding=utf-8
from __future__ import division
from design.MainData import MainData
from canvas import *
from algorithm import *
from PyQt5.QtCore import Qt
from PyQt5.QtGui import (QIcon, QFont)
from PyQt5.QtWidgets import (qApp,
QAction,
QComboBox,
... | zhaicao/pythonWorkspace | Pyqt5Practice/design/app.py | app.py | py | 50,611 | python | en | code | 0 | github-code | 6 |
34199991642 | #!/usr/bin/env python
from PyQt4 import QtGui, QtCore
from item import Item
class DescItem(Item):
def __init__(self, scene, x, y, parent):
self.text = ""
self.scale = 1.0
self.color = QtCore.Qt.gray
self.hover_color = QtCore.Qt.white
super(DescItem, self).__init__(scene... | robofit/arcor | art_projected_gui/src/art_projected_gui/items/desc_item.py | desc_item.py | py | 1,879 | python | en | code | 9 | github-code | 6 |
7552302996 | # Covid Resistant Husky 3 - ADA price prediction
# import pip to install necessary libraries
import math
import pip
pip.main(['install', 'python-binance', 'pandas', 'scikit-learn', 'matplotlib', 'keras', 'tensorflow', 'plotly',
'mplfinance'])
from keras.losses import mean_squared_error
from matplot... | aayushi1903/Cryptocurrency-project | main2.py | main2.py | py | 10,855 | python | en | code | 0 | github-code | 6 |
10881296356 | import unittest
from pathlib import Path
from tests import CdsTestMixin
from . import CDSCase
class DumpTest(CdsTestMixin, unittest.TestCase):
def test_trace_json(self):
with CDSCase(self, self.NAME_LIST, self.TEST_ARCHIVE) as cds:
cds.run_trace('import json')
cds.verify_files(che... | alibaba/code-data-share-for-python | tests/test_cds/test_dump.py | test_dump.py | py | 745 | python | en | code | 38 | github-code | 6 |
30338122797 | from collections import deque
def bfs(graph, start):
queue = deque([start]) #방문할 노드를 넣어두는 곳
visited = [] #방문한 노드들
while queue:
v = queue.popleft()
print(v, end=" ")
if v not in visited:
visited.append(v)
queue += graph[v]
return visited
graph = [
[... | minju7346/CordingTest | bfs_test2.py | bfs_test2.py | py | 472 | python | en | code | 0 | github-code | 6 |
171090943 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from rp_ui_harness import RequestPolicyTestCase
class TestBeforeAllOtherTests(RequestPolicyTestCase):
def test_ge... | RequestPolicyContinued/requestpolicy | tests/marionette/tests-special/test_before_all_other_tests.py | test_before_all_other_tests.py | py | 617 | python | en | code | 253 | github-code | 6 |
74326542907 | import datetime
import jsonlines
# Appends json to a jsonl file
def append_to_jsonl(timeline, file_path):
print("Writing contents to jsonl...")
# Sort major events array by timestamp
sorted_timeline = sorted(timeline, key=lambda event: int(event['date']))
# Pretty print JSON of human datetime
for event in sorte... | jeromechoo/gpt-for-you | helpers/write.py | write.py | py | 618 | python | en | code | 4 | github-code | 6 |
8670584413 | import cv2
import cvzone
from cvzone.PoseModule import PoseDetector
import numpy as np
cap = cv2.VideoCapture(1)
detector = PoseDetector()
per = 0
a1 = 0
color = (0,0,255)
situps = 0
dir = 0
while True:
__ , img = cap.read()
#assert isinstance(img, object)
img = detector.findPose(img)
lmlist, bbox = ... | adirastogi235/PUSH-UP-COUNTER | main.py | main.py | py | 1,392 | python | en | code | 0 | github-code | 6 |
43622986430 | # -*- coding: utf-8 -*-
import html
from gi.repository import Gtk
from mcomix.preferences import config
class MessageDialogRemember(Gtk.MessageDialog):
__slots__ = ('__dialog_id', '__choices', '__remember_checkbox')
def __init__(self):
"""
Creates a dialog window.
"""
supe... | thermitegod/mcomix-lite | mcomix/message_dialog/remember.py | remember.py | py | 2,610 | python | en | code | 2 | github-code | 6 |
37211599965 | import numpy as np
import torch
# # np.argwhere的用法
# a=np.zeros((4,3), dtype=np.uint32)
# b=np.argwhere(np.zeros((4,3), dtype=np.uint32) == 0)
# print(a)
# print(b)
# print(type(b),b.shape)
# # reshape的用法,torch和numpy都有类似的用法
# a = torch.arange(4.)
# print(a.shape)
# a=torch.reshape(a, (2, 2))
# print(a.shape)
# b = to... | hanquansanren/unified_doctransformer | simple_test/unit_test.py | unit_test.py | py | 1,371 | python | en | code | 1 | github-code | 6 |
43581170385 | from django.shortcuts import render
from .models import *
from django.http import HttpResponse
import json
from rest_framework import generics
from .serializers import *
# Create your views here.
def dashboard(request):
return render(request,"dashboard.html")
def department(request):
#department_list = Depart... | sanjaymehar/employee_management_system | emp/views.py | views.py | py | 12,083 | python | en | code | 0 | github-code | 6 |
6507125015 | from django.db import models
from applications.locations.models import Location
class Schedule(models.Model):
id = models.BigAutoField(
primary_key=True,
verbose_name='Id Horario'
)
location = models.ForeignKey(
Location,
verbose_name='Sede',
null=False,
o... | chpenaf/DotSportsBackend | applications/schedule/models.py | models.py | py | 2,611 | python | en | code | 0 | github-code | 6 |
74519748667 | import pyautogui
from random import random
import pyscreenshot as ImageGrab
import math
import cv2 as cv
from utilities import inventory as inv
from utilities.core import get_bounding_rect_from_pts
def get_pickup_rects(o_img, cnts): # returns bounding rect(s) of item(s) to pickup
items = []
line_pts = []
... | 009988b/2007scape-bot-functions | skills/combat.py | combat.py | py | 5,029 | python | en | code | 0 | github-code | 6 |
30864499352 | import numpy as np
n=np.genfromtxt('matrix1.csv',delimiter=',')
import numpy as ap
a=ap.genfromtxt('inmat.csv',delimiter=' ')
import numpy as bp
b=bp.genfromtxt('outmat.csv',delimiter=' ')
k=n[:,0:7]
k1=n[:,8:83]
p=[sum(k[i]) for i in range(83)]
p1=[sum(k1[i]) for i in range(83)]
cluster1=[]
clust... | mdaksamvk/drug-target-identification-clustering-and-local-resistance-analysis | cluster_analysis.py | cluster_analysis.py | py | 801 | python | en | code | 1 | github-code | 6 |
6259690746 | from enum import Enum
import numpy as np
from collections import deque
import bisect
from numpy.core.numeric import array_equal
from graphics import GraphWin, Text, Point, Rectangle, Circle, Line, Polygon, update, color_rgb
# +-------+
# | 16 17 |
# | 18 19 |
# +-------+---... | danemo01/CS470 | HW4/rubik_lab_assignment_4.py | rubik_lab_assignment_4.py | py | 17,458 | python | en | code | 0 | github-code | 6 |
9765699442 | def linear_search(array, item):
# It returns the index if the item is in the list or None if isn't
for i in range(len(array)):
if array[i] == item:
return i
return None
### Worse case is the size list, therefore 0(N), linear function
### Interaction with user bellow
array1 = [... | joaocarvoli/datastructures-ufc | in-python/3.sort-and-search-algorithms/linear_search.py | linear_search.py | py | 572 | python | en | code | 0 | github-code | 6 |
10976102669 | import numpy as np
import matplotlib.pyplot as plt
def linear_LS(xi, yi):
a = np.empty(2)
n = xi.shape[0]
c0 = np.sum(xi)
c1 = np.sum(xi ** 2)
c2 = np.sum(yi)
c3 = np.sum(xi * yi)
a[0] = (c0*c3 - c1*c2) / (c0*c0 - n*c1)
a[1] = (c0*c2 - n*c3) / (c0*c0 - n*c1)
return a
... | LiBingbin/Computational_Physics | PythonProject/hw04/hw04_t2.py | hw04_t2.py | py | 1,781 | python | en | code | 0 | github-code | 6 |
3045998741 | from fastapi import HTTPException, status
from app.v1.model.user_model import User as UserModel
from app.v1.schema import user_schema
from app.v1.service.auth_service import get_password_hash
from app.v1.service import registered_developers_service
from app.v1.schema.registered_developers_schema import RegisteredDeve... | marianamartineza/kunaisoft-database-CRUD-fastapi | app/v1/service/user_service.py | user_service.py | py | 7,752 | python | en | code | 0 | github-code | 6 |
22966971345 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 12 05:51:48 2020
@author: Souhardya
"""
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def push(self,new_data):
new_node=Node(new_data)
... | souhardya1/Single-LinkedList-in-python | Print Nth item from last in Single Linked List.py | Print Nth item from last in Single Linked List.py | py | 857 | python | en | code | 0 | github-code | 6 |
34416507045 | from setuptools import setup, find_packages
with open('requirements.txt') as f:
reqs = f.read().split()
with open('README.md') as f:
readme = f.read()
setup(
name='trackthenews',
version='0.1.9.1',
description='Monitor RSS feeds for keywords and act on matching results. A special project of the F... | fakebenjay/trackthenews-lefty | setup.py | setup.py | py | 1,096 | python | en | code | 0 | github-code | 6 |
13442681959 | # -*- coding: utf-8 -*-
"""Module containing network adapter for socket (asyncore.dispacher)."""
import logging
import socket
import struct
import asyncore
from collections import deque
from .. import connection, server, client
from .._utils import lazyproperty
_logger = logging.getLogger(__name__)
_conne... | Occuliner/ThisHackishMess | extern_modules/pygnetic/network/socket_adapter.py | socket_adapter.py | py | 5,296 | python | en | code | 2 | github-code | 6 |
46057888236 | # -*- coding: utf-8 -*-
import logging
import datetime
import pytz
__all__ = ['timezones']
logger = logging.getLogger('django')
def is_standard_time(time_zone, date_time):
try:
dst_delta = time_zone.dst(date_time, is_dst=False)
except TypeError:
dst_delta = time_zone.dst(date_time)
r... | nitely/Spirit | spirit/core/utils/timezone.py | timezone.py | py | 2,280 | python | en | code | 1,153 | github-code | 6 |
7192437436 | import datetime
import hashlib
import json
import yaml
import flask.json
import shutil
import subprocess
import uuid
import zipfile
import click
import os
from flask.cli import AppGroup
import requests
from sqlalchemy.orm import load_only
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import Integr... | pebble-dev/rebble-appstore-api | appstore/commands.py | commands.py | py | 22,680 | python | en | code | 13 | github-code | 6 |
2228623411 | '''
module to load yolov5* model from the ultralytics/yolov5 repo
'''
import torch
from src.core.logger import logger
def load_model(model_repo: str = "ultralytics/yolov5", model_name: str = "yolov5s6"):
"""
It loads the YOLOv5s model from the PyTorch Hub
:return: A model
"""
try:
device =... | TYH71/gradio-ml-skeleton | src/model/yolov5.py | yolov5.py | py | 814 | python | en | code | 0 | github-code | 6 |
9307549467 |
from logger import logger
from io import StringIO, BytesIO # python3; python2: BytesIO
from datetime import datetime
import boto3
def s3_client_init():
client = boto3.client('s3')
return client
def dataframe_to_s3(s3_client, input_datafame, bucket_name, format='parquet'):
logger.info(f"Writing {for... | caiolauro/flix-twitter-data-elt | twitter_api/s3_writer.py | s3_writer.py | py | 945 | python | en | code | 0 | github-code | 6 |
1802990089 | '''
Simple calculator functions
Lucas
09.05.2021
'''
import colorama
# adds two numbers
def add(x, y):
return x + y
# subtracts two numbers
def subtract(x, y):
return x - y
# multiplies two numbers
def multiply(x, y):
return x * y
# divides two numbers
def divide(x, y):
return x / y
while (Tru... | TheLucas777/Python_HTLAnichstasse | programme/calc_functions.py | calc_functions.py | py | 2,893 | python | en | code | 1 | github-code | 6 |
38957829610 | from socketio.namespace import BaseNamespace
from socketio.sdjango import namespace
from csvapp.pubsub import subscribe, unsubscribe
@namespace('/csv')
class CSVNamespace(BaseNamespace):
def disconnect(self, *args, **kwargs):
super(CSVNamespace, self).disconnect(*args, **kwargs)
unsubscribe(
... | iamjem/django-csvapp | project/csvapp/sockets.py | sockets.py | py | 947 | python | en | code | 0 | github-code | 6 |
41382929279 | from typing import Callable
from dataclasses import dataclass
import pandas as pd
from hvac import Quantity
from hvac.fluids import HumidAir
from hvac.climate import ClimateData
from hvac.climate.sun.solar_time import time_from_decimal_hour
from ..core import (
ExteriorBuildingElement,
InteriorBuildingElement,
... | TomLXXVI/HVAC | hvac/cooling_load_calc/building/space.py | space.py | py | 37,323 | python | en | code | 8 | github-code | 6 |
23929041781 | # Asyncio Python 3.7+ package comparision with Javascript async
# by default operates in single thread and CPU core
# and schedules tasks as coroutines to run in an event loop
import asyncio
#import requests incompatible because does not return awaitable tasks
# pyenv exec pip install aiohttp
import aiohttp
from aioht... | simonc312/today-i-learned | Apache Spark/python/AsyncIO.py | AsyncIO.py | py | 2,148 | python | en | code | 0 | github-code | 6 |
4487190452 | """
Exam task 2 Binary Tree
"""
from collections import deque
from queue import Queue
class BinatyTree:
"""
Binary tree class with basic functional
Version with tree as node
with data, left and right children
"""
def __init__(self, data) -> None:
"""
Init root with default lef... | sviat-l/FP_Labs | Exam/Binary tree/binary_tree.py | binary_tree.py | py | 4,297 | python | en | code | 0 | github-code | 6 |
31127621657 | import numpy as np
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.batchnorm = nn.BatchNorm2d(3, affine=False)
self.pad2 = nn.ConstantPad2d(2, 0)
sel... | peinrules/Darin | GAME.py | GAME.py | py | 4,427 | python | en | code | 0 | github-code | 6 |
39647933037 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
# Author : Amir Shokri
# github link : https://github.com/amirshnll/Wine
# dataset link : http://archive.ics.uci.edu/ml/datasets/Wine
# email : amirsh.nll@gmail.com
# In[8]:
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selec... | semnan-university-ai/Wine | tree3.py | tree3.py | py | 1,118 | python | en | code | 1 | github-code | 6 |
26471134751 | import unittest
from util.tests.reusable import compare_speed
from solution.batch2.problem30 import *
class DigitFifthPowers(unittest.TestCase):
def test_all_but_upper(self):
expected = [
[153, 370, 371, 407],
[1634, 8208, 9474],
[4150, 4151, 54748, 92727, 93084, 194_97... | bog-walk/project-euler-python | test/batch2/test_problem30.py | test_problem30.py | py | 914 | python | en | code | 0 | github-code | 6 |
72908437948 | from odoo import models, fields, api, _
from odoo.exceptions import ValidationError
import logging
_logger = logging.getLogger(__name__)
class StudentTranscript(models.TransientModel):
_name = "student.transcript"
_description = "Student Transcript"
from_date = fields.Date(
'From Date'... | mrrtmob/odoo_acac | local-addon/pm_general/wizards/student_transcript_wizard.py | student_transcript_wizard.py | py | 5,635 | python | en | code | 0 | github-code | 6 |
74473926906 | from django.shortcuts import render, redirect
from .models import Diary
from datetime import datetime
import pytz
import json
diary_dict = {}
response ={}
def index(request):
diary_dict = Diary.objects.all().values()
if 'user_login' in request.session:
response['user_name'] = request.session['user_logi... | argaghulamahmad/ppw-lab-arga | lab_3/views.py | views.py | py | 1,230 | python | en | code | 0 | github-code | 6 |
10862291387 | import glob
import numpy as np
from parsebook import Book
import bookNBC
def getData(loveBooksPath, horrorBooksPath):
loveBooks = []
horrorBooks = []
lovefiles = glob.glob(loveBooksPath)
for file in lovefiles:
book = Book(file,"love")
loveBooks.append(book)
horrorfiles = glob.glo... | AndresGutierrez01/GenreSortingSystem | getData.py | getData.py | py | 943 | python | en | code | 2 | github-code | 6 |
5412752271 | """
Python script to scrape a web page for all email addresses
"""
from bs4 import BeautifulSoup
import requests
import requests.exceptions
from urllib.parse import urlsplit
import re
url1 = "http://www.rit.edu/gccis/computingsecurity/people-categories/faculty"
url2 = "https://www.rit.edu/its/about/staff"
# a set of... | ahadsheriff/security_suite | pentest_suite/beautiful_soup/email_regex/email_regex.py | email_regex.py | py | 1,136 | python | en | code | 1 | github-code | 6 |
74537470908 | import numpy as np
import cv2
# 단일 채널 생성 및 초기화
m1 = np.full((3, 6), 10, np.uint8)
m2 = np.full((3, 6), 50, np.uint8)
m_mask = np.zeros(m1.shape, np.uint8) # 마스크 생성
m_mask[:, 3:] = 1 # 관심영역을 지정한 후, 1을 할당
m_add1 = cv2.add(m1, m2) # 행렬 덧셈
m_add2 = cv2.add(m1, m2, mask=m... | binlee52/OpenCV-python | ch05/04.arithmethic_op.py | 04.arithmethic_op.py | py | 772 | python | ko | code | 1 | github-code | 6 |
6812515285 | import logging
from scrim_bot.core.role import Role, RoleIsInvalid
logger = logging.getLogger(__name__)
class Player:
"""
Represents a player taking part in inhouse games
"""
_id: int
_name: str
roles: list[Role]
elo: float
summoner_name: str
def __init__(self, _id: int, name: ... | isvladu/inhouse-bot-lol | scrim_bot/core/player.py | player.py | py | 2,392 | python | en | code | 0 | github-code | 6 |
12307666054 | """Utility script to be used to cleanup the notebooks before git commit
This a mix from @minrk's various gists.
"""
import time
import sys
import os
import io
try:
from queue import Empty
except:
# Python 2 backward compat
from Queue import Empty
try:
from ipyparallel import Client
except ImportErr... | ogrisel/parallel_ml_tutorial | ipynbhelper.py | ipynbhelper.py | py | 8,087 | python | en | code | 1,592 | github-code | 6 |
30160884075 | # Write an action print, To debug: print("Debug messages", file=sys.stderr)
import sys
import math
def available_neighboors(grid, r, c):
res = []
for cor in ((r+1, c),(r-1, c), (r, c+1), (r, c-1)):
if grid[cor[0]][cor[1]] != '#':
res.append((cor[0],cor[1]))
return res
def ... | PierreMsy/CodeGames | CodinGame/Maze.py | Maze.py | py | 2,183 | python | en | code | 0 | github-code | 6 |
21097703844 | from invenio.ext.sqlalchemy import db
domain = 'BBMRI'
# display_name = 'Biobanking and BioMolecular Resources Research Infrastructure'
display_name = 'Biomedical Research'
table_name = 'BBMRI'
image = 'domain-bbmri.png'
kind = 'project'
domaindesc = 'Biomedical research data.'
fields = [
{
'name': 'study... | cjhak/b2share | invenio/b2share/modules/b2deposit/b2share_model/metadata/bbmri_metadata_config.py | bbmri_metadata_config.py | py | 4,523 | python | en | code | null | github-code | 6 |
10035856253 | """Training script for End-to-end visuomotor controllers."""
import argparse
import os
from stat import ST_CTIME
import shutil
import re
import json
import pprint
import tensorflow as tf
from data.geeco_gym import pickplace_input_fn
from models.e2evmc.estimator import e2evmc_model_fn, goal_e2evmc_model_fn
from model... | ogroth/geeco | scripts/train_e2evmc.py | train_e2evmc.py | py | 12,436 | python | en | code | 7 | github-code | 6 |
18625152569 | import os
import json
import requests
from bs4 import BeautifulSoup
from datetime import datetime as dt
import pandas as pd
from __common__ import user_choice
def __load_json__(file):
"""
"""
try:
with open(file) as rf:
data = json.load(rf)
return data
except:
retu... | robbie-manolache/energy-market-analysis | nemtel/tracker.py | tracker.py | py | 6,567 | python | en | code | 0 | github-code | 6 |
41061175651 | import numpy as np
import torch
import torch.nn.functional as F
import torch.nn as nn
import os
import cv2 as cv
def rgb2gray(rgb):
'''
Transforms frame into a grayscale
Args:
rgb (numpy array) : numpy array grayscaled
'''
r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
gray = 0.2989 * ... | ylajaaski/reinforcement_env | src/utils.py | utils.py | py | 2,534 | python | en | code | 0 | github-code | 6 |
32610163975 | from mercurial import archival, cmdutil, commands, extensions, filemerge, hg, \
httprepo, localrepo, merge, sshrepo, sshserver, wireproto
from mercurial.i18n import _
from mercurial.hgweb import hgweb_mod, protocol, webcommands
from mercurial.subrepo import hgsubrepo
import overrides
import proto
def uisetup(ui):... | Anderson-Lab/Learn2Mine-Main | galaxy-dist/eggs/mercurial-2.2.3-py2.7-macosx-10.6-intel-ucs2.egg/hgext/largefiles/uisetup.py | uisetup.py | py | 6,985 | python | en | code | 2 | github-code | 6 |
74363302909 | #!/usr/bin/python3
'''
A simple matrix module
'''
def matrix_divided(matrix, div):
''' A function that divides all elements of a matrix '''
error_msg = 'matrix must be a matrix (list of lists) of integers/floats'
if not all(
isinstance(row, list) and all(
isinstance(element, (i... | ugwujustine/alx-higher_level_programming | 0x07-python-test_driven_development/2-matrix_divided.py | 2-matrix_divided.py | py | 922 | python | en | code | 0 | github-code | 6 |
73732952507 | #!/usr/bin/env python
import requests
import base64
import random
import sys
def getPicText_bdOcr(pic_binary, type_index = 1):
'''
利用百度 ocr 接口识别文字
pic_binary 是图片文件的二进制数据
type_index 是百度提供的识别类型 0 表示一般识别, 1 表示精准识别
如果成功,则返回识别出的文字字符串
如果出错,则返回错误信息
'''
# 获取 appid 的 coo... | fkxxyz/fkxxyz-wechatRequestHandler | baiduOcr.py | baiduOcr.py | py | 2,061 | python | en | code | 0 | github-code | 6 |
1970824683 |
class elevator(): #defining elevator characteristics
def __init__(self, currentFloor = 1, serviceMode = False, maxHeight = 20, minHeight = 1):
self.currentFloor = currentFloor
self.inServiceMode = serviceMode
self.maxHeight = maxHeight
self.minHeight = minHeight
def goToFloor(self, move): #metho... | brentmm/elevator | main.py | main.py | py | 2,525 | python | en | code | 0 | github-code | 6 |
12526917301 | #! /usr/bin/env/python 3.1
#
# handle the transformation of the scanner results files.
# use MOT as transformattor
# author: Andreas Wagner
#
from AnalyzeToolConfig import AnalyzeToolConfig
import os.path
import py_common
class TransformTool(object):
def __init__(self, config):
self.config = config
... | devandi/AnalyzeTool | TransformTool.py | TransformTool.py | py | 1,322 | python | en | code | 4 | github-code | 6 |
25229791277 | import pandas as pd
from sklearn.metrics.pairwise import linear_kernel
from scipy.io import mmwrite, mmread
import pickle
from gensim.models import Word2Vec
# 데이터 가져오기
df_reviews = pd.read_csv('./naver_crawling_data/naver_cleaned_reviews.csv')
Tfidf_matrix = mmread('./naver_models/Tfidf_book_review.mtx').tocsr()
with ... | sealamen/project_03_book_curator | 07_book_recommendation.py | 07_book_recommendation.py | py | 1,305 | python | en | code | 0 | github-code | 6 |
75096001788 | def filterTags(attrs):
tags = {}
if attrs["SURFACE"] == "Gravel":
tags["surface"] = "gravel"
elif attrs["SURFACE"] == "Unpaved":
tags["surface"] = "unpaved"
elif attrs["SURFACE"] == "Paved":
tags["surface"] = "paved"
if attrs["TRAIL_NAME"]:
tags["name"] = attrs["... | impiaaa/SV-OSM | translations/bike.py | bike.py | py | 898 | python | en | code | 1 | github-code | 6 |
37560479588 | a1 = 0x31 ## (1)
a2 = 0x31 ## (1)
a3 = 0x38 ## (8)
a4 = 0x30 ## (0)
b1 = 0x2B ## (-) (+)0x2B (-)0x2D
b2 = 0x30 ## (0)
b3 = 0x30 ## (0)
b4 = 0x35 ## (5)
#print(chr(a))
def solarAsciitoInt(s1,s2,s3,s4):
solarStr = chr(s1) + chr(s2)+chr(s3) + chr(s4)
soloarInt = int(solarStr)
#print(soloarInt)
ret... | CoKap-ASL-DEV/ModBusRTUoverTCP | test2.py | test2.py | py | 928 | python | en | code | 0 | github-code | 6 |
25005216625 | import io
import typing
import random
import discord
import operator
import datetime
from config import config
from discord.ext import commands
from util.paginator import Pages
from util.converter import CaseInsensitiveRole, PoliticalParty, CaseInsensitiveMember
class Misc(commands.Cog, name="Miscellaneous"):
""... | DENE-dev/dene-dev | RQ1-data/exp2/114-jonasbohmann@democraciv-discord-bot-ae9b0558588ef6313477cfd58732ceec738dd706/module/misc.py | misc.py | py | 25,789 | python | en | code | 0 | github-code | 6 |
73891294909 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
# feature: 30天内加速度;创业板,中小板,白马
import re
import json
import requests
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
import statsmodels.formula.api as smf
import statsmodels.graphics.api as smg
import time
headers = {'Accept... | SoyM/fin | test.py | test.py | py | 7,933 | python | en | code | 0 | github-code | 6 |
39963956930 | """========================================================================
File Name : python_project.py
File Description : This file illustrate usage of oops concept of python,
iterates as many times as the user input
search the given keyword in input f... | 99003757/Python_Mini_Project | python_project.py | python_project.py | py | 3,417 | python | en | code | 0 | github-code | 6 |
22497784287 | from flask_app.config.mysqlconnection import connectToMySQL
from flask import flash
class Recipe:
db = "login_and_registration"
# db should = your schema
def __init__(self, data):
self.id = data['id']
self.names = data['names']
self.descriptions = data['descriptions']
self... | tsu112/login_and_registration | flask_app/models/recipe.py | recipe.py | py | 2,869 | python | en | code | 0 | github-code | 6 |
19237958892 | import os
from war3structs.storage import MPQ
from .common import PipeTransformer
from ..liquid import Liquid
class MapExtractorPipe(PipeTransformer):
def gate(self, build, liquid):
map_liquids = []
map_path = os.path.join(build['etcdir'], 'temp%s' % liquid.name)
# Begin by writing the liquid's content... | sides/war3archiver | war3archiver/transformers/maps.py | maps.py | py | 856 | python | en | code | 0 | github-code | 6 |
29122533365 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 1 12:24:24 2018
@author: omer mirza
"""
import math as m
def f(x):
return m.cos(x) - x
def f1(x):
return x**3 -2*x**2 - 5
def f2(x):
return x**3 + 3*x**2 -1
def f3(x):
return x - m.cos(x)
def f4(x):
return x -.8 -.2*m.sin(x)
de... | omermirza556/NumericalPrograms | secant_omirza14.py | secant_omirza14.py | py | 3,344 | python | en | code | 0 | github-code | 6 |
73741438266 | import tonos_ts4.ts4 as ts4
eq = ts4.eq
# Initialize TS4 by specifying where the artifacts of the used contracts are located
# verbose: toggle to print additional execution info
# Инициализировать TS4, указав, где находятся артефакты используемых контрактов
# verbose: переключить на печать дополнительной информации о... | baerelektro/TestSuite4 | tutorials/tutorial08_balance.py | tutorial08_balance.py | py | 1,403 | python | ru | code | 0 | github-code | 6 |
22007528984 | # def calculator(n1, n2):
# return n1 + n2
#
# returnVAL = calculator(10, 20)
# print(returnVAL)
# calculator = lambda n1, n2: n1 + n2 # 함수 선언과 같음
#
# returnVAL = calculator(10, 20)
# print(f'returnVAL: {returnVAL}')
triangle = lambda n1, n2: n1 * n2 / 2
square = lambda n1, n2: n1 * n2
circle = lambda r: r * r *... | bobdongeun/bobcoding | pythonProject/5_008/fun.py | fun.py | py | 702 | python | ko | code | 0 | github-code | 6 |
5648119133 |
import sys
from typing import List, Optional, Tuple
import unittest
def all_construct(target_string: str, strings: List[str], memo=None) -> List[List[str]]:
# Memo.
if memo is None:
memo = {}
if target_string in memo:
return memo[target_string]
# Base case.
if len(target_string) =... | bradtreloar/freeCodeCamp_DP_problems | problems/memoized/all_construct.py | all_construct.py | py | 2,426 | python | en | code | 0 | github-code | 6 |
39242617287 | from torch import nn
import torch
from models.cotnet import CotLayer
class ChannelAttention(nn.Module):
def __init__(self,in_channels,reduction=16):
super(ChannelAttention,self).__init__()
self.attention = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(in_channels,in_ch... | ucaswangls/GAP-CCoT | models/basicblock.py | basicblock.py | py | 3,737 | python | en | code | 9 | github-code | 6 |
12700629432 | import sys
import heapq
INF = int(1e9)
def input(): return sys.stdin.readline().rstrip()
def extractHackingResults(results):
hacked_computer, max_hacking_time = 0, 0
for hacking_time in results:
if hacking_time not in [None, INF]:
hacked_computer += 1
max_hacking_time = max(ma... | MinChoi0129/Algorithm_Problems | BOJ_Problems/10282.py | 10282.py | py | 1,875 | python | en | code | 2 | github-code | 6 |
32249755158 | import streamlit as st
import altair as altc
import pandas as pd
import numpy as np
import os, urllib
from PIL import Image
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, BatchNormalization, Activation, Dense, Dro... | ajayjalluri/Drone-Data-Image-Segmentatation | app.py | app.py | py | 2,166 | python | en | code | 0 | github-code | 6 |
15505226126 | # Author: Lane Moseley
# Description: This file demonstrates the usage of the custom logistic regression
# module implemented in the ML library.
# Resources Used:
# Fish Dataset:
# Included with the project, but also available from Kaggle:
# https://www.kaggle.com/aungpyaeap/fish-ma... | lanemoseley/ml-library | logisticRegression.py | logisticRegression.py | py | 4,735 | python | en | code | 0 | github-code | 6 |
34435689503 |
#lucratividade x produtividade
# a seguir voce vera uma analise de lucro x produtividade#
lucro_primeira = float(input('digite seu lucro na primeira loja'))
lucro_segunda = float(input('digite seu lucro na segunda loja'))
lucro_terceira = float(input('digite seu lucro na terceira loja'))
lucro_quarta = float(inpu... | gamiel075/py | estudov5.py | estudov5.py | py | 2,343 | python | pt | code | 0 | github-code | 6 |
32461455469 | import re
import os
datafolder = "./data/"
def processObjdump(case: str) -> None:
folder = datafolder + case
input = case + "-armv8m.objdump"
output = case + "Objdump.txt"
inPath = os.path.join(folder, input)
outPath = os.path.join(folder, output)
with open(outPath, 'w') as w:
with open... | kakack/function-tracer | initialDemo/ProcessFile.py | ProcessFile.py | py | 1,625 | python | en | code | 0 | github-code | 6 |
26627014986 | from django.db import models
from livesettings import config_value_safe, config_choice_values, SettingNotSet
def shipping_choices():
try:
return config_choice_values('SHIPPING','MODULES')
except SettingNotSet:
return ()
class ShippingChoiceCharField(models.CharField):
def __init__(self, ... | dokterbob/satchmo | satchmo/apps/shipping/fields.py | fields.py | py | 977 | python | en | code | 30 | github-code | 6 |
37751980621 | import sys
helpText = '''This tool is used to extract text from a file, summarize it using OpenAI's LLM model, and print/save it to a file. Supported file types: TXT, PDF, CSV, MD, JSON.'''
helpText += '\nCommand-Line args required: -f filePath\nOptional Command-Line args: -start startingPageNum -end endingPageNum -d ... | cglavin50/pdf-summarizer-cli | handlers/cliHandler.py | cliHandler.py | py | 1,031 | python | en | code | 0 | github-code | 6 |
42197969651 | from django.urls import path
from .views import (
InvitiHome,
InvitoDetailView,
InvitoCreateView,
InvitoUpdateView,
InvitoDeleteView,
InvitiUtente,
PrenotazioniUtente,
InvitoPartecipa,
InvitiGenere,
InvitoRimuoviPartecipa,
InvitiFilterView,
GeneriFilterView,
About
)
... | lucacasarotti/CineDate | inviti/urls.py | urls.py | py | 1,830 | python | it | code | 0 | github-code | 6 |
30138218135 | # !/usr/local/python/bin/python
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <wudong@eastwu.cn>'
# @Time: '2020-03-19 10:49'
""" 演示 pre-request 框架如何使用长度校验,仅针对字符串有效
"""
from flask import Flask
from pre_request import pre, Rule
app = Flask(__name__)
app.config["TESTING"] = True
... | Eastwu5788/pre-request | examples/example_filter/example_length.py | example_length.py | py | 1,070 | python | en | code | 55 | github-code | 6 |
35787180481 | from starlette.responses import JSONResponse, FileResponse
from starlette.background import BackgroundTasks
from fastapi import APIRouter #, Form, File, UploadFile
# from model.classification_pylon.predict import main as pylon_predict
# from model.covid19_admission.predict_admission import main as covid_predict
import ... | mmkanta/fl-webapp-model | api/infer.py | infer.py | py | 2,542 | python | en | code | 0 | github-code | 6 |
74309695227 | import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
screen = Screen()
screen.title("Turtle Race")
screen.setup(width=600, height=600)
screen.tracer(0)
myplayer = Player()
cars = CarManager()
score = Scoreboard()
screen.listen()
screen.onk... | shuklaritvik06/PythonProjects | Day - 23/main.py | main.py | py | 726 | python | en | code | 0 | github-code | 6 |
40592577580 |
from collections import Counter
import operator
st=input()
k=int(input())
omap=Counter(st)
a=sorted(omap.items(),key=operator.itemgetter(1))
i=0
while k>0 and i<len(a):
if a[i][1]<=k:
k-=a[i][1]
del omap[a[i][0]]
else:
omap[a[i][0]]-=k
k=0
i+=1
print(len(omap))
ans=""
for i ... | ku-nal/Codeforces | codeforces/102/C.py | C.py | py | 479 | python | en | code | 3 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.