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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
37116819870 | import csv
f = open(r'G:\ResearchWork\G_extrac\jiyi-nowear.gcode','r')
lines = f.readlines()
#print(lines)
c = open('extract_infor_1.csv', 'w', newline="")
writer=csv.writer(c)
#删除单元间空格
def filterNan(item):
return item != ''
#循环处理每一行
#line为字符串
#lines为总字符串列表
#items为单行字符串列表
#item为单行字符串
#item2为重组... | Sautumn-Huang/using_Python_doing_G_code_extract | G_extrac/G_Info_Extra.py | G_Info_Extra.py | py | 1,477 | python | zh | code | 0 | github-code | 36 |
5460426589 | from functools import partial
from ._derived import Derived
from . import utilities
class Operation(Derived):
__slots__ = ('opkwargs', 'opfn')
def __init__(self,
*terms,
op = None,
**kwargs,
):
if type(op) is tuple:
sops, op = op[:-1], op[-1... | lmoresi/funcy | funcy/_operation.py | _operation.py | py | 972 | python | en | code | 0 | github-code | 36 |
42243061570 | import cant_utils as cu
import numpy as np
import matplotlib.pyplot as plt
import glob
import bead_util as bu
import tkinter
import tkinter.filedialog
import os, sys
from scipy.optimize import curve_fit
import bead_util as bu
from scipy.optimize import minimize_scalar as minimize
import pickle as pickle
import time
#... | charlesblakemore/opt_lev_analysis | scripts/general_analysis/not_yet_updated/straighten_cantilever_withpower.py | straighten_cantilever_withpower.py | py | 3,333 | python | en | code | 1 | github-code | 36 |
8616084326 | """
HomeWork 14 - task 5
Dmytro Verovkin
robot_dreams
5. (необов'язкове виконання) Створити клас Bot та TelegramBot із першого завдання за допомогою функції type
"""
def bot_init_function(self, name):
self.name = name
def bot_say_name_function(self):
print(self.name)
def bot_send_message_function(self, mes... | verovkin/robot_dreams | 18/task5.py | task5.py | py | 1,656 | python | en | code | 0 | github-code | 36 |
4724184190 | import sys
sys.path.append('/usr/local/lib/python3.7/site-packages')
import mido
import time
outport = mido.open_output('VirtualDevice Bus 1')
note_sequence = [57, 59, 60, 62, 57, 59, 55, 57]
for note in note_sequence:
time.sleep(0.25)
outport.send(mido.Message('note_on', note=note, velocity = 100))
tim... | krispenney/midi | test.py | test.py | py | 404 | python | en | code | 0 | github-code | 36 |
19643341301 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# PyArtForms - Python generative art forms paint algorithms (artificial artist)
# experimental 'smears' paint algorithms, v1.0 - core algorithm definitions
# (c)2017-2021 MoNsTeR/GDC, Noniewicz.com, Noniewicz.art.pl, Jakub Noniewicz
# #01 [...] 'cruel red smears', not on... | monstergdc/pyartforms | playgroud/smears.py | smears.py | py | 49,566 | python | en | code | 4 | github-code | 36 |
23966001733 | # coding=utf-8
import pytest
from mockito import expect, mock, verify, verifyNoUnwantedInteractions, verifyStubbedInvocationsAreUsed, when
# noinspection PyProtectedMember
from elib_run._run import _run
@pytest.mark.parametrize(
'mute',
[True, False]
)
def test_exit(mute, caplog):
caplog.set_level(10, ... | theendsofinvention/elib_run | test/test_run.py | test_run.py | py | 3,523 | python | en | code | 0 | github-code | 36 |
70533372263 |
from pickle import TRUE
from re import A
from turtle import Turtle, penup, reset, speed
carpoints = (
(4,0),
(2,2),
(1,4),
(1,8),
(0,8),
(0.10),
(1,10),
(1,18),
(0,18),
(0,20),
(1,20),
(1,24),
(2,26),
(4,28),
(7,28),
(9,26),
(10,24),
(10,20),
... | ArseniyMegrabyan/FBlockComputerProgramming | sus.py | sus.py | py | 2,423 | python | en | code | 0 | github-code | 36 |
36587263845 | # 완전제곱수
import sys
input = sys.stdin.readline
M = int(input())
N = int(input())
sqr = [i**2 for i in range(1, 101)]
ans = []
for s in sqr:
if M <= s <= N:
ans.append(s)
if len(ans) == 0:
print(-1)
else:
print(sum(ans))
print(ans[0])
| meatsby/algorithm | boj/1977.py | 1977.py | py | 272 | python | en | code | 0 | github-code | 36 |
70471621543 | # TODO : TRANSFORM INTO A CLASS AND CREATE A REPORT OF REGION TRIMMED
#~~~~~~~GLOBAL IMPORTS~~~~~~~#
# Standard library packages import
from os import remove, path
import gzip
from time import time
from sys import stdout
# Third party package import
from Bio import SeqIO
# Local library packages import
from pyDNA.U... | a-slide/pyDNA | RefMasker.py | RefMasker.py | py | 3,819 | python | en | code | 1 | github-code | 36 |
39665406570 | import gzip
import sys
from SPARQLWrapper import SPARQLWrapper, JSON
import gzip
from bs4 import BeautifulSoup
import re
import spacy
from spacy import displacy
from collections import Counter
import en_core_web_md
import difflib
import requests
import json
from elasticsearch import Elasticsearch
nlp = en_core_web_md.l... | SummerXIATIAN/wdps_asg1_group27 | code_es.py | code_es.py | py | 5,220 | python | en | code | 0 | github-code | 36 |
40943557380 | from ruamel.yaml import YAML
from datetime import datetime
from common import *
import sys
def main():
fn = 'data/races.yaml'
if len(sys.argv) > 1:
fn = sys.argv[1]
yaml = YAML(typ='safe')
with open(fn, 'r') as fi:
ydat = yaml.load(fi)
prev_date = None
for race in ydat['races... | pkdawson/workrobot | print_schedule.py | print_schedule.py | py | 717 | python | en | code | 0 | github-code | 36 |
9454038158 | # coding: utf-8
# Credits : https://gist.github.com/jason-w/4969476
from typing import List, Dict, Any
from mongoengine import (
Document,
ListField,
EmbeddedDocumentField,
DictField,
EmbeddedDocument,
FloatField,
DateTimeField,
ComplexDateTimeField,
IntField,
BooleanField,
... | nicolasjlln/lbc-challenge | app/database/utils.py | utils.py | py | 3,396 | python | en | code | 0 | github-code | 36 |
43639712257 | import os
from hashlib import md5
from bson.objectid import ObjectId
import datetime as dt
import re
def all_files(path):
files = []
with os.scandir(path) as entries:
for entry in entries:
entry_path = os.path.abspath(entry)
if entry.is_file() and os.path.splitext(entry_path)[... | blry/docker-flask-mongodb-uwsgi-nginx | parser/project/utils.py | utils.py | py | 1,316 | python | en | code | 3 | github-code | 36 |
12834483142 | import sys
import math
# 파이썬에선 해시맵을 딕셔너리라고 부릅니다.
# 해시맵생성 방법 변수이름 = {key1 : value1, key2 : value2, key3 : value3}
n = int(input())
dictionary = []
for i in range(n):
word = input()
dictionary.append(word)
letters = input()
max_score = 0
max_score_word = ""
def is_word_fessible(word, letters):
for char in ... | ohjooyeong/codingame | scrabble.py | scrabble.py | py | 1,389 | python | en | code | 0 | github-code | 36 |
1239251599 | from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse
from application.chart.models.chart import TopPosts_MH, TopPosts_WH, TopPosts_PVN, TopPosts_RW, TopPosts_BI, TopPosts_ROL, TopPosts_WE
class GetTopPosts(View):
def get(self, request):
models_map =... | jialinzou/DjangoDashboard | application/chart/views/get_top_posts.py | get_top_posts.py | py | 1,005 | python | en | code | 7 | github-code | 36 |
14838347473 | import re
import nltk
import spacy
from nltk import Tree
from nltk.corpus import brown
sentence = "A solution of piperidin-4-ol (100 mg, 0.989 mmol) and 3-((phenylsulfonyl)methylene)oxetane (prepared according to a published literature procedure: Wuitschik et al. J. Med. Chem. 53(8) 3227-3246, 2010, 416 mg, 1.977 mmo... | arrafmousa/generate_code | custom_tags.py | custom_tags.py | py | 2,826 | python | en | code | 0 | github-code | 36 |
1836493461 |
class Solution:
def __init__(self,nums):
self.nums =nums
def lomuto_partition(self,low,high):
pivot = self.nums[high]
i = (low - 1)
for j in range(low, high):
if (self.nums[j] <= pivot):
i += 1
self.nums[i],self.nums[j] = self.nu... | zideajang/python_tuts | data_struture/quick_sort.py | quick_sort.py | py | 1,775 | python | en | code | 0 | github-code | 36 |
6708836597 | import unittest
# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
class Solution:
def twoSum1(self, nums, target):
"""
Time: O(n)
Space: O(n)
"""
map = {}
for i in range(len(nums)):
compliment = target - nums[i]
... | tanveer/leetcode-python | 0001_two_sum.py | 0001_two_sum.py | py | 1,261 | python | en | code | 1 | github-code | 36 |
20139269542 | '''
o/ Iae pessoal, Tudo bem?
Espero que sim :)
Bom este é o exercício 1018 do URI, modulo iniciante
Leia um valor inteiro. A seguir, calcule o menor número de notas possíveis (cédulas) no qual o valor pode ser decomposto.
As notas consideradas são de 100, 50, 20, 10, 5, 2 e 1. A seguir mostre o valor lido e a relação... | ronaldocoding/ipc-python | desafios/iniciante/cedulas.py | cedulas.py | py | 2,903 | python | pt | code | 7 | github-code | 36 |
72774806185 | from typing import Any, Dict, List, TypedDict
import torch as th
from tango.integrations.torch import DataCollator
from tango.integrations.transformers import Tokenizer
from dreambooth.steps.transform_data import PreprocessedExample
class BatchExample(TypedDict):
input_ids: th.Tensor
pixel_values: th.Tensor... | shunk031/tango-dreambooth | dreambooth/integrations/torch/data_collator.py | data_collator.py | py | 1,556 | python | en | code | 0 | github-code | 36 |
718069407 |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.query import ModelIterable
from django.db.models.signals import post_save, post_init
import requests
import random
def sendNotification(usertoken, title, body):
userdata = {
"to": str(usertoken),
"notif... | haydencordeiro/FoodDeliveryDjango | food/models.py | models.py | py | 7,454 | python | en | code | 1 | github-code | 36 |
7350043900 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | Mirantis/mos-horizon | openstack_dashboard/test/integration_tests/tests/test_networks.py | test_networks.py | py | 7,253 | python | en | code | 7 | github-code | 36 |
21631078978 | import os
import csv
# get the current directory
dir_path = os.getcwd()
# Check if the script has been run before
if os.path.exists(os.path.join(dir_path, 'script_has_run.txt')):
print("The script has already been run.")
exit(0)
# list all files in the directory
files = [f for f in os.listdir(dir_path) if os... | MaorAviad1/auto-create-csv-from-files-dir | main.py | main.py | py | 1,935 | python | en | code | 0 | github-code | 36 |
44395709703 | import torch
import numpy as np
from book.pytorch.utils.helper import get_mnist_loader
import torch.nn.functional as F
from torch import nn
import matplotlib.pyplot as plt
class ConvDenoiser(nn.Module):
def __init__(self, encoding_dim):
super(ConvDenoiser, self).__init__()
# encoder layers
... | jk983294/morph | book/pytorch/autoencoder/cnn_denoise.py | cnn_denoise.py | py | 4,398 | python | en | code | 0 | github-code | 36 |
74470182182 | import unittest
import mock
import openstack.common.context
from openstack.common.middleware import context
class ContextMiddlewareTest(unittest.TestCase):
def test_process_request(self):
req = mock.Mock()
app = mock.Mock()
options = mock.MagicMock()
ctx = mock.sentinel.context... | emonty/openstack-common | tests/unit/middleware/test_context.py | test_context.py | py | 2,329 | python | en | code | 1 | github-code | 36 |
40851263636 | import json
def help():
helpprint = print("""
addcoins: plus Your coins.
minuscoins: minus Your coins.
help: shows this list.
coins: Shows how many coins do you have
""")
main()
def checkbalance():
with open('coins.json','r') as f:
get_balance = json.loads(f.... | hahayeslol12/CoinScript | main.py | main.py | py | 1,455 | python | en | code | 0 | github-code | 36 |
30494220256 | import pandas as pd
import numpy as np
import tensorflow as tf
import time
import os
import csv
from sklearn.preprocessing import MinMaxScaler
from keras.layers import Input
from keras.layers import Dense, LSTM, Dropout, Embedding, Input, Activation, Bidirectional, TimeDistributed, RepeatVector, Flatten
from k... | MeichenBu/2018-2019-SURF | CNN+LSTM/LSTM_old.py | LSTM_old.py | py | 7,596 | python | en | code | 0 | github-code | 36 |
30613126170 | # 이것이 코딩테스트다
# p.180
n = int(input())
nameScoreList = []
for i in range(0, n):
nameScore = input().split()
nameScoreList.append((nameScore[0], int(nameScore[1])))
nameScoreList = sorted(nameScoreList, key = lambda x: x[1])
for name in nameScoreList:
print(name[0], end = ' ')
| KodaHye/Algorithm | This is CodingTest/practice/ascScore.py | ascScore.py | py | 310 | python | en | code | 0 | github-code | 36 |
27467133509 | #verificar se tem caracteres duplicados em string
def tem_duplicado(palavra):
vistos=[]
for c in palavra:
if c in vistos:
return True
vistos.append(c)
return False
if tem_duplicado('abacaxi'):
print('tem duplicados')
else:
print("nao tem duplicados") | GiulianeEC/praticas_python | modulo02/duplicidade.py | duplicidade.py | py | 285 | python | pt | code | 0 | github-code | 36 |
16098074633 | from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager # The Webdriver
import pyautogui # To Click
import time # To wait and all
custom_site = input("Enter The Website to Download Video...") # Take the youtube video link as the input
driver = webdriver.Firefox(executa... | JhaRishikesh/Projects | YouTube Downloader.py | YouTube Downloader.py | py | 1,902 | python | en | code | 0 | github-code | 36 |
10315136743 | from __future__ import print_function
import sys
import mdtraj as md
from simtk.openmm import app
import simtk.openmm as mm
from simtk import unit
import argparse
class Tee(object):
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
def write(self, data):
... | vivek-bala/adaptive-msm-openmm | entk2/fs-peptide/simulate-fs.py | simulate-fs.py | py | 2,035 | python | en | code | 0 | github-code | 36 |
10525922454 | import copy
import torch
import torch.nn as nn
from .backbone import *
import numpy as np
import torch.nn.functional as F
import thop
def ConvBNReLU(in_chann, out_chann, ks, st, p=1):
return nn.Sequential(
nn.Conv2d(in_chann, out_chann, kernel_size=ks, stride=st, padding=p, bias=False),
nn.BatchNo... | yadongJiang/semantic-segmentation-projects | libs/cpnet/model.py | model.py | py | 7,478 | python | en | code | 5 | github-code | 36 |
29654851332 | """ A python program that scrapes news articles, classifies their sentiment, and creates a time series of sentiment over time """
import os
import openai
# Set OpenAI API key from environment
openai.api_key = os.environ.get('OPENAI_API_KEY', '')
def classify(query, search_model="ada", model="davinci"):
openai.Cla... | candiceevemiller/company-sentiment-analysis | main.py | main.py | py | 752 | python | en | code | 0 | github-code | 36 |
40272854300 |
class Board:
def __init__(self, init_data):
self.data = [[-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1]]
for i in range(0,5):
for j in range(0,5):
self.data[i][j] = int(init_data[i][(j*3):(j*3)+2].lstrip())
def __str__(self... | paulbaumgarten/advent-of-code | 2021/day04a.py | day04a.py | py | 3,017 | python | en | code | 4 | github-code | 36 |
323540718 | # -*- coding: utf-8 -*-
"""Console script for mcc."""
import os
import click
from pydub import AudioSegment
from pydub.silence import split_on_silence
@click.command()
@click.argument('sound_path')
@click.option('--mls', default=500, help='沉默的时长,毫秒')
@click.option('--st', default=-30, help='无声的界限,如果比这个数值更小则认为是无声')
@... | nanke-ym/mcc | mcc/split.py | split.py | py | 1,227 | python | en | code | 0 | github-code | 36 |
7762827089 | # =============================================================================
# Smallest multiple
# Problem 5
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?... | piotrpatrzylas/projecteuler.net | Problem 5 python.py | Problem 5 python.py | py | 743 | python | en | code | 0 | github-code | 36 |
41961905364 | # importing module
import re
# taking input from user
n = int(input())
# iterating through the credit cards
for t in range(n):
#taking the credit card number from user
credit = input().strip()
credit_removed_hiphen = credit.replace('-','')
# valid is true in the beggining
v... | achyuth9490/Python | credit_card.py | credit_card.py | py | 876 | python | en | code | 0 | github-code | 36 |
29026071968 | #!/usr/bin/env python3
animals = ['cat', 'dog']
while (len(animals)) != 0:
print(animals[(len(animals)) - 1])
animals.pop()
else:
print('End of the stock')
for animal in animals:
print(animal)
else:
print('Results end here') | Himesh-Codes/Python | Base/loop.py | loop.py | py | 249 | python | en | code | 0 | github-code | 36 |
69982633063 | import torch
import torch.nn as nn
from torch.nn import functional as F
import math
from typing import Tuple
device = "cuda" if torch.cuda.is_available() else "cpu"
class Embedding(nn.Module):
def __init__(self,
config,
vocab_size):
"""
Embedding generates le... | SkAndMl/MusGPT | model.py | model.py | py | 6,552 | python | en | code | 3 | github-code | 36 |
43304002854 | import sys, os
import os.path
import shutil
from rpython.translator.translator import TranslationContext
from rpython.translator.tool.taskengine import SimpleTaskEngine
from rpython.translator.goal import query
from rpython.translator.goal.timing import Timer
from rpython.annotator.listdef import s_list_of_strings
fro... | mozillazg/pypy | rpython/translator/driver.py | driver.py | py | 24,503 | python | en | code | 430 | github-code | 36 |
152948829 | import PyQt6
import pandas as pd
from PyQt6 import QtWidgets, QtGui, QtCore
from PyQt6.QtCore import pyqtSignal, pyqtSlot, Qt
from PyQt6.QtWidgets import QListWidget, QFileDialog
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg
from matplotlib.figure import Figure
from gui.HyperParamterWidget import Hy... | Falrach94/deeplearning_ex4 | gui/MainWindow.py | MainWindow.py | py | 26,881 | python | en | code | 0 | github-code | 36 |
43678975341 | # importing the requests library
import requests
import time
# defining the api-endpoint
URL = "http://127.0.0.1:5000/add"
# data to be sent to api
PARAMS = {
'TimeStamp':time.time(),
'Temp1':'24.00',
'Temp2':'24.00',
'TAmbiant':'23.00',
'Humidity':'35'}
# sending ... | mh49/HSTM | test_tools/post.py | post.py | py | 548 | python | en | code | 0 | github-code | 36 |
9417381460 | """Lab_3.finite_automaton"""
import random
class State:
"""Determination of possible states of the finite automaton"""
SLEEP = "Sleep"
EAT = "Eat"
WORK = "Work"
RELAX = "Relax"
PLAY = "Play"
class FiniteStateMachine:
"""A class that implements a finite automaton"""
def __i... | vbronetskyi/Lab_3.disctret.2023 | finite_automaton.py | finite_automaton.py | py | 2,751 | python | en | code | 0 | github-code | 36 |
22777212657 | #!/usr/bin/python
import threading
import Queue
import socket
import time
import struct
import subprocess
class ROAjobMaster(threading.Thread):
def __init__(self, dataQueue, timerQueue, loggerQueue, statEvent, stopEvent):
super(ROAjobMaster, self).__init__()
self.dataQueue = dataQueue
self.timerQueue = timerQ... | lpelletier/PY_OMTESTSUITE | OMTEST_ROA.py | OMTEST_ROA.py | py | 8,278 | python | en | code | 0 | github-code | 36 |
21749724281 | import unittest
from BaseClasses import MultiWorld
from worlds.AutoWorld import AutoWorldRegister
class TestBase(unittest.TestCase):
world: MultiWorld
_state_cache = {}
def testUniqueItems(self):
known_item_ids = set()
for gamename, world_type in AutoWorldRegister.world_types.items():
... | adampziegler/Archipelago | test/general/TestUniqueness.py | TestUniqueness.py | py | 878 | python | en | code | null | github-code | 36 |
70197138344 | def word_wrap3(adres):
with open(adres) as f:
icerik = f.readlines()
icerik = [elem.replace('\n', '') for elem in icerik]
count = 0
for i in range(0, len(icerik)):
if len(icerik[i]) <= 60:
print(icerik[i], end="")
else:
texts... | Bygokcen/codestepbystep_works | main.py | main.py | py | 725 | python | en | code | 0 | github-code | 36 |
40761385267 | import os
import sys
FILE_DIR = os.path.dirname(os.path.abspath(__file__))
# PROJ_DIR = FILE_DIR[:FILE_DIR.index('src')]
# sys.path.append(PROJ_DIR)
PROJ_DIR = os.path.abspath("..")
print(f"proj_dir is: {PROJ_DIR}, adding to sys.path")
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.fu... | Qing25/demo | conditional_generation/frame.py | frame.py | py | 9,872 | python | en | code | 8 | github-code | 36 |
26932945307 | from EelemFringe import ElemFringe
from Fringe import Fringe
from Node import Node
from State import State
import labyrinth
def treeSearch():
# initialization objects
fringe = Fringe()
state = State()
node = Node(state, None, labyrinth.h[state.position])
elemFringe = ElemFringe(node)... | aledigirm3/AI | ricercaEuristica/Astar/treeSearchLabirinto/main.py | main.py | py | 876 | python | en | code | 0 | github-code | 36 |
15826790722 | # Standard imports
import copy
import pandas as pd
import logging
import jsonpickle as jpickle
import sklearn.cluster as sc
# Our imports
import emission.storage.timeseries.abstract_timeseries as esta
import emission.analysis.modelling.tour_model.get_scores as gs
import emission.analysis.modelling.tour_model.get_user... | e-mission/e-mission-server | emission/analysis/modelling/tour_model/build_save_model.py | build_save_model.py | py | 7,787 | python | en | code | 22 | github-code | 36 |
4833398186 | import re
import json
import numbers
import numpy as np
class Composition():
__atom_mass = {
# From NIST, "https://physics.nist.gov/cgi-bin/Compositions/stand_alone.pl?ele=&all=all&isotype=some"
'neutron': 1.00866491595,
'proton': 1.007276466621,
'electron': 0.000548579909065,
... | AmadeusloveIris/GraphNovo | genova/utils/BasicClass.py | BasicClass.py | py | 10,351 | python | en | code | 6 | github-code | 36 |
72053024743 | import numpy as np
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
from mars import Mars
emissivity_dessert = 0.5
emissivity_PV = 0.5
absorptivity_dessert = 0.5
absorptivity_PV = 0.5
delta_time = 24 * 60 * 60
f = 0.15
cp = 1
T_Atmosphere = 200
rho = 1
num_days = 700
# formula not given. Just a plac... | muedavid/Mars | main.py | main.py | py | 1,207 | python | en | code | 0 | github-code | 36 |
3680795220 | import numpy as np
import cv2
import math
import subprocess
import shutil
import os
if not os.path.exists('/home/martin/fotos'):
os.makedirs('/home/martin/fotos')
image_sudoku_original = cv2.imread('/home/martin/sudoku/sudoku_recognition/testing3.jpeg')
cv2.imshow("Imagen original",image_sudoku_original)
cv2.wai... | msampietro/sudoku_recognition | sudoku.py | sudoku.py | py | 6,869 | python | en | code | 0 | github-code | 36 |
19826403866 | """
--- Day 20: Grove Positioning System ---
https://adventofcode.com/2022/day/20
"""
from aoc import *
def solve(rep, multiplier):
vals = [(n, v*multiplier) for n, v in enumerate(ints(puzzle_input(20, 2022, sample=False), '\n'))]
vals_copy = vals.copy()
for _ in range(rep):
for n, v in vals_copy... | BricksAndPieces/AdventOfCode | 2022/days/day20.py | day20.py | py | 647 | python | en | code | 1 | github-code | 36 |
37779455706 | import json
from datetime import datetime as dt
from datetime import date as dto
import copy
class ProcessJsonPortfolio:
def calculate_average_price(self, _dict):
"""Calculate dollar cost average per security.
Args:
_dict (:obj:`dict`): Portfolio loaded from json.
Re... | lzy7071/portfolio_tools | portfolio_tools/util/process_json_portfolio.py | process_json_portfolio.py | py | 1,929 | python | en | code | 0 | github-code | 36 |
15207404869 | # 最短距离算法
import networkx as nx
debug = False
start_node = ('start', -1) # 初始节点
end_node = ('end', -1) # 终止节点
def fmt_edges(points, max_score=1.):
"""将节点得分列表格式化成距离矩阵
:param points list[[left, right, score]]
:return edges [(node_id1, node_id2, score)]
:return nodes [(left, right)]
"""
... | ibbd-dev/python-ibbd-algo | ibbd_algo/shortest_distance.py | shortest_distance.py | py | 2,510 | python | en | code | 1 | github-code | 36 |
13279982119 | # -*- coding: utf-8 -*-
# Scrapy settings for news project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/d... | xiaojie0202/web_spider | news(Script-redis应用)/settings.py | settings.py | py | 5,093 | python | en | code | 4 | github-code | 36 |
31279947642 | from ray import serve
from typing import List, Dict
import json
import numpy as np
from scipy.optimize import linprog
@serve.deployment(num_replicas=1, ray_actor_options={"num_cpus": 1, "num_gpus": 0})
class LinearProgrammingService(object):
# def __init__(self):
def LinearProgramming(self, body: Dict):
... | tju-hwh/Yet-Another-Serverless-Benchmark | solver/ray_stateful/so/service/linear_programming.py | linear_programming.py | py | 1,180 | python | en | code | 0 | github-code | 36 |
7615563038 | # -*- coding: utf-8 --
import re
import math
from multiprocessing import cpu_count, freeze_support
from multiprocessing.pool import Pool
import sys
from util import read_text_lines
from util import refine_line
from char2vec import load_model
B = 1
I = 0
'''
1. word2vec 모델 불러오기(from char2vec)
'''
def is_hangul(ch... | kimwansu/autospacing_tf | make_data.py | make_data.py | py | 9,337 | python | en | code | 0 | github-code | 36 |
18200360642 | import json
import os
import random
import shutil
from predictor import get_predictor
from yolox.tracking_utils.timer import Timer
import cv2
import numpy as np
def get_gt_by_frame(bbox_file: str):
gtByFrames = {}
# convert to List[bboxes, List[int]]
with open(bbox_file) as f:
annot = json.load(f)
... | chenzhutian/nba-Player-classifier | generate_samples.py | generate_samples.py | py | 4,488 | python | en | code | 0 | github-code | 36 |
19022803935 | from aiogram.types import (
InlineKeyboardMarkup,
InlineKeyboardButton,
ReplyKeyboardMarkup,
KeyboardButton,
)
from main import admins_id
from utils.db_api.schemas.table_db import session, Contest
kb = ReplyKeyboardMarkup(resize_keyboard=True)
kb.add(KeyboardButton("Добавить конкурс")).add(... | A-Sergey/TelegramBot_Contest | keyboards/buttons.py | buttons.py | py | 1,574 | python | en | code | 0 | github-code | 36 |
10018384107 | from list import student
import pickle
f=open("satya.db","wb")
rows=int(input("enter rows how many rows you want : "))
for i in range(rows):
print("----------------------------------")
print("enter "+str(i+1)+"student details")
print("-----------------------------------")
id=int(input("enter student num... | prasadnaidu1/django | Adv python practice/demo.py | demo.py | py | 571 | python | en | code | 0 | github-code | 36 |
30039556459 | import math
import numpy as np
from sympy import*
import matplotlib.pyplot as plt
class Solver:
def __init__(self, f, t0, y0, h, nsteps, inital_points):
self.f = f
self.t0 = t0
self.y0 = y0
self.h = h
self.nsteps = nsteps
self.inital_points = inital_points;
self.coef_ab = [
[1],
[1],
[3.0/2.0, ... | vserraa/Numerical-Methods | solver.py | solver.py | py | 9,570 | python | en | code | 0 | github-code | 36 |
16835981819 | import pytest
from backend.utils.assertions import assert_equals, assert_true
from backend.utils.helper import Helper
from front.data_for_tests.calender_data_for_tests import DataForTests
from front.pages.page import CalendarPage, CalendarConfiguration
@pytest.mark.usefixtures("setup", "test_config")
class TestCalen... | RivkaTestGit/MoonActive | front/tests/test_calender.py | test_calender.py | py | 3,347 | python | en | code | 0 | github-code | 36 |
74834157225 | import numpy as np
import random
import copy
# utils
from extra.utils import trans_vector, get_cards_small_extend, calculate_score
class RunfastGameEnv():
def __init__(self, cards=[], position=0, next_player=0, pattern=0):
self.position = position
self.next_player = next_player
... | zawnpn/RL_RunFast | GameEnv/RunFastGame.py | RunFastGame.py | py | 28,130 | python | en | code | 6 | github-code | 36 |
41240226723 | # Importar Librerias
import pandas as pd
import json
# Opening JSON file
f = open('orderbooks_05jul21.json')
print(f)
# Returns JSON object as a dictionary
orderbooks_data = json.load(f)
ob_data = orderbooks_data['bitfinex']
# Drop Keys with none values
ob_data = {i_key: i_value for i_key,i_value in ob... | if722399/Laboratorio-1-MySt- | dataa.py | dataa.py | py | 578 | python | en | code | 0 | github-code | 36 |
43375661698 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the fibonacciModified function below.
def fibonacciModified(t1, t2, n):
seq=[t1,t2]
if n<=2:
print(seq[n-1])
else:
for i in range(n-2):
seq.append(seq[-2]+seq[-1]**2)
return seq[-1]
r... | emfreak/Competitive-Programming | Hackerrank/Algorithms/Dynamic Programming/fibonacci_modified.py | fibonacci_modified.py | py | 598 | python | en | code | 0 | github-code | 36 |
496184917 | # -*- coding: utf-8 -*-
import time
import click
from click.testing import CliRunner
from dagster_aws.cli.term import Spinner, Term
def test_term():
def term_helper(term_cmd, prefix, exit_code=0):
@click.command()
def fn():
term_cmd('foo bar')
runner = CliRunner()
res... | helloworld/continuous-dagster | deploy/dagster_modules/libraries/dagster-aws/dagster_aws_tests/cli_tests/test_term.py | test_term.py | py | 1,054 | python | en | code | 2 | github-code | 36 |
35147097028 | import nltk
from functools import lru_cache
from nltk.corpus import stopwords
from nltk.stem.snowball import EnglishStemmer
import re
from bs4 import BeautifulSoup
class Preprocessor:
def __init__(self):
# Stemming is the most time-consuming part of the indexing process, we attach a lru_cache to the stemm... | sidsachan/movie_sentiment | preprocessor.py | preprocessor.py | py | 1,221 | python | en | code | 0 | github-code | 36 |
32782552053 | import logging
import cabby
from events.stix import parse_stix_package, STIXPackage
def collect_indicator_packages(configuration: dict) -> STIXPackage:
for repository in configuration['repositories']:
yield from poll_repository(repository)
def poll_repository(repository: dict) -> list:
logging.deb... | noxdafox/iocep | events/taxii.py | taxii.py | py | 1,252 | python | en | code | 0 | github-code | 36 |
17305255074 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 7 17:46:55 2021
@author: Administrator
"""
import SimpleITK as sitk
import numpy as np
import os
import cv2
from shutil import copyfile
import random
num=379
lists=['train_002_0000.nii.gz','train_019_0000.nii.gz','train_069_0000.nii.gz','train_101_0000.nii.gz','train_11... | xyndameinv/FLARE21 | process0.py | process0.py | py | 1,837 | python | en | code | 2 | github-code | 36 |
39723292841 | #Find list of all sub_breed breed name
import requests
def get_json_dog_output_dict(url):
r = requests.get(url)
output = r.json()
return output
def get_breed_sub_breed_full_name():
dog_output = get_json_dog_output_dict(url = "https://dog.ceo/api/breeds/list/all")
dog_breed_output = dog_output["mes... | Swetha-Vootkuri/PythonSessions | dogs_api/breed_sub_breed_list.py | breed_sub_breed_list.py | py | 859 | python | en | code | 0 | github-code | 36 |
72312960103 | from typing import Dict, List, Optional, Tuple
import numpy as np
import torch
from torch import Tensor
import torch.nn as nn
import torch.nn.functional as F
from mmcv.utils import ConfigDict
from mmdet.core import bbox2roi
from mmdet.models.builder import HEADS
from mmfewshot.detection.models.roi_heads.meta_rcnn_roi_... | csuhan/VFA | vfa/vfa_roi_head.py | vfa_roi_head.py | py | 12,474 | python | en | code | 56 | github-code | 36 |
35478284383 | import os
import glob
import h5py
import json
import copy
import torch
import librosa
import numpy as np
import soundfile as sf
import speech_recognition as sr
from jiwer import wer
from tqdm import tqdm
from scipy import signal
from trainer import Trainer
from hps.hps import hp, Hps
from torch.autograd import Variable... | andi611/ZeroSpeech-TTS-without-T | convert.py | convert.py | py | 14,769 | python | en | code | 109 | github-code | 36 |
22565647008 | import numpy as np
import torch as th
from .gaussian_diffusion import GaussianDiffusion, mean_flat
class KarrasDenoiser:
def __init__(self, sigma_data: float = 0.5):
self.sigma_data = sigma_data
def get_snr(self, sigmas):
return sigmas**-2
def get_sigmas(self, sigmas):
return si... | openai/shap-e | shap_e/diffusion/k_diffusion.py | k_diffusion.py | py | 9,973 | python | en | code | 10,619 | github-code | 36 |
23642938118 | from flask import Flask,render_template,request,redirect,session,flash
app = Flask(__name__)
app.secret_key = 'Farn'
@app.route ('/')
def index():
return render_template('index.html')
@app.route ('/result', methods=['POST'])
def result():
if len(request.form['name']) < 1:
flash("Name cannot be em... | bmcconchie/DojoAssignments | Python/Flask/python_stack/flask_fundamentals/dataform/server.py | server.py | py | 946 | python | en | code | 0 | github-code | 36 |
31734592611 | from modules import aws_sript, firestorage_code
import os
from flask import Flask, jsonify
from flask import render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
import os, shutil
from flask_cors import CORS
from decorater_file import crossdomain
global app
app = Flask(__name__)
CORS... | akhlaq1/flask-aws-face-detect-api | app.py | app.py | py | 2,784 | python | en | code | 0 | github-code | 36 |
2312965094 | import unittest
from adt_extension import SwitchDict
class SwitchDictTest(unittest.TestCase):
def setUp(self):
"""New object for all tests."""
self.switch_dict = SwitchDict({
'test1': 1,
'test2': 2,
'test3': 3,
})
def test_overload_getitem(self):
... | alvarofpp/python-adt-extension | tests/test_switchdict.py | test_switchdict.py | py | 926 | python | en | code | 4 | github-code | 36 |
18045830902 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def get_reward_curve(agents):
"""
Extract rewards from list of agents used in training
:param agents: list of agents used in training
:return: array of rewards
"""
return np.array([agent.reward_total for agent in agents])
... | hmdmia/HighSpeedRL | backend/utils/analysis.py | analysis.py | py | 7,951 | python | en | code | 0 | github-code | 36 |
3302452099 | import telebot
import requests
import re
import os
from twilio.rest import Client
import pyrebase
bot = telebot.TeleBot("Replace this with telegram bot father key", parse_mode=None)
config = {
"apiKey": "",
"authDomain": "",
"databaseURL": "",
"storageBucket": ""
}
x = 0
y = 0
z = 0
q = 0
firebase = pyrebase.in... | harishsg99/Telegram-to-WA-bot | app.py | app.py | py | 2,041 | python | en | code | 0 | github-code | 36 |
14298749677 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/12/23 19:30
# @Author : lingxiangxiang
# @File : demonWrite.py
if __name__ == '__main__':
filename = input("Please input the name of file: ")
f = open(filename, "w", encoding="utf-8")
while 1:
context = input("please input context(... | ajing2/python3 | Basics/fileOption/demonWrite.py | demonWrite.py | py | 715 | python | en | code | 2 | github-code | 36 |
27045322842 | # File: RookBishopQueen.py
# By: Christopher Luey
# Date: 2/10/20
# Rook, Bishop, Queen classes
from Piece import *
class Rook(Piece):
def __init__(self, coord, board, color, img):
# Call superclass constructor
super().__init__(coord, board, color, img)
def getPossibleMovesNoCheck(self):
... | clin155/chess-game | RookBishopQueen.py | RookBishopQueen.py | py | 3,106 | python | en | code | 0 | github-code | 36 |
20019809326 | #file used to take screenshot to baseline rectangle mappings off of
import cv2
cam = cv2.VideoCapture(0)
result, image = cam.read()
if result:
cv2.imshow("img_to_map", image)
cv2.imwrite("img_to_map.png", image)
cv2.waitKey(0)
cv2.destroyWindow("img_to_map")
else:
print("No image det... | thqtcher/physical-computing-final | app/config/python/screenshotter.py | screenshotter.py | py | 346 | python | en | code | 0 | github-code | 36 |
22700582787 | import pathlib
import json
import numpy as np
import pandas as pd
from scipy.interpolate import SmoothBivariateSpline, UnivariateSpline
import matplotlib as mpl
import matplotlib.pyplot as plt
from .common import Timer, Tools
from .sim_ctr import RgbGrid
from .sim_reduce import Steps, ReduceModel
clas... | kailicao/mesa_apokasc | sim_synth.py | sim_synth.py | py | 8,766 | python | en | code | 0 | github-code | 36 |
30280408206 | import os
def delete_empty_folders(path):
if os.path.exists(path):
for root_folder, folders, files in os.walk(path):
for folder in folders:
if len(os.listdir(os.path.join(root_folder, folder))) == 0:
os.rmdir(os.path.join(root_folder, folder))
print("... | hafeezulkareem/python_scripts | delete_empty_folders.py | delete_empty_folders.py | py | 496 | python | en | code | 0 | github-code | 36 |
29729372400 | import random
BS_feedback = dict[int, set['User']]
Group = dict[int, set['User']]
ChannelSet = set[int]
BS_response = list[int]
def rand_gen(probability):
gen = random.random()
return gen <= probability
def calculate_average_delay(users):
overall_delay = 0
for subscriber in users:
... | krezefal/preamble-slotted-aloha-simulation | utils.py | utils.py | py | 402 | python | en | code | 2 | github-code | 36 |
71075249065 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
point = head
res = []
... | nango94213/Leetcode-solution | 1721-swapping-nodes-in-a-linked-list/1721-swapping-nodes-in-a-linked-list.py | 1721-swapping-nodes-in-a-linked-list.py | py | 767 | python | en | code | 2 | github-code | 36 |
9659107550 | #!/usr/bin/env python
# coding: utf-8
# @Author: lapis-hong
# @Date : 2018/4/12
"""Prob 167. Two Sum II - Input array is sorted
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
Description:
Given an array of integers that is already sorted in ascending order, find two numbers such that... | Lapis-Hong/Leetcode | python/easy/167.Two-Sum-II.py | 167.Two-Sum-II.py | py | 1,795 | python | en | code | 8 | github-code | 36 |
25600927243 | from odoo import models, fields, api
class PurchaseOrderInh(models.Model):
_inherit = 'purchase.order'
perc_discount = fields.Float('Discount', compute='_compute_discount')
net_total = fields.Float('Net Total', compute='_compute_net_total')
perc = fields.Float(compute='compute_percentage')
... | Gidwani/CRA | so_po_customization/models/purchase.py | purchase.py | py | 6,995 | python | en | code | 0 | github-code | 36 |
10556749786 | import serial
import tkinter
from tkinter import*
TTY_DEVICE = "COM"
s=serial.Serial()
def init(port,text2):
global s
try:
s=serial.Serial(TTY_DEVICE + str(port), 115200, timeout=10)
print('connect com'+str(port))
text2.configure(state=tkinter.NORMAL)
text2.insert(1.0,'connect... | Zealua/PythonFirstTest | GUI/GUI_VGH/driver/comPort.py | comPort.py | py | 1,363 | python | en | code | 0 | github-code | 36 |
31050662738 | import re
import unicodedata
def slugify(value):
""" From django.utils.text """
value = unicodedata.normalize('NFKD', value).encode(
'ascii', 'ignore').decode('ascii')
value = re.sub('[^\w\s-]', '', value).strip().lower()
return re.sub('[-\s]+', '-', value)
| ryankask/esther | esther/utils.py | utils.py | py | 284 | python | fa | code | 17 | github-code | 36 |
3482612068 | class IterInt(int):
def __iter__(self):
for i in str(self):
yield int(i)
def __getitem__(self, index):
res = str(self)[index]
return int(res)
def __len__(self):
count = 0
for i in self:
count += 1
return count
# return len(str... | aanastasiyatuz/python23-lections | oop/iter_int.py | iter_int.py | py | 599 | python | en | code | 5 | github-code | 36 |
198794662 | import abc
from typing import Dict, List
from uuid import UUID
from moderation_ml_example.models import Post
class PostNotFoundError(Exception):
pass
class PostRepository:
__metaclass__ = abc.ABCMeta
async def save(self, post: Post) -> None:
...
async def get(self, id: UUID) -> Post:
... | mikeyjkmo/post-moderation-example | moderation_ml_example/repository.py | repository.py | py | 1,156 | python | en | code | 0 | github-code | 36 |
8373131694 |
import jwt
JWT_SECRET = "this_is_just_for_testing"
def create_jwt(payload):
token = jwt.encode(
payload,
JWT_SECRET,
algorithm="HS256"
)
return token
def validate_jwt(token):
try:
payload = jwt.decode(token, JWT_SECRET, "HS256")
except:
raise
re... | walterbrunetti/playground | auth/core/jwt_utils.py | jwt_utils.py | py | 338 | python | en | code | 0 | github-code | 36 |
70857518504 | import copy
with open('input.txt', 'r') as file:
input = [[line.strip(), False] for line in file if line.strip()]
# build up list of instructions
programs_to_try = []
jmp_instruction_indices = [idx for idx, (operation, _) in enumerate(input) if 'jmp' in operation]
nop_instruction_indices = [idx for idx, (operatio... | davsucks/AdventOfCode | 2020/8/part-two.py | part-two.py | py | 1,666 | python | en | code | 0 | github-code | 36 |
1060549613 | import unittest
from paint_calculator import api
from paint_calculator.run import app
class APITestCase(unittest.TestCase):
def setUp(self):
app.testing = True
self.app = app.test_client()
def test_calculate(self):
"""
Tests calculate function
"""
room1 = {'leng... | robinf1/paint-calculator | test/test_api.py | test_api.py | py | 3,197 | python | en | code | 0 | github-code | 36 |
30954831491 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 19 04:39:33 2018
@author: hyeongyuy
"""
import numpy as np
class visGraph(object):
def __init__(self):
#node num
self.NODE_NUM = 0
#leaf node info in tree graph
self.LEAF_BASE = \
'[label=\"predict = {}\\nhomogeneity = {}\... | hyeongyuy/DecisionTree_python | modules/visgraph.py | visgraph.py | py | 3,298 | python | en | code | 1 | github-code | 36 |
5155695157 | from uagents.setup import fund_agent_if_low
from uagents import Agent, Context, Model
class Message(Model):
message: str
RECIPIENT_ADDRESS = "agent1q0lqc50tgunfr8zumuj8744fqd9wl8hmh3akq0ygyzud9cp5yju524d7gcw"
agent = Agent(
name="alice",
port=8000,
seed="agent1 recovery seed phrase",
endpoint={... | cmaliwal/uAgents | examples/08-remote-agents-registration/agent1.py | agent1.py | py | 775 | python | en | code | null | github-code | 36 |
6031572605 | #this will be the personality quiz part of my program
from tkinter import*
from tkinter import messagebox as mb
window = Tk()
window.title("Giftlab")
window.geometry("500x500")
window.rowconfigure(0, weight = 1)
window.columnconfigure(0,weight = 1)
#creating different frames
picker = Frame(window) #this wil... | naviniii/giftlab | secondcomponent_v1.py | secondcomponent_v1.py | py | 1,614 | python | en | code | 0 | github-code | 36 |
35280214366 | # 숫자와 문자열의 다양한 기능
#
# 문자열 format() 함수
# - 문자열을 가지고 있는 함수
# - "{}".format(10) 형식이며
# - 중괄호의 개수와 괄호안의 매개변수의 개수가 반드시 같아야한다
String_a = "{}".format(10)
String_b = "{} {}".format(10, 20)
String_c = "{} {} {}".format(10, 20, 30)
print(String_a) # 10
print(String_b) # 10 20
print(String_c) # 10 20 30
print("---------... | juneglee/Deep_Learning | python-basic/chapter02/ex04_1.py | ex04_1.py | py | 1,803 | python | ko | code | 0 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.