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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
29343615007 | import sys
import json
import sql
from dateutil import parser as dt
def getPackageId(package, ecosystem):
''' returns packageId if exists, else creates '''
selectQ = 'select id from package where name=%s and ecosystem=%s'
results = sql.execute(selectQ,(package,ecosystem))
if not results:
inse... | nasifimtiazohi/secrel | ghsa/explore.py | explore.py | py | 1,991 | python | en | code | 0 | github-code | 1 |
71435223394 | import requests
api_url = 'http://3.109.224.64:8080'
def turn_motor_off():
try:
data = {'status': 'off'}
response = requests.post(f'{api_url}/motor/update', json=data)
response_data = response.json()
return response_data
except Exception as e:
return {'... | yascio/sih-prototype | motor_off.py | motor_off.py | py | 464 | python | en | code | 0 | github-code | 1 |
16943091683 | # _*_ coding:utf-8 _*_
import pika
from multiprocessing import Process, current_process
from settings import *
class FlowCollect(Process):
"""流量收集类"""
def __init__(self, url, instance):
super(FlowCollect, self).__init__()
self.url = url
self.instance = instance
self.name = ins... | cloudmonitor/flowcollector | flowcollector/flowcollect.py | flowcollect.py | py | 3,355 | python | en | code | 0 | github-code | 1 |
19956123029 | # © 2021 Solvos Consultoría Informática (<http://www.solvos.es>)
# License LGPL-3.0 (https://www.gnu.org/licenses/lgpl-3.0.html)
from odoo import models
class StockPicking(models.Model):
_inherit = "stock.picking"
def lines_category_product(self):
self.ensure_one()
categories = {}
... | solvosci/slv-stock | stock_picking_eco_tag/models/stock_picking.py | stock_picking.py | py | 812 | python | en | code | 2 | github-code | 1 |
32712471476 | from pydicom import dcmread
import numpy as np
from scipy.sparse import csc_matrix
import matplotlib.pyplot as plt
import math
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import pandas as pd
import scipy.stats as stats
def fun(contour_dataset, image, zcoord):
img_ID = image.SOPInstanceUID
... | perseusf/MainProject | main.py | main.py | py | 12,068 | python | ru | code | 0 | github-code | 1 |
6584229686 | import numpy
from typing import Optional, cast
from UM.Qt.Bindings.Theme import Theme
from UM.Qt.QtApplication import QtApplication
from UM.Logger import Logger
class LayerPolygon:
NoneType = 0
Inset0Type = 1
InsetXType = 2
SkinType = 3
SupportType = 4
SkirtType = 5
InfillType = 6
Su... | Ultimaker/Cura | cura/LayerPolygon.py | LayerPolygon.py | py | 12,372 | python | en | code | 5,387 | github-code | 1 |
6482397047 | from preprocessing.loading import *
from utils import *
import logging, os
import gcsfs
from joblib import Parallel, delayed
from tqdm import tqdm
from db import RedisDB
from math import ceil
logging.basicConfig(level = logging.INFO)
GOOGLE_APPLICATION_CREDENTIALS = os.getenv('GOOGLE_APPLICATION_CREDENTIALS')
GOOGLE_... | agriuseatstweets/gut | load_tweets.py | load_tweets.py | py | 1,464 | python | en | code | 0 | github-code | 1 |
24508802688 | import math
import sys
import time
from typing import Tuple
from codebase.real_world.base.getters import Getters
from codebase.real_world.base.senders import Senders
from socket import socket
from codebase.real_world.base.base_client import BaseClient
class PTP(BaseClient):
def __init__(self, host: str, port: int... | Dominique-Yiu/pyspacemouse-coppeliasim | codebase/real_world/base/PTP.py | PTP.py | py | 9,431 | python | en | code | 1 | github-code | 1 |
43498696368 | import numpy as np
import matplotlib.pyplot as plt
from part4 import kf_smooth
def time_and_meas_update(Sigma, A, Sigma_w, C, R):
'''Your code here'''
# all the definitions are similar to KF implementation, performing time update and measurement update
# here Sigma_w is Q in the slides. You need to output ... | tpvt99/robotics | cs287hw4/part5.py | part5.py | py | 3,213 | python | en | code | 1 | github-code | 1 |
16643229318 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 12 00:23:46 2023
@author: calic
"""
import random
options = ["rock", "paper", "scissors"]
def get_player_choice():
player_choice = input("Enter a choice(rock, paper, scissors: ")
return str(player_choice)
def check_input(user_input):
if user_input == "roc... | eric-babcock/python-public | learningExamples/rockPaperScissors.py | rockPaperScissors.py | py | 1,853 | python | en | code | 0 | github-code | 1 |
22378411363 | import random
from Plemiona.terrain import Terrain
import math
class Map:
"""
Class resposnible for providing acess to map and for performing operations on terrains
"""
def __init__(self, name, config):
"""
Parameters
----------
name : str
The name of the m... | nuczlab/po_projekt | Plemiona/map.py | map.py | py | 3,007 | python | en | code | 0 | github-code | 1 |
1801918096 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
import re
from django.conf import settings
class RbacMiddleware(MiddlewareMixin):
'''
1.获取当前用户的url
2.获取当前用户在session中的url权限列表
3.权限信息进行匹配
'''
def process... | yjiu1990/crm | rbac/middlewares/rbac.py | rbac.py | py | 2,340 | python | en | code | 0 | github-code | 1 |
1588154559 | """Tests for ``highcharts.no_data``."""
from copy import deepcopy
import pytest
from json.decoder import JSONDecodeError
from validator_collection import checkers
from highcharts_core.headless_export import ExportServer as cls
from highcharts_core.options import HighchartsOptions
from highcharts_core import errors
fr... | highcharts-for-python/highcharts-core | tests/test_headless_export.py | test_headless_export.py | py | 7,115 | python | en | code | 40 | github-code | 1 |
6488325809 | '''MIXED CONTENT
You have a string of words and digits divided by comma. Write a program which
separates words with digits. You shouldn't change the order elements.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. Input
example is the following
8,33,21,0,16,50,37,0,melon,7,apricot... | mgorgei/codeeval | Easy/c115 Mixed Content.py | c115 Mixed Content.py | py | 901 | python | en | code | 1 | github-code | 1 |
28144864826 | #!/usr/bin/env python
# coding: utf-8
import pickle
import streamlit as st
st.set_page_config(page_title = 'Titanic Survival Predictor')
pickle_in = open("decision_tree.pkl","rb")
classifier=pickle.load(pickle_in)
def predict_survival(Pclass,sex,SibSp,Parch,Embarked,Age_band,Fare_band):
prediction=classi... | ryanwng12/TitanicAnalysis-Prediction | app.py | app.py | py | 3,859 | python | en | code | 0 | github-code | 1 |
2736711933 | def get_count1(sentence):
bad = ['a','e','i','o','u']
n = 0
for s in sentence:
for b in bad:
if b == s:
n+=1
return n
vo = ['a','e','i','o','u']
def get_count(sentence):
return len([1 for s in sentence if [True for v in vo if v==s]])
| SzybkiRabarbar/CodeWars | 2022-03/2022-03-29Vowel Count.py | 2022-03-29Vowel Count.py | py | 291 | python | en | code | 0 | github-code | 1 |
36262937913 | import math
import torch
from torch import nn
import torch.nn.functional as F
import torchvision
import torchaudio
from denoising_diffusion_pytorch import Unet, GaussianDiffusion
class DPTBlock(nn.Module):
def __init__(self, t_len, f_len, batch_first):
super(DPTBlock, self).__init__()
self.t_len = ... | GyoukChu/EE495 | DPTDiffSeg/DPTDiffSeg.py | DPTDiffSeg.py | py | 5,374 | python | en | code | 0 | github-code | 1 |
40331562823 | # --coding:utf8--
age = input ("How old are you? ")
height = input ("How tall are you (m)? ")
weight = input ("How much do you weigh (Kg)? ")
# BMI 公式为 体重 除以身高的平方
BMI = weight / height ** 2
print ("Your BMI is %r " % BMI)
# 这是今天在路上想到昨天的练习,觉得可以试着用BMI的公式写写看。
# 意外的完成了变数跟input的练习还有print的练习。
# 公式的部分,有点错误,所以运算结果有出点问题,但是修... | wangzongyuan/LPTHW | ex_try.py | ex_try.py | py | 713 | python | zh | code | 0 | github-code | 1 |
27582012013 | import math
r = float(input("Enter radius of the cylinder: "))
h = float(input("Enter height of the cylinder: "))
a = math.pi*r*r
sa = ((2*math.pi*r)*h) + ((math.pi*r**2)*2)
v = math.pi * r * r * h
print("The area is : %.2f" %a)
print("The surface area is: %.2f" %sa)
print("the volume is %.2f" %v)
| chrisWalker11/Python | basic_math_calcs.py | basic_math_calcs.py | py | 301 | python | en | code | 0 | github-code | 1 |
833418569 | from typing import Sequence
import math
import torch
from torch.utils.data.sampler import Sampler, RandomSampler
class StratifiedEventBatchSampler(Sampler):
"""Samples elements with from a set with binary labelling to ensure
the event label (1) is evenly distributed across batches.
This sampler is useful... | alok-ai-lab/pyDeepInsight | pyDeepInsight/utils/_sebs.py | _sebs.py | py | 3,289 | python | en | code | 137 | github-code | 1 |
11426673537 | # SOFTEX-RECIFE
# Aluno: Fábio de Tássio
# Atividade 06 do Módulo 02 (Contornar problemas previstos no sistema)
# Desenvolva um programa que recebe do usuário nome completo e ano de nascimento que seja entre 1922 e 2021.
# A partir dessas informações, o sistema mostrará o nome do usuário e a idade que completou, ou... | fabiodtassio/Logica-e-Orientacao-a-Objetos | Modulo.02/atividade06.py | atividade06.py | py | 1,183 | python | pt | code | 0 | github-code | 1 |
1042706126 | import warnings
from PIL import Image,ImageFilter
def down_sample_fit(pil_img, num):
ds = [2 ** (i + 1) for i in range(num)]
for d in ds:
a, b = pil_img.size
add = (a % d)
na = a + add
add = (b % d)
nb = b + add
pil_img = pil_img.resize((na, nb),Image.... | MashiMaroLjc/elegance | plugin/util.py | util.py | py | 1,095 | python | en | code | 39 | github-code | 1 |
20942104690 | from requests.exceptions import RequestException
class RateQuoteServiceException(Exception):
def __init__(self, *args, **kwargs):
if kwargs:
for key, value in kwargs:
setattr(self, key, value)
class RateQuoteNetworkException(RateQuoteServiceException):
"""Exceptions for n... | diveone/finone | finone/exceptions.py | exceptions.py | py | 1,048 | python | en | code | 0 | github-code | 1 |
44044303509 | #!/usr/bin/env python3
import os
import sys
from dataclasses import dataclass, field
"""
author: dmaynor@gmail.com
The script will scan through my ~/code and ~/home directory to look for virtual enviroments for python by looking for a venv directory structure.
It can be called from my ~/tools/bin directory so firs... | dmaynor/mytools | src/project_selector.py | project_selector.py | py | 2,035 | python | en | code | 0 | github-code | 1 |
7413621348 | import re
from glob import glob
import numpy as np
import pandas as pd
def parse_results(fname, sample=None):
results = []
rtt_results = []
regex = (
r"Target: (([0-9a-f]{2}:*){6}), " +
r"status: ([0-9]), rtt: ([0-9\-]+) psec, " +
r"distance: ([0-9\-]+) cm"
)
regex_new = (... | ml4wifi-devs/ftmrate | experiments/calibration/ftm/parse.py | parse.py | py | 2,113 | python | en | code | 1 | github-code | 1 |
40059843407 | import copy
import random
from typing import Optional, List
from ..services.spu_feature_service import SpuFeatureService
from ...entity.rec_item import RecItem
class HotsRecall(object):
def get_candidates(self, k: Optional[int] = None) -> List[RecItem]:
"""
获取前k个热映商品
:param k: 待获取的数量,如果为N... | lingltang/LML | tx/02_nlp/projectSet/MovieRecSystem/src/MovieRecSystem/stategy/recall/hots_recall.py | hots_recall.py | py | 1,020 | python | en | code | 0 | github-code | 1 |
9760113804 | from Process import Process
from Generators import Generators
from UnitOfBlood import UnitOfBlood
class StandardOrder(Process):
counter_standard_order = 0
def __init__(self, bdp, blood_type):
super().__init__(bdp)
self.time = 300
self.blood_type_order = blood_type
self.activ... | szymag/BloodPoint | StandardOrder.py | StandardOrder.py | py | 1,442 | python | en | code | 0 | github-code | 1 |
24606078374 | #!/usr/bin/env python
# coding: utf-8
# In[10]:
'''
비만을 판단하기 위해서 BMI 수치가 필요하다.
BMI 수치가 입력되면 비만을 판단하시오.
* BMI에 따른 비만 판정
BMI 수치 비만 판정
~10 이하 정상
~20 이하 과체중
20 초과 비만
'''
a=input()
a=int(a)
if a<11:
print("정상")
elif a<21:
print("과체중")
else:
print("비만")
# In[ ]:
| smilesunho/practice-for-codeup | 1203.py | 1203.py | py | 416 | python | ko | code | 0 | github-code | 1 |
3196026743 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 26 18:15:35 2017
@author: twu
"""
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dictionary = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M' : 1000}
num = []
while... | niufenjujuexianhua/Leetcode | Roam To Integer.py | Roam To Integer.py | py | 1,635 | python | en | code | 0 | github-code | 1 |
26813376874 | import pygame, sys, random
import pygame.camera
from pygame.locals import *
from PIL import Image
import pytesseract as pt
"""S_L = 'eng'
D_L = 'en'"""
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
FPS = 30
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BRIGHTBLUE = ( 0, 50, 255)
BUTTONCOLOR = WHITE
BUT... | nehalAggarwal/Linguista | main3.py | main3.py | py | 10,494 | python | en | code | 0 | github-code | 1 |
29455804140 | class Node:
def __init__(self, data=None):
self.data = data
self.nextNode = None
class SingleLinkedList:
def __init__(self):
self.headval = None
def traversList(self):
currval = self.headval;
while currval is not None:
print(currval.data)
... | IndikaMaligaspe/Python_here_and_there | datastructures/SingleLinkList.py | SingleLinkList.py | py | 2,482 | python | en | code | 0 | github-code | 1 |
29890050923 | from api_request import *
def main():
menu_text = "\n\t----Menu----\n"
intro_text = " 1. Get Character Data\n 2. Get Location Data\n 3. Get Episode Data\n\r"
print(menu_text)
user_id_input = input(intro_text)
if(user_id_input == "1"):
character_id_input = input("What is the Character Id?... | Malam2704/rmapi | deez.py | deez.py | py | 823 | python | en | code | 0 | github-code | 1 |
11923005618 | import datetime
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.builtin import CommandStart
from aiogram.types import InputFile
from handlers.helps.met_support import create_array_account_proxy, replaceter_text_in_aiogram
from handlers.users.som_inviter.a_in... | psiap/botsProject | handlers/users/som_spam/spam_hendler.py | spam_hendler.py | py | 3,523 | python | en | code | 0 | github-code | 1 |
34812847763 | def convertMillis(millis):
totalSecond=millis//1000
currentSecond=totalSecond%60
totalMinute=totalSecond//60
currentMinute=totalMinute%60
currentHour=totalMinute//60
time=str(currentHour)+':'+str(currentMinute)+':'+str(currentSecond)
return time
def main():
... | mediew/pynote | pyjclx/第6章/6_23.py | 6_23.py | py | 404 | python | en | code | 0 | github-code | 1 |
34523874515 | import sys
from ._argument_parser import get_giscli_argument_parser
from .command_handler import get_handler
def main():
parser = get_giscli_argument_parser()
args = parser.parse_args()
module_name = _get_fully_qualified_module_name(args)
try:
handler = get_handler(module_name)
handler... | jtroe/gis-cli | src/gis/__init__.py | __init__.py | py | 932 | python | en | code | 0 | github-code | 1 |
9863552294 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 3:
(080) is the area code for fixe... | Stuart88/udacity-data-structures-algorithms | Phase 1/P0/Task3.py | Task3.py | py | 3,046 | python | en | code | 0 | github-code | 1 |
23131468885 | from django.contrib.auth import get_user_model
from django.db import transaction
from django.utils.translation import ugettext as _
from openslides.core.config import config
from openslides.utils.autoupdate import inform_changed_data
from openslides.utils.exceptions import OpenSlidesError
from openslides.utils.rest_ap... | chrmorais/OpenSlides | openslides/agenda/views.py | views.py | py | 9,795 | python | en | code | null | github-code | 1 |
43658554993 | #program to print the largest and the smallest elements in array
arr = []
n = int(input("Enter the number of elements in numerical form :"));
for i in range(n):
element=int(input("Enter the elements in numerical form :"))
arr.append(element)
max = arr[0]
min = arr[0]
for i in range(n):
... | sagarahire07/Python-Practical | Practical 3/minandmax_in_array.py | minandmax_in_array.py | py | 500 | python | en | code | 0 | github-code | 1 |
73033849633 | # -*- coding: utf-8 -*-
'''
Module for gathering and managing network information
'''
# Import python libs
from __future__ import absolute_import
import datetime
import hashlib
import logging
import re
import os
import socket
# Import salt libs
import salt.utils
import salt.utils.decorators as decorators
import salt.... | shineforever/ops | salt/salt/modules/network.py | network.py | py | 32,604 | python | en | code | 9 | github-code | 1 |
35708849027 | '''
Author: 千仞无锋
Date: 2022-04-20 21:31:30
LastEditors: 千仞无锋
LastEditTime: 2022-04-20 22:36:20
FilePath: \20220411HTML_CSS\一个小插曲关于excel和py的\youtube_openpyxl_03.py
'''
import openpyxl
from openpyxl import Workbook, load_workbook
from openpyxl.utils import get_column_letter, column_index_from_string
from openpyxl.styles ... | asusfgg/20220411HTML_CSS | 一个小插曲关于excel和py的/youtube_openpyxl_03.py | youtube_openpyxl_03.py | py | 1,468 | python | en | code | 1 | github-code | 1 |
9454023907 | import random
star = input('請決定隨機數字範圍開始值:')
end = input('請決定隨機數字範圍結束值:')
r = random.randint(int(star), int(end))
count = 0
while True:
count += 1 # count = count + 1
num = input('請輸入數字:')
num = int(num)
if num == r:
print('恭喜你猜對了!')
print('這是你猜的第', count, '次')
break
elif num > r:
print('比答案大')
elif num <... | peteryng0619/guess-num | guess-num.py | guess-num.py | py | 486 | python | en | code | 0 | github-code | 1 |
20113334698 | import json
import os
import time
import uuid
from pathlib import Path
from typing import (
Any,
AsyncGenerator,
Coroutine,
Dict,
Generator,
Optional,
Tuple,
Union,
)
import tiktoken
from anthropic import Anthropic
from fastapi import HTTPException
from fastapi.responses import JSONResp... | TensorOpsAI/LLMstudio | llmstudio/engine/providers/provider.py | provider.py | py | 6,548 | python | en | code | 60 | github-code | 1 |
32918054625 | import logging
import os
import time
import asyncpraw
import discord
from discord.ext import tasks, commands
from cogs.commands import settings
log = logging.getLogger(__name__)
class RedditTask(commands.Cog):
""" Reddit Background Task """
def __init__(self, bot):
self.bot = bot
# Attempt... | richtan/chiya | cogs/tasks/reddit.py | reddit.py | py | 4,527 | python | en | code | null | github-code | 1 |
15814542538 | #!/usr/bin/env python
"""
Example application views.
Note that `render_template` is wrapped with `make_response` in all application
routes. While not necessary for most Flask apps, it is required in the
App Template for static publishing.
"""
import app_config
import json
import oauth
import static
from flask import... | PostDispatchInteractive/app-template | app.py | app.py | py | 2,843 | python | en | code | 1 | github-code | 1 |
3151897462 | import tkinter as tk
from tkinter import filedialog
from pynput.keyboard import Listener, Key
import datetime
# Set the maximum number of characters per line
max_characters_per_line = 50
current_line_length = 0
current_line = []
log_file_path = None
# Define a list of keys to exclude from recording
exclud... | DDimov03/Keylogger | keylogger.py | keylogger.py | py | 2,459 | python | en | code | 2 | github-code | 1 |
21200175313 | import time as t
scale = 50
print("执行开始".center(scale//2, "-"))
start = t.perf_counter()
for i in range(scale + 1):
a = '*' * i
b = '.' * (scale - i)
x = i / scale * 100
duration = t.perf_counter() - start
print("\r{:3.0f}%[{}->{}]{:.2f}s".format(x, a,b, duration), end="")
t.sleep(0.01)
print("... | china-university-mooc/Python-Basics | ChapterIII/Exercise/III.2-2-Text-Progress-Bar.py | III.2-2-Text-Progress-Bar.py | py | 371 | python | en | code | 0 | github-code | 1 |
30995285666 | from PythonClient import *
import sys
import time
client = AirSimClient('127.0.0.1')
print("Flying a small square box using moveByVelocityZ")
print("Try pressing 't' in the AirSim view to see a pink trace of the flight")
# AirSim uses NED coordinates so negative axis is up.
# z of -7 is 7 meters above the ... | geevargs/AirSim | PythonClient/box.py | box.py | py | 1,212 | python | en | code | null | github-code | 1 |
4251009863 | #!/usr/bin/pytho
import os
import shutil
def restore():
atual = os.path.dirname(os.path.abspath(__file__))
urlSrc = os.path.join(atual, 'default/urls.conf')
urlDest = os.path.join(os.path.dirname(atual), 'urls.conf')
print ("Copying from: "+urlSrc)
print ("Copying to: "+urlDest)
shutil.copyfile ( ... | brenoarosa/fileUpdater | src/default.py | default.py | py | 339 | python | en | code | 0 | github-code | 1 |
35010640604 | import datetime
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from drf_yasg.utils import swagger_auto_schema
from apps.commons.views import Pagination, MyPagination
from apps.posts.seriali... | Billionaire-Project/four_hours_service | apps/posts/views/post_my.py | post_my.py | py | 2,683 | python | en | code | 0 | github-code | 1 |
39840651273 | from collections import defaultdict
# location of kernel.implicit_dependencies
IMPL_DEP_FILE_STR = "../../smatch_data/kernel.implicit_dependencies"
OUTPUT_FILE_STR = "implicit_dependencies"
# struct fields to ignore, because they are too common
GLOBAL_BLACKLIST = [
('fd', 'file'),
]
# here we can manually add st... | illumos/illumos-gate | usr/src/tools/smatch/src/smatch_scripts/implicit_dependencies/constants.py | constants.py | py | 696 | python | en | code | 1,466 | github-code | 1 |
22249493114 | import sys
sys.path.append('../')
import time
#from controller.show_soilMoisture_5V import CSMS12
from controller.turn_on_bar_led import BarLED
from controller.show_voltage_3p3V import Potentionmeter
class SeviceWaterLight:
def __init__(self):
self.isWatering = False
def serve(self):
potentionmeter = ... | Masato23940/water_light | service/SeviceWaterLight.py | SeviceWaterLight.py | py | 774 | python | en | code | 0 | github-code | 1 |
6761293557 | from sPENminer import sPENminer
from oPENminer import oPENminer
from stream import Stream
import argparse
import sys
def parse_args():
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
... | SSDS-Croatia/SSDS-2020 | Day-4/Hands-on/persistence_evolving_networks/src/main.py | main.py | py | 3,286 | python | en | code | 4 | github-code | 1 |
7273039158 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This server watches for changes in log files and sends out updates to
subscribers via web sockets.
"""
import time
import subprocess
import select
import threading
from websocket_server import WebsocketServer
from baibaitrader.utils import build_logger
class TickerSer... | moppymopperson/baibai-trader | baibaitrader/TickerServer.py | TickerServer.py | py | 2,047 | python | en | code | 1 | github-code | 1 |
25142590976 | import torch
import torch.nn as nn
from typing import Dict, Any
from argparse import _ArgumentGroup
import argparse
import numpy as np
from .cnn import CNN, IMAGE_SIZE
class IvanoConv(nn.Module):
def __init__(self, in_dim: int, out_dim: int, kernel_size:int=3, stride:int=1, padding:int=1):
super().__in... | cluePrints/fsdl-text-recognizer-2021-labs | lab3/text_recognizer/models/line_cnn_ivan.py | line_cnn_ivan.py | py | 4,649 | python | en | code | null | github-code | 1 |
43563103032 | __version__ = "$Rev: 48541 $"
import datetime
import socket
import cx_Oracle
import despydb.errors as errors
import despymisc.miscutils as miscutils
# Construct a name for the v$session module column to allow database auditing.
import __main__
try:
_MODULE_NAME = __main__.__file__
except AttributeError:
_... | DarkEnergySurvey/despydb | python/despydb/oracon.py | oracon.py | py | 9,936 | python | en | code | 0 | github-code | 1 |
7853998639 | import torch
import detectron2.data.transforms as T
from detectron2.structures import Instances
from detectron2.layers import paste_masks_in_image
from detectron2.modeling import build_model
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.data import MetadataCatalog
from detectron2.checkpoint i... | gist-ailab/uoais | adet/utils/post_process.py | post_process.py | py | 6,482 | python | en | code | 110 | github-code | 1 |
22252250363 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import codecs
import time
import random
TEST = False
TIME_LIMIT = 10
random.seed(1)
def output_fld(fld):
with codecs.open('output.txt', 'w', 'utf-8') as f:
h = len(fld)
w = len(fld[0])
for y in range(h):
for x in range(w... | matscube/TopCoder | MM78/mm78.py | mm78.py | py | 6,468 | python | en | code | 0 | github-code | 1 |
27848165994 | import copy
import torch.nn as nn
import torch.optim as optim
from Net import Net
class Agent(object):
def __init__(self, LR, global_net_dict, label_length, output_length):
self.LR = LR
self.output_length = output_length
self.net = Net(label_length, self.output_length+1) # 由于取头取尾,所以加1
... | BobbyBBY/machine-learning-course | Agent.py | Agent.py | py | 1,245 | python | en | code | 0 | github-code | 1 |
410790070 | from werkzeug.routing import BaseConverter
class ListConverter(BaseConverter):
"""Matches one of the items provided. Items can either be Python
identifiers or strings::
Rule('/<any(about, help, imprint, class, "foo,bar"):page_name>')
:param map: the :class:`Map`.
:param items: this function accepts the pos... | inab/disease_perception | REST/libs/converters.py | converters.py | py | 1,036 | python | en | code | 2 | github-code | 1 |
43187275066 | from http import HTTPStatus
from typing import Any, Union, Optional, List, Dict
import allure
from assertions.constants import TYPE_NAMES
from assertions.formatters.assertions import MessageTemplate, AllureTemplates
from assertions.operators import Operators
from assertions.utils import prettify_json
def compare_ke... | Nikita-Filonov/assertions | assertions/assertions.py | assertions.py | py | 5,943 | python | en | code | 2 | github-code | 1 |
6690702578 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as data
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from dataloader.PennFudanPedDataset import PennFudanPedDataset
from model.deeplabv4 import Deeplabv4
device = tor... | wisnunugroho21/nugi_computer_vision | test.py | test.py | py | 1,518 | python | en | code | 0 | github-code | 1 |
73457857633 | from flask import Blueprint, request
from src.db.user import *
user = Blueprint("user", __name__)
@user.route("/api/user/register", methods=["POST"])
def register():
print(request.json) # dict
body = request.json
arg_list = list(body.values())
res = user_register(arg_list)
return {
"resu... | xkyang00/Web-Development-Technology---Experiment---Good-Community---Backend | src/api/user_api.py | user_api.py | py | 1,480 | python | en | code | 0 | github-code | 1 |
16954714999 | # Link For Problem: https://leetcode.com/problems/shortest-path-in-binary-matrix/
from collections import deque
class Solution:
"""
Apply Standard BFS Algorithm.
TC : O(mn)
SC : O(mn)
"""
def shortestPathBinaryMatrix(self, grid: list[list[int]]) -> int:
if grid[0][0] o... | loopclub2022/MonthLongChallenge | Anurag_19_CSE/Python/day16.py | day16.py | py | 1,171 | python | en | code | 9 | github-code | 1 |
75121909153 | import math
import cv2
import mediapipe as mp
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands
font = cv2.FONT_HERSHEY_SIMPLEX
# 0 For webcam input:
cap = cv2.VideoCapt... | himanshurajofficials/Virtual-Steering | steering.py | steering.py | py | 6,093 | python | en | code | 1 | github-code | 1 |
34578145185 | import os, json, timeit
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics import accuracy_score
from sklearn.manifold import TSNE
from param import *
with open(set_path) as json_file:
set_dict = json... | JeffT13/rd-diarization | RDSV/run_LR.py | run_LR.py | py | 2,632 | python | en | code | 4 | github-code | 1 |
34197031360 | years = input('Введите количество лет от 1 до 99: ')
if years != '':
years = int(years)
if years >= 1 and years < 100:
end = years % 10
if years >= 11 and years < 21:
age = 'лет'
elif end == 1:
age = 'год'
elif end >= 2 and end < 5:
age = 'года'
else:
age = 'лет'
print('Мне {}... | mash2000/famen | task11/task11-b.py | task11-b.py | py | 513 | python | ru | code | 0 | github-code | 1 |
11834773534 | """
Author: @sohamroy19
Date: 12/12/2020
This script prints the number of messages sent by a WhatsApp user,
given the exported chat as 'chat.txt'.
"""
import re
# open the file
f = open("chat.txt", encoding="utf8")
# idk how to use map data structure
senders = []
counts = []
total = 0
# read line b... | sohamroy19/miscellaneous | Tools/WhatsapperStatsOld.py | WhatsapperStatsOld.py | py | 1,001 | python | en | code | 0 | github-code | 1 |
1158470099 | import cv2
import numpy as np
import argparse
import os
def draw_mask(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
param['drawing'] = True
param['current_contour'].append((x, y))
elif event == cv2.EVENT_MOUSEMOVE:
if param['drawing'] == True:
cv2.circle(par... | rawalkhirodkar/egohumans | egohumans/external/mmpose/tools/seg_vitpose/draw_seg_bbox.py | draw_seg_bbox.py | py | 3,281 | python | en | code | 16 | github-code | 1 |
6503914532 | from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: azure_rm_automationhybridrunbookworkergroup_facts
version_a... | testormoo/ansible-azure-complete | modules/library/azure_rm_automationhybridrunbookworkergroup_facts.py | azure_rm_automationhybridrunbookworkergroup_facts.py | py | 6,237 | python | en | code | 0 | github-code | 1 |
5957018529 | """
aoe2netwrapper.converters
-------------------------
This module implements a high-level class with static methods to convert result of AoENetAPI methods to
pandas DataFrames.
"""
from typing import List
from loguru import logger
from aoe2netwrapper.models import (
LastMatchResponse,
LeaderBoardResponse,
... | fsoubelet/AoE2NetAPIWrapper | aoe2netwrapper/converters.py | converters.py | py | 16,817 | python | en | code | 3 | github-code | 1 |
4868259954 | from __future__ import print_function
import logging
import os
import random
import time
import signal
from relaax.client import rlx_client
from . import game_process
def run(rlx_server_url, env, seed):
n_game = 0
game = game_process.GameProcessFactory(env).new_env(_seed(seed))
def toggle_rendering():... | j0k/relaax | environments/OpenAI_Gym/environment.py | environment.py | py | 1,962 | python | en | code | 2 | github-code | 1 |
17269321258 | import logging
from django.conf import settings
from sqlalchemy.exc import OperationalError
from receval.apps.explorer.experiments import BaseExperiment
from sqlalchemy import create_engine
from sqlalchemy.sql import text
logger = logging.getLogger(__name__)
class ZbMath(BaseExperiment):
db = None
def get... | gipplab/docker-receval | receval/apps/explorer/experiments/zbmath.py | zbmath.py | py | 2,774 | python | en | code | 1 | github-code | 1 |
18903749297 | from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('books', views.books),
path('register', views.register),
path('login', views.login),
path('logout', views.logout),
path('books/add', views.addBook),
path('submitBook', views.submitBook),
path('b... | LeuJames/dojoReadsProj | dojoReadsApp/urls.py | urls.py | py | 519 | python | en | code | 0 | github-code | 1 |
20412602396 | import os
import re
import tkinter as tk
from os import path as op
from tkinter import filedialog as fd
from tkinter import messagebox as mb
def is_num(data):
"""判断字符串是否为数字"""
try:
int(data)
return True
except:
return False
def go_split(s, symbol):
# 拼接正则表达式
symbol = "[" ... | Sakwya/pyscript | pyscripts/rename_h_file/rename_h_file.py | rename_h_file.py | py | 2,993 | python | en | code | 0 | github-code | 1 |
7117347435 | # This code converts integer to string without using the str() function
# by using the % and //
# 123 %10 gives 3
# 123 // 10 gives 12
def convert_to_string(input_int):
# if input_int.isalpha():
# return 'requires an integer value'
if input_int < 0:
isNegative = True # to catch the neegative ... | Theeyecode/python_alg | lucid/integer_tostring.py | integer_tostring.py | py | 1,012 | python | en | code | 0 | github-code | 1 |
73654171233 | import os
from qgis.PyQt.QtCore import Qt, QTimer
from qgis.gui import QgsRubberBand
from qgis.core import (
QgsCoordinateTransform,
QgsRectangle,
QgsPoint,
QgsPointXY,
QgsGeometry,
QgsWkbTypes,
QgsProject,
)
from qgis.PyQt import QtWidgets, uic
from qgis.PyQt.QtCore import pyqtSignal
from... | danylaksono/GeoKKP-GIS | modules/gotoxy.py | gotoxy.py | py | 3,135 | python | en | code | 2 | github-code | 1 |
14811425392 | # -*- coding: utf-8 -*-
"""
Date:17.4.26
Description:
打算开始上机器学习基石了,但不知道这个课总共有多久,于是写了这个,原谅我的懒……
计算结果是15:30:54
@author: Drapor
"""
import re
import urllib2
url='https://www.youtube.com/playlist?list=PLXVfgk9fNX2I7tB6oIINGBmW50rrmFTqf'
request = urllib2.Request(url)
response = urllib2.urlopen(request)
content = ... | GabrielDrapor/MyCrawlerGadget | Findout_the_total_time_of_a_playlist.py | Findout_the_total_time_of_a_playlist.py | py | 676 | python | en | code | 0 | github-code | 1 |
72597110114 | from unittest.mock import call, ANY
import pytest
from pki_file import PKIFile, KEY_ALGORITHMS, SIGNING_ALGORITHMS
from cryptography.hazmat.primitives.asymmetric import rsa, ec
from cryptography.hazmat.primitives import serialization
CWD = 'zion'
CERT_FILE_PATH = 'matrix/trinity'
PRIV_KEY_PATH = 'matrix/neo'
CERTIFICA... | awslabs/aws-greengrass-labs-certificate-rotator | tests/artifacts/test_pki_file.py | test_pki_file.py | py | 8,688 | python | en | code | 6 | github-code | 1 |
32292737225 | from drg_group.yinchuan_2023.Base import message,intersect,SS_VALID
from drg_group.yinchuan_2023.DRG import MDCQ_DRG
def group(record):
adrg_zd=["D13.901","D18.000x044","D18.100x023","D58.000","D73.100","D73.400","D73.500","D73.501","D73.805","R16.100x001","S36.002"]
adrg_zd1=[]
adrg_ss=["41.2x03","41.4200x002",... | OpenDRG/DRG_Python | drg_group/yinchuan_2023/ADRG/QB1.py | QB1.py | py | 830 | python | en | code | 20 | github-code | 1 |
72966899875 | import copy
import numpy
class Monkey:
def __init__(self):
self.items = []
self.operation = ''
self.test = {
'divisibleby': 0,
'true': 0,
'false': 0
}
self.inspected = 0
def __str__(self):
o = ''
o += f"Items :... | junyian/adventofcode-2022 | 11/11.py | 11.py | py | 3,112 | python | en | code | 0 | github-code | 1 |
40834821563 | import os
import pandas as pd
import rampwf as rw
from rampwf.workflows import FeatureExtractorRegressor
from rampwf.workflows import FeatureExtractorClassifier
from rampwf.score_types.base import BaseScoreType
from sklearn.model_selection import GroupShuffleSplit
from sklearn.model_selection import StratifiedSh... | camcochet/Severity-Accident-Classification | problem.py | problem.py | py | 3,245 | python | en | code | 1 | github-code | 1 |
12237235101 | from collections import defaultdict
n = int(input())
grid = []
for i in range(n):
row = list(map(int, input().split()))
cur = []
for j in range(n):
if row[j]:
cur.append(j+1)
print(len(cur), *cur)
| amanyih/Competitive-Programming | from_adjacency_matrix_to_list.py | from_adjacency_matrix_to_list.py | py | 236 | python | en | code | 2 | github-code | 1 |
70544299234 | from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['keras','google-cloud-storage']
setup(
name='trainer',
version='0.1',
install_requires=REQUIRED_PACKAGES,
include_package_data=True,
description='My trainer application package.',
packages=find_packages()
)
| bsinger98/subreddit-simulator-dataminer | setup.py | setup.py | py | 320 | python | en | code | 0 | github-code | 1 |
3734379309 | from flask import Flask,request,render_template,flash,redirect
import requests
app=Flask(__name__)
app.secret_key="secret key"
@app.route("/",methods=['GET','POST'])
def main():
if request.method=='POST':
try:
city_name=request.form['name']
print(city_name)
url =... | Kalyug5/weather | app.py | app.py | py | 1,302 | python | en | code | 0 | github-code | 1 |
1704634248 | import sys
input = sys.stdin.readline
n = int(input())
Stairs = [0]
for i in range(n):
Stairs.append(int(input()))
memo = [[0 for j in range(n+1)] for i in range(3)]
# 0 -> 다음으로 갈 수 있음
# 1 -> 다음으로 못감
# 2 -> 최대값
memo[0][1] = Stairs[1]
memo[2][1] = Stairs[1]
if n >=2:
memo[0][2] = Stairs[2]
memo[1][2] = Stai... | SunghunKim98/Algorithm_Study | sprint09/KMS/FW/BOJ_2579.py | BOJ_2579.py | py | 574 | python | en | code | 0 | github-code | 1 |
4340315176 | #15min
def isLuckyNum(n):
for ch in str(n):
if ch != '4' and ch != '7':
return False
return True
n = int(input())
for i in range(1,n+1):
if n % i == 0:
if isLuckyNum(int(n/i)):
print('YES')
exit()
print('NO') | JaeguKim/PSAssistant | test/Codeforces/A2OJ Ladder 13/luckyDivision.py | luckyDivision.py | py | 273 | python | en | code | 0 | github-code | 1 |
39793659658 |
from cx_Freeze import setup, Executable
# On appelle la fonction setup
buildOptions = dict(
includes=["pygame.py"],
include_files=["fichier1.txt", "mon_icone.ico"]
)
setup(
name="BoumeurMan",
version="1",
description="Projet Terminale 2021",
executables=[Executable("main.py")],... | LeadCreep/BombermanLan | setup.py | setup.py | py | 325 | python | en | code | 1 | github-code | 1 |
41138681273 | import numpy as np
from JorGpi.POSCARloader import POSCARloader
class KPOINTS:
def __init__(self,POSCAR="POSCAR",resolution=0.001):
self.multipliers = np.arange(1.0,89,resolution)
loader = POSCARloader(POSCAR)
loader.parse()
self.directions = loader()['directions']
self.foun... | MaterialDesigner/JorG | JorGpi/utilities/KPOINTS/kpoints.py | kpoints.py | py | 1,555 | python | en | code | 0 | github-code | 1 |
44012534609 | import time
import heapq
def Scheduling(Arrival,Burst):
clock=0
n=len(Arrival)
ReadyQueue=[]
heapq.heapify(ReadyQueue)
Completion=[0 for i in range(len(Burst))] # clock time at completion
Copy=[] # to detect if a process is already transferred to ReadyQueue
for i in range(len(Arrival)): #puting in proc... | jayeshlohani/DynamicRoundRobin | Final.py | Final.py | py | 2,608 | python | en | code | 0 | github-code | 1 |
13582022769 | n=int(input()) # read input n
for i in range(n): # for each in in range between 0 and n
a,b,c=map(int,input().split(" ")) # raed inputs of number of cats and dogsand legs
c1=a+b
c2=c1*4
if(c1==2 and c%4==0): #if c1 satisfies the condition ... | RagaPraneeth7/question6 | question6.py | question6.py | py | 525 | python | en | code | 0 | github-code | 1 |
13361453446 | import time
from datetime import datetime
import numpy as np
np.random.seed(50000)
class Conv():
def __init__(self, in_channels, out_channels, kernel_size, stride, padding=0):
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
... | Yuval938/convolution-network-from-scratch | NN/Layers.py | Layers.py | py | 15,954 | python | en | code | 0 | github-code | 1 |
17959572668 | # 숫자 다루기
# 자연수 35를 뒤집으면 53이 되고, 각 자리수를 합하면 8이 된다. 또,
# 1200을 뒤집으면 21이 되고, 각 자릿수를 합하면 3이 된다.
# 즉, 뒤집었을 때 불필요한 0은 무시된다.
# 자연수 N이 입력되면 그 수를 뒤집은 수와 각 자릿수의 합을 출력하는
# 프로그램을 작성하시오.
# 자연수 N이 입력된다. (1≤N≤1,000,000)
# 1. 첫째 줄에 뒤집은 수를 출력한다.
# 2. 둘째 줄에 각 자릿수의 합을 출력한다.
# method 1
n = input()
st, s = 0, 0
for i in range(len(n)-1, -1,... | junes7/python_algorithm | CodeUp/deep_problem/4041.py | 4041.py | py | 749 | python | ko | code | 1 | github-code | 1 |
24877079903 | import contextlib
from typing import Any, Generator
import pytest
import responses
from pyastrosalt.auth import login as auth_login
# Prevent accidental real HTTP requests.
# Source: https://blog.jerrycodes.com/no-http-requests/
from pyastrosalt.web import api_url
@pytest.fixture(autouse=True)
def no_http_requests... | saltastroops/PyAstroSALT | tests/conftest.py | conftest.py | py | 1,347 | python | en | code | 0 | github-code | 1 |
213771692 | import string
from itertools import permutations
import random
import sys
# Counter class to keep track of fitness evaluations
class Counter:
def __init__(self):
self.__value = 0
def inc(self):
self.__value += 1
def get(self):
return self.__value
# Solution class represents a po... | Haim5/GeneticAlgorithm | src/geneticAlgorithm.py | geneticAlgorithm.py | py | 15,672 | python | en | code | 0 | github-code | 1 |
33468382901 | from __future__ import absolute_import, division
import time
import psychopy
from psychopy import sound, gui, visual, core, data, event
import pandas as pd
import numpy as np # whole numpy lib is available, prepend 'np.'
import os # handy system and path functions
import matplotlib.pyplot as plt
import math
import se... | ortegauriol/ShootingPy | ShootPy.py | ShootPy.py | py | 22,448 | python | en | code | 0 | github-code | 1 |
7460013163 | import sys
sys.stdin = open("input.txt")
T = int(input())
for tc in range(1, T+1):
N, M = map(int, input().split())
weights = list(map(int, input().split())) # N개
trucks = list(map(int, input().split())) # M개
weights.sort(reverse=True) # 큰 것부터 욱여넣으려고
trucks.sort(reverse=True)
... | coolihans/TIL | Algorithms/swea/L5201_컨테이너운반/장한나.py | 장한나.py | py | 733 | python | en | code | 0 | github-code | 1 |
3002917118 | #!/usr/bin/env python
# -*- coding: utf-8-*-
import xml.etree.ElementTree as ET
import tarfile
import zipfile
import re
from pathlib import Path
import shutil
import os
import pymysql
import sys
import traceback
import subprocess
import getpass
import Archive as archive
if __name__ in '__main__':
# xml用ルートディレクトリ
... | rise-pat/patent | fulltxt/ArchiveFiles.py | ArchiveFiles.py | py | 4,734 | python | en | code | 0 | github-code | 1 |
11109751286 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Purchase Bot.
Usage: This bot records the spendings in the database and makes monthly and weekly reports.
Press Ctrl-C on the command line to stop the bot.
"""
import psycopg2
import logging
import re
import datetime
import random
import argparse
from telegram import ... | TaniaVK/purchase-bot | purchase-bot.py | purchase-bot.py | py | 14,087 | python | en | code | 1 | github-code | 1 |
4200222745 | def solution(record):
answer = []
dic = {}
for i in record:
action = i.split(' ')
if action[0] == "Enter":
dic[action[1]] = action[2]
answer.append((action[1]+"님이 들어왔습니다."))
elif action[0] == "Leave":
answer.append((action[1]+"님이 나... | hyeonwook98/Algorithm | Programmers/오픈채팅방.py | 오픈채팅방.py | py | 693 | python | en | code | 0 | github-code | 1 |
72358344355 | class Solution:
def equalFrequency(self, word: str) -> bool:
freq = [0] * 26
for w in word:
freq[ord(w) - ord('a')] += 1
for i in range(26):
if freq[i] == 0:
continue
freq[i] -= 1
f = set(w for w in freq if w > 0)
if... | lyzsk/leetcode-solutions | python-solutions/2423-remove-letter-to-equalize-frequency/solution.py | solution.py | py | 408 | python | en | code | 3 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.