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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
21478478680 | import logging, datetime, sys
from modules import *
args = parser.parse_args()
start_time = datetime.datetime.now()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# create a file handler for INFO
handler = loggi... | greird/the-release-note | the-release-note.py | the-release-note.py | py | 3,711 | python | en | code | 2 | github-code | 6 |
21256935702 | # 500 Exercícios Resolvidos com Python
# Thiago Barros
# Exercícios resolvidos com base no Livro - 500 Algoritimos Resolvidos (ANITA LOPES E GUTO GARCIA)
# Algoritimo Numero 122
# Capitulo 3
"""
Ler três números e verificar se os três números são possiveis de
serem lados de um triângulo
"""
lde1 = float(input("Ent... | Tbarros1996/500algoritmos | Capitulo_3/algoritmo_122.py | algoritmo_122.py | py | 670 | python | pt | code | 0 | github-code | 6 |
39404813463 | from django.urls import path
from .views import (
ColaboradorList,
ColaboradorUpdate,
ColaboradorDelete,
ColaboradorCreate,
ColaboradorReport,
HtmlPdf,
)
urlpatterns = [
path('listar', ColaboradorList.as_view(), name='list_colaborador'),
path('criar', ColaboradorCreate.as_view(), name=... | fabiogpassos/GRH | apps/colaboradores/urls.py | urls.py | py | 664 | python | es | code | 0 | github-code | 6 |
10033128545 | # Créé par LEWEEN.MASSIN, le 23/03/2023 en Python 3.7
from csv import reader as read
file = '49-prenoms-2013-22.csv'
name = 'Aaron'
gender = 'F'
year = 2019
def import_table(file):
l=[]
with open(file, 'r') as csv_open:
csv_read = read(csv_open, delimiter=';')
for row in csv_read:
... | Remingusu/NSI_premiere | 7 - Traitement de données en tables/Projet Traitement de données en tables/main.py | main.py | py | 957 | python | en | code | 0 | github-code | 6 |
43193667766 | #!/usr/bin/env python
import rospy
import smach
from PrintColours import *
from std_msgs.msg import String,UInt8
from mavros_msgs.msg import ExtendedState
# import custom message:
from muav_state_machine.msg import UAVState
# global variables to catch the data from the agent state machine node
airframe_type = ""
mis... | miggilcas/muav_state_machine | scripts/GStates/uav_state.py | uav_state.py | py | 4,040 | python | en | code | 0 | github-code | 6 |
43431937253 | #!/usr/bin/env python3
""" Evaluator """
import sys
import tensorflow as tf
from utils import decode_img, image_patches, write_tensor_as_image
from model import image_diff, UPSCALER_FACTOR
def main():
""" Main function """
try:
image_path = sys.argv[1]
except:
print("Usage: {} <image path>... | Masterchef365/ENHANCE | eval.py | eval.py | py | 1,123 | python | en | code | 0 | github-code | 6 |
17529991766 | import os, glob, asyncio
class CommandDispatcher:
"""Register commands and run them"""
def __init__(self):
self.commands = {}
self.commands_admin = []
self.unknown_command = None
def get_admin_commands(self, bot, conv_id):
"""Get list of admin-only commands (set by plugins... | xmikos/hangupsbot | hangupsbot/commands/__init__.py | __init__.py | py | 2,229 | python | en | code | 105 | github-code | 6 |
7165790234 | import argparse
import logging
import sys
from itertools import chain
from logging import getLogger
from typing import Iterable, Optional, Union
from competitive_verifier import oj
from competitive_verifier.arg import add_verify_files_json_argument
from competitive_verifier.error import VerifierError
from competitive_... | competitive-verifier/competitive-verifier | src/competitive_verifier/download/main.py | main.py | py | 2,823 | python | en | code | 8 | github-code | 6 |
34199641942 | #!/usr/bin/env python
import sys
import rospy
from art_collision_env.int_collision_env import IntCollisionEnv
import os
def main():
rospy.init_node('collision_env_node', anonymous=True)
try:
setup = os.environ["ARTABLE_SETUP"]
except KeyError:
rospy.logfatal("ARTABLE_SETUP has to be set... | robofit/arcor | art_collision_env/src/node.py | node.py | py | 551 | python | en | code | 9 | github-code | 6 |
10918517772 | """ Plugin entry point for helga """
import math
from craigslist_scraper.scraper import scrape_url
from helga.plugins import match
TEMPLATE = 'Listing title: {}, price: {}'
@match(r'[A-Za-z]+\.craigslist\.org/.../\S+')
def craigslist_meta(client, channel, nick, message, match):
""" Return meta information about a... | narfman0/helga-craigslist-metadata | helga_craigslist_meta/plugin.py | plugin.py | py | 538 | python | en | code | 0 | github-code | 6 |
3682557651 | class MapFlags(object):
__slots__ = ('_value')
name = 'tmwa::map::MapFlags'
enabled = True
def __init__(self, value):
self._value = value['flags']
def to_string(self):
i = int(self._value)
s = []
for n, v in MapFlags.junk:
v = 1 << v
if i & v... | themanaworld/tmwa | src/map/mapflag.py | mapflag.py | py | 2,048 | python | en | code | 48 | github-code | 6 |
11353299783 | """
Problem Statement
Given a binary tree, populate an array to represent its level-by-level traversal.
You should populate the values of all nodes of each level from left to right in separate sub-arrays.
"""
from collections import deque
class TreeNode:
def __init__(self, val):
self.val = val
se... | jihoonyou/problem-solving | Educative/bfs/example1.py | example1.py | py | 1,137 | python | en | code | 0 | github-code | 6 |
6533110297 | #!/usr/bin/python3
#-*- coding: utf-8 -*-
from moduls.data import *
from PyQt4 import QtGui, QtCore, uic
# StudentData = StudentData()
class MainWindow(QtGui.QMainWindow):
"""docstring for MainWindow"""
def __init__(self):
super(MainWindow, self).__init__()
self.ui = uic.l... | TchippunkT/Kursuch | moduls/windows/MainWindow.py | MainWindow.py | py | 1,129 | python | en | code | 0 | github-code | 6 |
24993496301 | from osv import fields
from osv import osv
class dm_address_segmentation(osv.osv): # {{{
_inherit = "dm.address.segmentation"
_description = "Order Segmentation"
def set_address_criteria(self, cr, uid, ids, context={}):
sql_query = super(dm_address_segmentation,self).set_address_criteria(cr, uid, ... | factorlibre/openerp-extra-6.1 | dm_extract_sale/dm_extract_sale.py | dm_extract_sale.py | py | 6,108 | python | en | code | 9 | github-code | 6 |
20172575137 | import os
import sys
from typing import Optional
from dotenv import load_dotenv
from spinner import Spinner
import actions
import response_parser
import speech
import gpt
message_history = []
GENERAL_DIRECTIONS_PREFIX = """
CONSTRAINTS:
- Cannot run Python code that requires user input.
ACTIONS:
- "TELL_USER": t... | rokstrnisa/RoboGPT | robogpt/main.py | main.py | py | 4,135 | python | en | code | 264 | github-code | 6 |
25874708021 | class MyClass:
nome: str
cognome: str
def __init__(self, nome, cognome):
self.nome = nome
self.cognome = cognome
mc = MyClass(nome = "Roberto", cognome = "Gianotto")
print(mc)
print(mc.nome)
print(mc.cognome) | pinguinato/corso-python | esercizi/type_annotations/myclass.py | myclass.py | py | 239 | python | la | code | 0 | github-code | 6 |
11000393367 | import typing as T
from datetime import datetime, timedelta
from pydantic import BaseModel
from mirai import (
Mirai, Member, Friend,
MessageChain, At
)
from .alias import MESSAGE_T
# https://mirai-py.originpages.com/tutorial/annotations.html
Sender = T.Union[Member, Friend]
Type = str
def reply(app: Mirai... | Lycreal/MiraiBot | plugins/_utils/__init__.py | __init__.py | py | 2,146 | python | en | code | 70 | github-code | 6 |
33608143285 | # 1 Перевести строку в массив
# "Robin Singh" => ["Robin”, “Singh"]
# "I love arrays they are my favorite" => ["I", "love", "arrays", "they", "are", "my", "favorite"]
rob = "Robin Singh"
fav = "I love arrays they are my favorite"
def robin(rob):
rob = list(rob)
return rob
robin(rob)
robin(fav)
# 2 Дан спи... | visek8/-QAP12OnlVikanas | home_work/hw_4/types.py | types.py | py | 1,345 | python | ru | code | 0 | github-code | 6 |
74280782907 | import pandas as pd
import numpy as np
from xgboost import XGBClassifier
from metrics import macro_f1
import settings
import pickle
import gc
import time
class BCXGBTrainer:
def __init__(self, config, logger):
self.config = config
self.model_params = config['model_params']
self.training_pa... | lim-hyo-jeong/DACON-Breast-Cancer | xgb_trainer.py | xgb_trainer.py | py | 5,105 | python | en | code | 4 | github-code | 6 |
36030628166 | """Countdown/Stopwatch functionalities."""
import subprocess
import threading
import time
import traceback
from abc import (
ABC,
abstractmethod,
)
from pathlib import Path
from typing import (
List,
Optional,
Union,
)
from overrides import overrides
import albert as v0
import gi # isort:skip
gi.... | ppablocruzcobas/Dotfiles | albert/clock/__init__.py | __init__.py | py | 11,096 | python | en | code | 2 | github-code | 6 |
28313903181 | from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QMenuBar, QAction, QTextEdit, QHBoxLayout, QWidget, QFontDialog, QColorDialog, QFileDialog, QDialog, QVBoxLayout, QMessageBox
from PyQt5 import QtGui, QtCore
from PyQt5.QtGui import QIcon
from PyQt5.QtPrintSupport import QPrinter, QPrintDialog, QPri... | schnuppi1984/Easy-Text-Editor | start.py | start.py | py | 6,702 | python | en | code | 0 | github-code | 6 |
25159533855 | import psycopg2
import random
con=psycopg2.connect('dbname=ecommerce_db user=postgres port=5432 host=localhost password=Murad2004')
cur=con.cursor()
def show(cursor):
cur.execute(query)
length = 30
print(*[desc[0].ljust(30) for desc in cursor.description], sep='')
print('-'*140)
result = cur.fetc... | MuradAsadzade/Postresql-join-tasks | ecommerce.py | ecommerce.py | py | 13,617 | python | en | code | 0 | github-code | 6 |
21322953683 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Camel: A dos game ported to a cross platform solution.
Was originally: Camel Source Code for the BrailleNote, written in Rapid Euphoria
Original author: Louis Bryant
Modified by Nathaniel Schmidt <schmidty2244@gmail.com>
Date modified: 09/09/2020; 23/01/2021... | njsch/camel | camel.py | camel.py | py | 13,805 | python | en | code | 0 | github-code | 6 |
1824122729 | from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from book.models import BookInfo
# Create your views here.
################################# Request #######################################################################################################################... | guoxi-xixi/django_base | bookmanager03/book/views.py | views.py | py | 8,205 | python | zh | code | 0 | github-code | 6 |
31788132323 | from typing import TYPE_CHECKING, Iterable, List, Optional, Union, overload
from ..builtins import types
from ..common.error import ConstraintError
from ..node import (
ArrayTypeNode,
FuncTypeNode,
PointerTypeNode,
SimpleTypeNode,
TypeNode,
)
if TYPE_CHECKING:
from .block import Expression
c... | jedevc/fyp | vulnspec/graph/chunk.py | chunk.py | py | 6,242 | python | en | code | 0 | github-code | 6 |
21275819456 | """Defines all necessary networks for training / evaluation
"""
from typing import Optional, Tuple
import mindspore.nn as nn
from mindspore import Tensor
from .backbones import Backbone
from .decoders import Decoder
from .heads import Head
from .loss import Loss
from .necks import Neck
class Net(nn.Cell):
"""Cr... | mindspore-lab/mindpose | mindpose/models/networks.py | networks.py | py | 2,807 | python | en | code | 15 | github-code | 6 |
10678150202 | import asyncio
from typing import List, Any, Set, Dict
import orjson
import websockets
from websockets import WebSocketServerProtocol
from blockchain import Blockchain
from block import Block
from transaction import Transaction
from utils import send, handle
class WsNode:
def __init__(self, domain: str):
... | XmasApple/simple_blockchain | ws_node.py | ws_node.py | py | 3,756 | python | en | code | 0 | github-code | 6 |
16563057746 | import numpy as np
import time, cv2, copy, os, random, sys
# Check if Running On Pi
import io
import os
def is_raspberrypi():
try:
with io.open('/sys/firmware/devicetree/base/model', 'r') as m:
if 'raspberry pi' in m.read().lower(): return True
except Exception: pass
return False
fr... | Rolling-Blocks/RB-CODE-Prototype-1 | image_processor.py | image_processor.py | py | 4,098 | python | en | code | 1 | github-code | 6 |
72486084988 | n = int(input("Enter the value of n: "))
for i in range(11, n+1):
# Divisible by both 3 & 7
if i % 21 == 0:
print("TipsyTopsy")
elif i % 7 == 0:
print("Topsy")
elif i % 3 == 0:
print("Tipsy")
else:
print(i)
| arnab7070/BeyondCoding | Python Programs/AOT IT Workshop/Final Lab Exam Revison/question14.py | question14.py | py | 260 | python | en | code | 1 | github-code | 6 |
31236652781 | from youtube3.youtube import *
import json
from oauth2client.tools import argparser
import re
def process_videos(workDir='.', inputFile='liked.json', recommendedFile='recommended.json',
excludedFile='excluded.json', postponedFile='postponed.json',maxCount=5):
recommended, excluded, postponed,... | diegoami/DA-youtube-scripts | youtube-scripts/recommend_videos.py | recommend_videos.py | py | 6,021 | python | en | code | 0 | github-code | 6 |
14175992166 | import math
import random
import copy
import numpy
import numpy as np
file = open("australian.dat", "r")
l = []
for line in file:
l.append(line.split())
wynik = []
for i in l:
wynik.append(list(map(lambda e: float(e), i)))
mojalista = wynik
def MetrykaEuklidesowa(listaA, listaB):
tmp = 0
for i in ra... | Tomasz-Wegrzynowski/MetodyInzWiedzy | main.py | main.py | py | 16,554 | python | pl | code | 0 | github-code | 6 |
8099610278 | from datetime import datetime
import os
# from dataclasses import dataclass
from sensor.constant.trainingPipeline_consts import *
class TrainingPipelineConfig:
def __init__(self, timestamp=datetime.now()):
timestamp = timestamp.strftime("%m_%d_%Y_%H_%M_%S")
self.pipeline_name: str = PIPELINE_N... | sverma1999/sensor-fault-detection | sensor/entity/config_entity.py | config_entity.py | py | 1,269 | python | en | code | 1 | github-code | 6 |
70945141308 | # 동이름으로 주소 찾기
try:
dong = input('동이름 입력 :')
#print(dong)
with open('zipcode.txt', mode='r', encoding='euc-kr') as f:
line = f.readline() # readline은 한줄, readlines는 모두 다 읽어옴
#print(line)
while line:
lines = line.split('\t') # 구분자는 tab
#print(li... | kangmihee/EX_python | pypro1/pack2/fio3.py | fio3.py | py | 698 | python | en | code | 0 | github-code | 6 |
27260039230 | """We are the captain of our ships, and we stay 'till the end. We see our stories through.
"""
"""290. Word Pattern
"""
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
word_map, pattern_map = {}, {}
words = str.split(" ")
n = len(words)
m = len(pattern)
... | asperaa/back_to_grind | bactracking/290. Word Pattern.py | 290. Word Pattern.py | py | 582 | python | en | code | 1 | github-code | 6 |
73886305466 | """
Author: Huang liuchao
Contact: huanglc50@chinaunicom.cn
Datetime: 2020/9/16 15:55
Software: PyCharm
File description:
"""
import hlc_common_utils as hcu
import onenet_warning_utils as owu
import os
import openpyxl
from openpyxl import load_workbook
import pandas as pd
from pathlib impor... | hlc0216/alarm_think | venv/Include/onenet_warning1/get_onenet_unique_warning.py | get_onenet_unique_warning.py | py | 5,097 | python | zh | code | 1 | github-code | 6 |
35860574373 | # Anything encountered around the map
objects = {
# things to potentially find at different map locations
"empty" : {
"desc" : "nothing here"
},
"chest" : {
"desc" : "a treasure chest full of valuables"
},
"enemy" : {
"desc" : "some armed and hostile warriors"
},
... | bpoulin7/ben_p_rpg_map | objects.py | objects.py | py | 479 | python | en | code | 0 | github-code | 6 |
24543736299 | import sys
data = sys.stdin.read().strip()
sum = 0
for row in data.split('\n'):
min = None
max = None
for value in row.split():
value = int(value)
if min is None or value < min:
min = value
if max is None or value > max:
max = value
sum += max - min
prin... | jonaskrogell/adventofcode2017 | 2.py | 2.py | py | 335 | python | en | code | 0 | github-code | 6 |
23268756998 | def check_true_matrix(column_, matrix_):
for line in matrix_:
if len(line) != column_:
raise ValueError('Не правильно введены данные(Data entered incorrectly)')
if __name__ == '__main__':
line_A, column_A = map(int, (input("Количество строк и столбцов матрицы A(Matrix Size A): ").split(... | Salazhiev/CalculatorMatrix | multiplication_matrix.py | multiplication_matrix.py | py | 1,479 | python | en | code | 0 | github-code | 6 |
36321955212 | import os
import re
import sys
import glob
import shutil
import pdftotext
def extract_Text_pdf(pdfdir):
print("Starting Text Extraction for pdf files......")
number_of_files = str(len([item for item in os.listdir(pdfdir) if os.path.isfile(os.path.join(pdfdir, item))]))
print("Processing ("+ number_of_fi... | mstatt/Udemy_HighSpeedDataAnalysis | 3_PDF_Text_Extraction/pdf_text_extraction.py | pdf_text_extraction.py | py | 1,272 | python | en | code | 2 | github-code | 6 |
25002203831 | from osv import fields, osv
class copy_verification_lines(osv.osv_memory):
"""
Copy Verification Lines
"""
_name = "copy.verification.lines"
_description = "Copy Verification Lines"
_columns = {
'audit_src': fields.many2one('mgmtsystem.audit','Choose audit'),
}
def copy(self, ... | factorlibre/openerp-extra-6.1 | mgmtsystem_audit/wizard/copy_verification_lines.py | copy_verification_lines.py | py | 1,235 | python | en | code | 9 | github-code | 6 |
28839405440 | '''
Eduardi Cruz DIV B
Ejercicio 03
Es la gala final de Gran Hermano y la producción nos pide un programa para contar
los votos de los televidentes y saber cuál será el participante que ganará el juego.
Los participantes finalistas son: Nacho, Julieta y Marcos.
El televidente debe ingresar:
● Nombre del votante
● Edad ... | EduardoCruzfm/UTN | programacion_1/ejercicios_phyton/ejercicio_03.py | ejercicio_03.py | py | 6,445 | python | es | code | 0 | github-code | 6 |
32584103329 | import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
from app import app
from apps import theme_explorer as te, text
import util
"""
=====================================================... | thigbee/dashBootstrapThemeExplorer | apps/bootstrap_templates.py | bootstrap_templates.py | py | 5,729 | python | en | code | 0 | github-code | 6 |
41244848850 | '''Desenvolva um programa que leia o nome, idade, e sexo de 4 pessoas.
No final do programa mostre:
* A média de idade do grupo.
*Qual o nome do homem mais velho.
*Quantas mulheres tem menos de 21 anos '''
soma = 0
total = 0
maioridadehomem = 0
nomevelho = ''
totmulher20 = 0
for pessoa in range(1,5):
nome = ... | andrematos90/Python | CursoEmVideo/Módulo 2/Desafio 056.py | Desafio 056.py | py | 1,040 | python | pt | code | 0 | github-code | 6 |
8012099265 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("file", type=str, help="data file")
parser.add_argument("-R", "--rd", type=float, default=1e3, help="resistor on drain")
parser.add_argument("-D", "--diagnose", action="stor... | mvallina/trts | nmosfit.py | nmosfit.py | py | 3,076 | python | en | code | 1 | github-code | 6 |
35003317168 | # Домашняя работа по задаче 2.4 курса Python 3
# Задача 2.4. (Условия)
# Пункт A.
# Напишите функцию, которая удаляет все восклицательные знаки из заданной строк.
# Например,
# foo("Hi! Hello!") -> "Hi Hello"
# foo("") -> ""
# foo("Oh, no!!!") -> "Oh, no"
# def remove_exclamation_marks(s):
# pass
... | PavelVes/project_01 | HomeWorks_for_course_Python_3/HW_lvl_1/hw_task_2.4.py | hw_task_2.4.py | py | 6,215 | python | ru | code | 0 | github-code | 6 |
4406068121 | import random
import operator
class Node():
def __init__(self, val):
self.val = val
self.next = None
def make_linklist(datas):
head, tail = None, None
for d in datas:
node = Node(d)
if not head:
head = node
tail = node
else:
tai... | guzhoudiaoke/data_structure_and_algorithms | coding_interview_guide/2_link_list/16_selection_sort/selection_sort.py | selection_sort.py | py | 3,152 | python | en | code | 0 | github-code | 6 |
74190873788 | __author__ = "ALEX-CHUN-YU (P76064538@mail.ncku.edu.tw)"
from sklearn.datasets import load_wine
from sklearn.ensemble import RandomForestClassifier
from sklearn import preprocessing
from sklearn.model_selection import validation_curve
from sklearn.model_selection import GridSearchCV
from sklearn_evaluation.plot import ... | Alex-CHUN-YU/Recommender-System | scenario_algorithm_analysis/rfc.py | rfc.py | py | 9,077 | python | en | code | 0 | github-code | 6 |
28713863068 | import torch
import pandas as pd
import os
from shutil import copy
from utils import fix_randomness, save_to_df, _logger, report_results, get_nonexistant_path, copy_Files
from dataloader.dataloader import data_generator
from trainer.training_evaluation import cross_domain_test
from datetime import datetime
from iterto... | mohamedr002/SLARDA | Autorgressive_Adaptation/train_CD.py | train_CD.py | py | 6,844 | python | en | code | 23 | github-code | 6 |
39763998514 | import streamlit as st
import os
from PIL import Image
from ultralytics import YOLO
import re
# Load the model
model = YOLO("model.pt")
# Set the path for results
output_dir = 'temp_out_res'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Function to predict images
def predict_image(i... | DawidTobolski/YOLO_cell | YOLO_cell.py | YOLO_cell.py | py | 2,252 | python | en | code | 0 | github-code | 6 |
8588345616 | from collections import namedtuple
from datetime import datetime
from time import sleep
from timeit import default_timer as timer
import re
import requests
def _request_matches(r, regexp) -> bool:
"""Check if request has data and that data matches give regular expresssion
Args:
r: HTTP call result fr... | abbyssoul/site_check | site_checker/rest_source.py | rest_source.py | py | 3,130 | python | en | code | 0 | github-code | 6 |
74285386747 | import sys
sys.path.append('../python')
sys.path.append('../apps')
import needle as ndl
from d2l import torch as d2l
import torch
import torch.nn as nn
import numpy as np
class MultiHeadAttention(nn.Module):
"""多头注意力"""
def __init__(self, key_size, query_size, value_size, num_hiddens,
num_head... | Erostrate9/needle | tests/MultiHeadAttention.py | MultiHeadAttention.py | py | 7,843 | python | en | code | 2 | github-code | 6 |
26287041907 | import sys
import matplotlib.pyplot as plt
import numpy as np
import os
# this program reads input from a script which has assessed how networks react to a particular combination of gradient and division status
# the script has produced for each network a matrix with 0 (migrate) and 1 (divide), which this program will... | RenskeVroomans/regulation_evolution | scripts/plot_netanalysis_jan.py | plot_netanalysis_jan.py | py | 3,203 | python | en | code | 0 | github-code | 6 |
25225150959 | import time
import random
class NPC():
def __init__(self, trigger_item, speech = "", name = ""):
self.name = name
self.trigger_item = trigger_item
self.speech = speech
self.health = 20
def deliver_speech(self):
print("\nThe patient runs towards you intent o... | marivielle/KFC | NPC.py | NPC.py | py | 1,239 | python | en | code | 0 | github-code | 6 |
5518662883 | #!/usr/bin/python3
import sys, getopt
#Replace version number in html files
def replace_version (current_version, new_version):
#Files where version number will be replaced
files = ['index.html', 'article.html', './write/index.html']
#Goes through the array replacing the version in each file
for file_name in file... | willgcr/mblog | new_version.py | new_version.py | py | 1,521 | python | en | code | 2 | github-code | 6 |
30728277710 | import fileinput
from typing import Counter
ll = [l.strip() for l in fileinput.input()]
numbers = []
for line_nr in range(len(ll)):
l = ll[line_nr]
numbers = [int(x) for x in l.split(',')]
def count_fishes(days):
dd = Counter(numbers)
for _ in range(days):
new_fishes = dd[0]
for i in... | mdaw323/alg | adventofcode2021/6.py | 6.py | py | 498 | python | en | code | 0 | github-code | 6 |
3848748609 | from setuptools import setup, Extension
condor_module = Extension('condor',
sources=['c/condor.c', 'c/glutils.c'],
libraries=['GLEW', 'glfw'])
setup (name='Condor',
version='0.1',
description='',
ext_modules=[condor_module])
| enricozb/Condor | condor/setup.py | setup.py | py | 301 | python | en | code | 0 | github-code | 6 |
39685754485 | with open('input.txt', 'r') as f:
priorities = 0
for line in f:
l = len(line)//2
s1, s2 = line[l:-1], line[:l]
for c in s1:
if c in s2:
priorities += 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.index(c) + 1
break
print(priorities)
| SalmonA/adventofcode | 2022/03/03_1.py | 03_1.py | py | 320 | python | en | code | 0 | github-code | 6 |
19411076487 | def create_offering(newOffering):
classTimesArray = []
if newOffering.classTimes:
for classTime in newOffering.classTimes:
classTime = {
u'location': classTime.location,
u'startTime': classTime.startTime,
u'endTime': classTime.endTime,
... | timtraversy/GWU-Scrape-Python | emerson-scrape.py | emerson-scrape.py | py | 12,340 | python | en | code | 0 | github-code | 6 |
25022064101 | # http://docs.python.org/library/htmlparser.html
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("start tag: %s" % tag)
def handle_endtag(self, tag):
print("end tag: %s" % tag)
def main():
page="<a color=black>poo</a>"
pag... | ahbaid/learn | python/scae/class-08/html1.py | html1.py | py | 495 | python | en | code | 1 | github-code | 6 |
13658425408 | import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
def summarize_qc_resamples(input_df, verbose=False, **resample_kwargs):
time_list = list()
data_list = list()
for time, df in input_df.resample(**resample_kwargs):
if verbose == True:
print("Cur... | wangsen992/pyqc | src/pyqc/tools.py | tools.py | py | 855 | python | en | code | 0 | github-code | 6 |
19504742337 | from igraph import Graph
from igraph import plot
grafo = Graph(edges = [(0,1),(2,3),(0,2),(0,3)], directed = True)
grafo.vs['label'] =['Fernando', 'Pedro', 'Jose', 'Antonio']
grafo.vs['nota'] = [100, 40, 60, 20]
grafo.es['tipoAmizade'] = ['Amigo', 'Inimigo', 'Amigo']
grafo.es['devendo'] = [1,3,2,5]
grafo.vs['color'] ... | guibarreta1993Average/data_science_udemy | 05_Grafos/aula34_impressao.py | aula34_impressao.py | py | 557 | python | en | code | 0 | github-code | 6 |
31148205537 | import argparse
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
import pandas as pd
import numpy as np
import json
import os
def parse_args():
parser = argparse.ArgumentParser(prog='')
parser.add_argument('json', type=str, help='Figure1 JSON.')
parser.add_argument('-o', '--ou... | perezja/Leukos | presentation/figure6/figure6.py | figure6.py | py | 3,116 | python | en | code | 0 | github-code | 6 |
5657507234 | import os
from functools import reduce
class Photo:
id = None
layout = None # v or h
tags = []
def __init__(self, id, layout, tags):
self.id = id
self.layout = layout
# self.tagalf = "".join(sorted(tags))
self.tagalf = tuple(sorted(tags))
self.tags = tags
... | phyx4/hashcode_2019 | main.py | main.py | py | 3,664 | python | en | code | 0 | github-code | 6 |
24931817284 | from json import dumps, loads
from State import State
class Api:
"""
A class that provides methods for encoding and decoding
States to and from JSON strings.
Methods:
- Encode(states: list[State]) -> str:
Encodes a list of State objects to a JSON string.
- Decode(jsonStr... | Saeed-Ayman/8-puzzle | API.py | API.py | py | 1,287 | python | en | code | 1 | github-code | 6 |
712141287 | #! /usr/bin/env python3
# coding: utf-8
import os
import logging as lg
import pandas as pd
import numpy as np
lg.basicConfig(level=lg.DEBUG)
import os
import pandas as pd
class SetOfParliamentMembers:
def __init__(self, name):
self.name = name
def __repr__(self):
return "setOfParliament... | honorezemagho/python-oc | analysis/csv.py | csv.py | py | 1,496 | python | en | code | 0 | github-code | 6 |
7276876468 | from django.db import models
from django.contrib.auth.models import User
class Animal(models.Model):
"""Класс описывает объект Животное"""
owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Владелец")
species = models.CharField(max_length=30, verbose_name="Вид животного")
name = ... | Gamilkar/animal_medical_record | main/models.py | models.py | py | 2,320 | python | ru | code | 0 | github-code | 6 |
12510085973 | from tqdm import tqdm
import math
import time
import numpy as np
def bingliu_mpqa(utterance_tokenized, file):
feat_ = []
dict1_bing = {}
for line in file:
x = line.split("\t")
dict1_bing[x[0] + "_" + x[1][:-1]] = 1
i=0
for tokens in utterance_tokenized:
res = np.array([0,0,0,... | hamzah70/Multi_Modal_Emotion_Analysis | lexiconFeatureVector.py | lexiconFeatureVector.py | py | 4,491 | python | en | code | 0 | github-code | 6 |
38353405555 | import requests
from bs4 import BeautifulSoup #screen-scraping library
#request = requests.get("http://www.google.com")
request = requests.get("https://www.johnlewis.com/house-by-john-lewis-curve-dining-chair-white/p231441579")
content = request.content #getting content of the page
soup = BeautifulSoup(content, "html... | BrayoKane/python-mongo | price-of-a-chair/src/app.py | app.py | py | 811 | python | en | code | 0 | github-code | 6 |
74022415547 | from rest_framework import status
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from apps.celery_task.models import PeriodicTask
from apps.celery_task.serializers.periodic_task_serializer import PeriodicTaskSerializer, CreatePe... | yaowuya/django-major-core | apps/celery_task/views/periodic_task_view.py | periodic_task_view.py | py | 2,133 | python | en | code | 0 | github-code | 6 |
18959826347 | from rest_framework.decorators import api_view, permission_classes
import random
import string
from pprint import pprint as pp
import requests
from allauth.account.models import EmailAddress
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permiss... | isaacShin-dev/kickin | accounts/social_views.py | social_views.py | py | 3,846 | python | ko | code | 0 | github-code | 6 |
20093575148 | # General
import os
# Tools/utils
import itertools
import multiprocessing
from tqdm.notebook import tqdm
from tqdm import tqdm as tqdm_cli
from functools import reduce # for aggregate functions
from itertools import chain # for aggregate functions
# Data management
import math
import numpy as np
import pandas as pd... | masyahook/Single-cell-gene-regulatory-networks | scGRN/func.py | func.py | py | 43,101 | python | en | code | 0 | github-code | 6 |
28031461245 | #!/usr/bin/python3
from time import sleep
from datetime import date, datetime
from pynput.keyboard import Key, Controller
from logging.handlers import RotatingFileHandler
import sys, signal, argparse, logging, platform, subprocess
# ----------------------------------Configuration--------------------------------
VOLUM... | muteebakram/Timer | main.py | main.py | py | 5,198 | python | en | code | 0 | github-code | 6 |
22791755556 | import sys
sys.path.insert(0, '../../class')
import os
import time
import nnet
import cubelattice as cl
import multiprocessing
from functools import partial
from scipy.io import loadmat
import numpy as np
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Verification Settin... | Shaddadi/veritex | examples/Microbenchmarks/main.py | main.py | py | 1,739 | python | en | code | 10 | github-code | 6 |
24044811304 | #compare parameter between abc-smc
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sys
from scipy import stats
from matplotlib.colors import LogNorm, Normalize
from scipy.signal import argrelextrema
filename=["ACDC_X2","ACDC_Y2","ACDC_Z2"]#,"ACDC_all"]
#filename=['A... | icvara/AC-DC | compareplot.py | compareplot.py | py | 14,082 | python | en | code | 0 | github-code | 6 |
2416692184 | from pygame import *
from random import randrange
from math import *
from Pong.GameStats import GameStats
from Pong.Player.Goal import Goal
from Pong.Player.PlayerRacket import PlayerRacket
class Ball:
MAX_SPEED_Y = 12
SPEED_X = 6
COLOR = (int(255), int(255), int(255))
RADIUS: int = 10
WIN_SCORE... | dogancanalgul/Pong | ball.py | ball.py | py | 2,820 | python | en | code | 0 | github-code | 6 |
11047304211 | '''----------------------------------------------------------------------------
engine.py
----------------------------------------------------------------------------'''
from engine.ssc.image_ini import *
import numpy as np
#import sunpy.instr.aia
def standard_multitype_ini(observations):
'''Standard initial... | gyengen/SheffieldSolarCatalog | engine/initialisation.py | initialisation.py | py | 1,753 | python | en | code | 1 | github-code | 6 |
70747391228 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 28 12:54:38 2016
@author: Kylin
"""
import math
import quyu
import erfenbijin
import pylab as pl
a = 200
Rx = 10
Ry = 20
V0 = 100
theta = math.pi/5
dt = 0.1
Vx = V0*math.co... | 52kylin/compuational_physics_N2014301020034 | exercise_09_new/code/zfxvx.py | zfxvx.py | py | 1,459 | python | en | code | 0 | github-code | 6 |
27251269716 | """
文件名: Code/Chapter05/C01_ConfigManage/E02_Config.py
创建时间: 2023/2/26 3:47 下午
作 者: @空字符
公众号: @月来客栈
知 乎: @月来客栈 https://www.zhihu.com/people/the_lastest
"""
import os
class ModelConfig(object):
def __init__(self,
train_file_path=os.path.join('data', 'train.txt'),
val_file_path=os... | moon-hotel/DeepLearningWithMe | Code/Chapter05/C01_ConfigManage/E02_Config.py | E02_Config.py | py | 1,326 | python | en | code | 116 | github-code | 6 |
70402167867 | import const
import sys, os
import string
import random
QUESTION_TOOL='What are the tools used in the attack?'
QUESTION_GROUP='Who is the attack group?'
INPUT_FILE='input/sample_attack_report_raw.txt'
TRAIN_RATE=0.8
VUL_RATE=0.1
LABEL_TRAIN='train'
LABEL_VAL='dev'
LABEL_TEST='test'
SENTENSE_DELIMETER=". "
WORD_DELI... | gamzattirev/Ahogrammer | create_dataset.py | create_dataset.py | py | 7,721 | python | en | code | 0 | github-code | 6 |
44379710290 | from random import randint
y=int(randint(1,10))
for i in range(3):
x = int(input("猜数字:\n"))
if x >y:
print("大了")
elif x<y:
print("小了")
else:
print("猜对了")
break
print("Game over!") | wuge-1996/Python-Exercise | Exercise 39.py | Exercise 39.py | py | 247 | python | en | code | 0 | github-code | 6 |
17256948742 | #El bloque else justo después de for / while se ejecuta solo cuando el ciclo
#NO termina con una declaración de interrupción.
"""for i in range(1,5):
print (i)
else :
print("Sin descanso/ se ejecuta porque no hay break")"""
# Program to check if an array consists
# of even number
"""def evenumbers (lista) ... | codekacode/Exercisespython | Elsefor.py | Elsefor.py | py | 682 | python | es | code | 0 | github-code | 6 |
17509722663 | '''
Problem Statement
Your company has a big conference coming up and needs to book conference rooms in a convention center. To help the company save budget, we want to book as few conference rooms as possible given a list of meeting schedules that contains only the starting and ending time of each meeting. Write a pro... | soji-omiwade/cs | dsa/before_rubrik/minimum_rooms.py | minimum_rooms.py | py | 1,937 | python | en | code | 0 | github-code | 6 |
19040286888 | from typing import Dict, List, Optional, Tuple, Union
import numpy as np
from rl_nav import constants
from rl_nav.environments import wrapper
try:
import cv2
import matplotlib
from matplotlib import cm
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
exc... | philshams/Euclidean_Gridworld_RL | rl_nav/environments/visualisation_env.py | visualisation_env.py | py | 6,969 | python | en | code | 1 | github-code | 6 |
12423871357 | __author__ = "Vanessa Sochat, Alec Scott"
__copyright__ = "Copyright 2021-2023, Vanessa Sochat and Alec Scott"
__license__ = "Apache-2.0"
import json
import os
import re
import shlex
import subprocess
import pakages.builders.spack.cache as spack_cache
import pakages.client
import pakages.oras
import pakages.utils
fro... | syspack/pakages | pakages/builders/spack/client.py | client.py | py | 5,794 | python | en | code | 2 | github-code | 6 |
13914723162 | import sys
import oneflow as flow
import oneflow.typing as tp
import argparse
import numpy as np
import os
import shutil
import json
from typing import Tuple
from textcnn import TextCNN
sys.path.append("../..")
from text_classification.utils import pad_sequences, load_imdb_data
parser = argparse.ArgumentParser()
par... | Oneflow-Inc/oneflow_nlp_model | text_classification/textcnn/train_textcnn.py | train_textcnn.py | py | 5,411 | python | en | code | 0 | github-code | 6 |
8246901300 | """
Module containing the rheologies, fault setup, and ODE cycles code
for the 2D subduction case.
"""
# general imports
import json
import configparser
import numpy as np
import pandas as pd
from scipy.integrate import solve_ivp
from numba import njit, objmode, float64, int64, boolean
from scipy.interpolate import in... | tobiscode/seqeas-public | seqeas/subduction2d.py | subduction2d.py | py | 145,621 | python | en | code | 0 | github-code | 6 |
21721374854 | import os
import math
import json
import librosa
from settings import (
SAMPLE_RATE,
NUM_MFCC,
N_FTT,
HOP_LENGTH,
NUM_SEGMENTS,
DURATION,
)
DATASET_PATH = "data\\archive\\Data\\genres_original" # loaded using the GTZAN Music Genre Classification dataset at https://www.kaggle.com/... | jmrossi98/genre_detect | src/preprocess_data.py | preprocess_data.py | py | 2,051 | python | en | code | 0 | github-code | 6 |
42111163390 | from fastapi import Body, FastAPI
from pydantic import BaseModel
from typing import Annotated
from enum import Enum
app = FastAPI()
class ModelName(str, Enum):
afs = "afs"
har = "har1"
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
... | mkilic20/task | testing.py | testing.py | py | 1,663 | python | en | code | 0 | github-code | 6 |
2987884048 | from urllib2 import urlopen, HTTPError
from django.template.defaultfilters import slugify
from django.core.files.base import ContentFile
from django.db import transaction, IntegrityError
from item.models import Item, Link
from movie.models import Movie, Actor, Director, Genre
from decorators.retry import retry
class ... | sameenjalal/mavenize-beta | mavenize/lib/db/loadmovie.py | loadmovie.py | py | 3,712 | python | en | code | 1 | github-code | 6 |
11332000472 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 1 10:10:45 2021
@author: 82106
"""
import cv2
import os
import sys
if not os.path.exists('result'):
os.makedirs('result')
capture = cv2.VideoCapture(1)
if not capture.isOpened():
print('Camera open failed!')
sys.exit()
'''
frameWidth = int(capture.get(cv... | dongwooky/Personal-Project | container/camera_screenshot.py | camera_screenshot.py | py | 1,084 | python | en | code | 0 | github-code | 6 |
5759183851 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@AUTHOR:Joselyn Zhao
@CONTACT:zhaojing17@foxmail.com
@HOME_PAGE:joselynzhao.top
@SOFTWERE:PyCharm
@FILE:main.py
@TIME:2019/6/13 10:32
@DES:
'''
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
old_v = tf.logging.get_verbosity()
tf.logging.set_ver... | joselynzhao/DeepLearning.Advanceing | DL_6/work/main.py | main.py | py | 2,860 | python | en | code | 5 | github-code | 6 |
44602770515 | import pytesseract
import PIL
from os import system
import re
system("tesseract -l")
class workout:
reps = 0
exercise_name = ""
def compile_text_to_workouts(text):
workouts = []
num = 0
for word in text:
new_workout = workout()
if word.isdigit():
new_workout.reps ... | reeyagup/GetFit | image_to_text.py | image_to_text.py | py | 972 | python | en | code | 0 | github-code | 6 |
35299316629 | # -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
from xml.etree import ElementTree as etree
from xml.dom import minidom
import untangle
def xml_generator(input_filename, input_foldername, exif_list, root_path):
root = ET.Element('annotation')
source = ET.SubElement(root, 'source')
image_dat... | simonchanper/ml_ann | ann_tools_eric/xml_process.py | xml_process.py | py | 2,403 | python | en | code | 0 | github-code | 6 |
19699008636 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
d={}
while headA:
d[headA] = 1
headA = headA.nex... | Superhzf/python_exercise | Linked List/Intersection of Two Linked Lists/solution.py | solution.py | py | 692 | python | en | code | 1 | github-code | 6 |
19516521842 | #for X in range(1,10):
#print(X)
#for char in "cofee":
#print(char * 10)
#for num in range (0,20,2):#if you start with odd nums it will print odd(1,20,2)
#print(num)
#times = input("how many times do i have to tell you? ")
#times = int(times)
#for time in range(times) :
# print ("clean up your ro... | mevine/seen | jee.py | jee.py | py | 1,511 | python | en | code | 0 | github-code | 6 |
71504118267 | from __future__ import annotations
from io import BufferedIOBase, BytesIO
from typing import List, Optional
from helper import (
byte_to_int,
encode_varstr,
hash160,
int_to_byte,
int_to_little_endian,
little_endian_to_int,
read_varint,
sha256,
)
from op import (
decode_num,
enc... | jimmysong/minipy | script.py | script.py | py | 13,382 | python | en | code | 1 | github-code | 6 |
7626498457 |
vertices = []
arestas = []
matriz = []
class Grafo:
def __init__(self, no, noAux, prioridade):
self.no = no
self.noAux = noAux
self.prioridade = prioridade
grafo = open('arquivomatriz.txt', 'r')
for i in grafo:
linha = i.split()
arestas.append(Grafo(int(l... | gustavoadl06/Gustavo | 6.py | 6.py | py | 1,535 | python | pt | code | 0 | github-code | 6 |
36670049284 | import matplotlib.pyplot as plt
# from mpl_toolkits.axes_grid1 import ImageGrid
# import numpy as np
from os import listdir
from os import chdir
from os import path
from PIL import Image
# import matplotlib.gridspec as gridspec
import argparse
parser = argparse.ArgumentParser(description="generate plot for report")
pa... | ThijsvdBurg/Husky_scripts | data_visualization/plot scripts/plot_results.py | plot_results.py | py | 1,911 | python | en | code | 1 | github-code | 6 |
10858272527 |
# coding: utf-8
# In[1]:
from pandas import DataFrame, read_csv
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import HashingVectorizer
from skle... | TejaishwaryaGagadam/music_genre_predictor | K_Means_Clustering.py | K_Means_Clustering.py | py | 4,472 | python | en | code | 0 | github-code | 6 |
10931063926 | import unittest
import requests_mock
from alertaclient.api import Client
class PermissionTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.perm = """
{
"id": "584f38f4-b44e-4d87-9b61-c106d21bcc7a",
"permission": {
... | alerta/python-alerta-client | tests/unit/test_permissions.py | test_permissions.py | py | 1,065 | python | en | code | 27 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.