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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
20119427464 | import csv
# Load files
file_load = "/Users/petr/Desktop/Data_School/python/python-challenge/PyPoll/Resources/03-Python_HW_Instructions_PyPoll_Resources_election_data.csv"
poll_analysis = "/Users/petr/Desktop/Data_School/python/python-challenge/PyPoll/Analysis/poll_analysis.txt"
# Set variables
votes = 0
winner_votes... | nguyenpe17/python-challenge | PyPoll/Analysis/main2.py | main2.py | py | 1,729 | python | en | code | 0 | github-code | 1 |
35572635490 | import os
import csv
from innostock import settings
from stockkdata.models import ListOfCompanies
from django.core.management.base import BaseCommand,CommandError
DIR_PATH=os.path.dirname(__file__)
class Command(BaseCommand):
help='Add company data'
def handle(self, *args, **options):
with open(str(D... | devanshslnk/StockHub | innostock/stockkdata/management/commands/list_of_company.py | list_of_company.py | py | 875 | python | en | code | 1 | github-code | 1 |
19322826912 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the arrayManipulation function below.
def arrayManipulation(n, queries):
arr = [0]*(n+1)
for q in queries:
arr[q[0]-1] += q[2]
arr[q[1]] -= q[2]
answer = 0
cumulative_sum = 0
for value in arr:
... | hanameee/Algorithm | HackerRank/interviewPreparation/Arrays/Array_Manipulation.py | Array_Manipulation.py | py | 612 | python | en | code | 2 | github-code | 1 |
22474452602 | class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) == 0 or nums[0] > target or nums[-1] < target: return [-1, -1]
local_min, local_max = 0, len(nums)
idx = (local_... | Brady31027/leetcode | 34.py | 34.py | py | 1,110 | python | en | code | 1 | github-code | 1 |
28097598839 | from schema import And, Optional, Or, Schema
_DATA_TYPES = Or(
"binary",
"text",
"number",
"date",
"image",
"audio",
"video",
"list",
"single_selection",
"multiple_selection",
"form_sequence",
"email",
"link",
"pdf",
"embed",
"named_entity_recognition",
... | Human-Lambdas/human-lambdas | src/human_lambdas/data_handler/data_schema.py | data_schema.py | py | 1,527 | python | en | code | 32 | github-code | 1 |
11350573536 | Import('BuildEnv')
import os
import sys
env = BuildEnv.Clone()
env.Append(CPPPATH = [env['TOP'],
env['TOP'] + '/base',
env['TOP'] + '/io',
env['TOP'] + '/bfd',
])
env.Append(LIBPATH = ['#/' + Dir('..').path,
'... | Juniper/contrail-dev-controller | src/bfd/test/SConscript | SConscript | 2,339 | python | en | code | 3 | github-code | 1 | |
70839143073 | import sys
sys.setrecursionlimit(10**9)
N = int(input())
arr = [[] * (N+1) for _ in range(N+1)]
for i in range(N-1):
a, b = map(int, input().split())
arr[a].append(b)
arr[b].append(a)
# print(arr)
visited = [0] * (N+1)
ans = [0] * (N+1)
def dfs(x):
visited[x] = 1
# print(x)
if 0 not in visi... | ckdfh0917/Algorithm | 기웅스터디/트리/11725. 트리의 부모 찾기.py | 11725. 트리의 부모 찾기.py | py | 555 | python | en | code | 0 | github-code | 1 |
74636596833 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: Wenxuan Wu, Zhongang Qi, Li Fuxin.
@Contact: wuwen@oregonstate.edu
@File: eval_cls_conv.py
Modified by
@Author: Jiawei Chen, Linlin Li
@Contact: jc762@duke.edu
@File: k_eval_cls_conv.py
"""
import argparse
import os
import sys
import numpy as np
import pand... | ECE685-FinalProject/3D-object-recognition | k_eval_cls_conv.py | k_eval_cls_conv.py | py | 7,925 | python | en | code | 1 | github-code | 1 |
21614577965 | from os import system
import os
datosEstudiante = [[],[],[],[]]
datosDocente = [[],[],[]]
calificacionEstudiante = []
totalIndividual = []
numerocalificaciones = 0
numeroEstudiantes = 0
busquedalineal = 0
busquedabinaria = 0
busquedaInterpolacion = 0
def burbuja(arreglo):
for fila in arreglo:
n = len(fila)
... | jsaul22/calificacionesProyecto | main.py | main.py | py | 21,947 | python | es | code | 0 | github-code | 1 |
34597254850 | import numpy as np
import matplotlib.pyplot as plt
import scipy.spatial as spa
from scipy.stats import multivariate_normal
def main():
# TODO I have tested my algorithm on two different computers,
# TODO Algorithm's average run time: M1 Chip MBP -> 3 min. Intel Chip MBP -> 9 min.
# TODO Please do not term... | kaanturkmen/ENGR421-Machine-Learning | Homeworks/HW8-EM-Maximization-Clustering/engr421_hw08.py | engr421_hw08.py | py | 12,566 | python | en | code | 1 | github-code | 1 |
1377568002 | from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
a = []
deepestRow = 0
def deepestLeavesSum(self, root: TreeNode) -> int:
self.scanTree(root, 0)
s... | xulu199705/LeetCode | leetcode_1302.py | leetcode_1302.py | py | 725 | python | en | code | 0 | github-code | 1 |
22122963677 | import unittest
from typing import List
import heapq
import collections
class Solution:
def minCostToSupplyWater(self, n: int, wells: List[int], pipes: List[List[int]]) -> int:
'''
首先利用最小生成树,找到一条最短的路径连接所有的点,(或者直接在当前处建立well), 且选择其中建wells cost最小的作为起始点。
'''
graph = collections.defaultdi... | AllieChen02/LeetcodeExercise | Graph/P1168OptimizeWaterDistributionInAVillage/OptimizeWaterDistributionInAVillage.py | OptimizeWaterDistributionInAVillage.py | py | 1,493 | python | en | code | 0 | github-code | 1 |
29880447622 | import math
def preprocess(word):
letters_dict = {}
for letter in word:
letter_count = 0
for letter2 in word:
if letter == letter2:
letter_count += 1
letters_dict.update({letter: letter_count})
return letters_dict
def generate_partitions_with_max(n, ma... | lubani/math | logic4.py | logic4.py | py | 3,038 | python | en | code | 0 | github-code | 1 |
39568625195 | from dataset import CatVsDogImageFoler
from dataloader import return_dataloaders
from trainer import Train
from model import ResNet, BasicBlock, BottleNeck
import torch.nn as nn
import torch
from torchsummary import summary
from collections import namedtuple
dataset = CatVsDogImageFoler()
train_dataset, val_dataset ,... | paragonyun/Papers_I_must_read | ResNet/train.py | train.py | py | 1,942 | python | en | code | 2 | github-code | 1 |
43130214707 |
class Queue:
def __init__(self, n):
self.__head = 0
self.__tail = 0
self.__len = n
self.__queue = [None] * n
def push(self, item):
if self.__tail == self.__len:
if self.__head == 0:
return False
for i in range(self.__head, self.__... | greatming/datastructure | queue.py | queue.py | py | 1,297 | python | en | code | 0 | github-code | 1 |
8088660702 | import csv
from datetime import date
import pandas as pd
import requests
# API Key from EIA
api_key = 'df8bc3420afaf1f07d730567179ad3e3'
# PADD Names to Label Columns used by api data set
PADD_NAMES = ['Date', 'Price']
# Series IDs
PADD_KEY = {'Daily':'NG.RNGWHHD.D ', 'Monthly':'NG.RNGWHHD.M', 'Yearly': '... | eacunagon/Natural-Gas-Prices | main.py | main.py | py | 1,127 | python | en | code | 0 | github-code | 1 |
27764367109 | """ Helper functions for parsing and preparing dataset from
the dateSet dataset
"""
from num2words import num2words
def dateSet_tuple_to_kvs(entry):
day, month, year = entry
assert day > 0 and day <= 31
assert month > 0 and month <= 12
assert year >= 2000 and year <= 2020
if day < 10:
day ... | JKinx/controlled-gen | data_utils/dateSet_helpers.py | dateSet_helpers.py | py | 2,518 | python | en | code | 1 | github-code | 1 |
22738212406 | #!/usr/bin/env python
#coding=utf-8
"""
Created on Wed Apr 14 22:58:08 2021
@author: guoxiong
"""
import threading
import math
import numpy as np
from matplotlib import pyplot as plt
import rospy
import tf
from human_robot_transport.msg import Distance
arrayLength = 100
dist = np.zeros(arrayLength)
def dist_get_an... | guoxxiong/Human-Robot-Co-transporting-Simulation | src/human_robot_transport/scripts/noRunning/distance_plot.py | distance_plot.py | py | 2,292 | python | en | code | 1 | github-code | 1 |
42702881305 | import time
import logging
LOG = logging.getLogger(__name__)
def start():
while True:
LOG.info('hello, I love you.')
LOG.debug('debug , I hate you.')
LOG.warn('warn, I do not like you')
LOG.error('error, I fuck you')
time.sleep(1)
| AndreMouche/python-logdemo | logdemo/inner/heartbeat.py | heartbeat.py | py | 277 | python | en | code | 0 | github-code | 1 |
32973406851 | from stock_paragraph import *
from fill_data_class import *
from functools import reduce
from alive_progress import alive_bar
from utils import *
import re
import os
import docx
from docx.shared import Pt
DEBUG = False
SAVE_PATH = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop', "Документы из программ... | ArkThem/EzDoc | main.py | main.py | py | 4,256 | python | en | code | 0 | github-code | 1 |
3724843078 | # Implement 2 classes, the first one is the Boss and the second one is the Worker.
#
# Worker has a property 'boss', and its value must be an instance of Boss.
#
# You can reassign this value, but you should check whether the new value is Boss. Each Boss has a list of his own workers.
# You should implement a method th... | yukotliar/beetroot | lesson18/homework/task2.py | task2.py | py | 1,602 | python | en | code | 0 | github-code | 1 |
72133850275 | #!/usr/bin/python3
# square.py
"""
class Square that inherits from Rectangle.
"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""
Create a class Square:
- Class constructor:
def __init__(self, size, x=0, y=0, id=None)
"""
def __init__(self, size, x=0, y=0, id=None):
... | jonseb974/holbertonschool-higher_level_programming | python-almost_a_circle/models/square.py | square.py | py | 1,837 | python | en | code | 0 | github-code | 1 |
16862918839 | from cliff import lister
from oio.cli.admin.common import ContainerCommandMixin
class ContainerVacuum(ContainerCommandMixin, lister.Lister):
"""
Vacuum (defragment) a database.
Execute the operation on the master service, then
resynchronize the database on the slaves.
"""
columns = ("Contai... | open-io/oio-sds | oio/cli/admin/item_vacuum.py | item_vacuum.py | py | 1,548 | python | en | code | 621 | github-code | 1 |
29634274791 | import sys
import threading
from colorama import Fore, Style,init
from utils import *
def animate(message):
for c in itertools.cycle(['|', '/', '-', '\\']):
if done:
break
print("\r"+Style.BRIGHT+Fore.GREEN+message+c+Fore.RESET, end="")
time.sleep(0.1)
def build(direc, port1, i... | DanyMilan23/BotAndroid | build.py | build.py | py | 3,022 | python | en | code | 0 | github-code | 1 |
37870059486 | import os
from pydub import AudioSegment
from bewise_second.settings import BASE_DIR
def convert_to_mp3(audio_file):
"Конвектирует wav -> mp3"
audio_file = str(audio_file)
audio_name = '.'.join(audio_file.split('.')[:-1])
src = os.path.join(BASE_DIR, rf"media/{audio_name}.wav") # src to dst
dst ... | anton431/bewise_2 | bewise_second/index/utils.py | utils.py | py | 565 | python | en | code | 0 | github-code | 1 |
26849576202 | import numpy as np
from eigen_rootfinding.Macaulay import build_macaulay, find_degree, \
create_matrix
from eigen_rootfinding.Multiplication import indexarray,indexarray_cheb,\
msroots,get_rand_combos_matrix
from eigen_rootfinding.polyn... | tylerjarvis/eigen_rootfinding | eigen_rootfinding/Nullspace.py | Nullspace.py | py | 17,548 | python | en | code | 0 | github-code | 1 |
33612373314 | import os
import pytest
import itertools
from openeis.applications.utest_applications.fixture_support import (project,
active_user,
create_dataset,
... | VOLTTRON/openeis | openeis/applications/utest_applications/utest_whole_building_energy_savings/conftest.py | conftest.py | py | 2,530 | python | en | code | 10 | github-code | 1 |
27060149406 | import os
import cv2
import timm
import torch
import numpy
import warnings
import pandas as pd
from tqdm import tqdm
import torch.nn as nn
import seaborn as sns
from scipy.stats import zscore
import matplotlib.pyplot as plt
import torch.nn.functional as F
from siren_pytorch import SirenNet
from sklearn.compose import C... | QLaHPD/V-Desafio-de-Ciencias-de-Dados-PUCGO | train_siren.py | train_siren.py | py | 4,013 | python | en | code | 0 | github-code | 1 |
9539821634 | from matrizTransicao_01 import *
def geraMatrizTransicao():
matriz = np.zeros([123, 123])
for i in range(0, 123):
linha = estadoTransicao(i)
matriz[i] = linha
return matriz
def probablidadesZ(t:int):
m = geraMatrizTransicao()
vetorInicial = np.zeros([123])
vetorInicial[0] = ... | mendesv1t/bancoImobiliarioMarkov | posicaoJogadorInfinito_05.py | posicaoJogadorInfinito_05.py | py | 966 | python | pt | code | 0 | github-code | 1 |
19747177274 | from FoodInventory import FoodInventory
from Food import Food
from Foodlog import Foodlog
class Interface: #amrit start
@staticmethod
#___________________________________________________________________________
def food_interface_cl():
print("*****************************************************... | ASingh-github/Calorie_Food_Tracker | Interface.py | Interface.py | py | 8,354 | python | en | code | 0 | github-code | 1 |
69800290914 | from django.contrib import admin
from django.urls import path, include, re_path
from . import views
urlpatterns = [
path('', views.index),
path('select_moive/', views.select_moive, name="select_moive"),
path('select_page/', views.select_page, name="select_page"),
path('select_contain/', views.select_co... | shaguahehehe/movie | moive_website/movie_detail/urls.py | urls.py | py | 471 | python | en | code | 0 | github-code | 1 |
25617604628 | import os
import pandas as pd
import numpy as np
from sklearn.metrics import auc, roc_curve
import xgboost as xgb
from sklearn.preprocessing import MinMaxScaler
base_path = os.path.dirname(os.path.abspath(__file__)) + "/../../data/o2o/"
dataset1 = pd.read_csv(base_path + 'data/dataset1.csv')
dataset1.label.replace(-1,... | littlemesie/tianchi | src/o2o/xgb02_model.py | xgb02_model.py | py | 3,354 | python | en | code | 2 | github-code | 1 |
23996847342 | from django.http import HttpResponse
from django.shortcuts import render
MENU = {"главная стр.":"/", "каталог":"/catalog", "о приложении":"/about"}
def main_page(request):
title = "Главная страницп приложения"
data={"menu": MENU, "title": title}
return render(request, "./index.html", context=data)
#def c... | ivan431/PANEL_CATALOG_DJ | manage_panel_Template/manage_panel_Template/views.py | views.py | py | 693 | python | en | code | 0 | github-code | 1 |
23809878721 | import os
import time
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
from torch.autograd import Variable
def save_results_in_csv(y_pred):
'''
Saves the predictions of test lung images in the provided csv file
:param y_pred: numpy array containing the boolean predictio... | rish01/CPSC340_Covid_Classification | utils.py | utils.py | py | 5,273 | python | en | code | 1 | github-code | 1 |
34372209540 | #!/usr/bin/python
# coding:utf-8
from futu import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data, page_req_key = quote_ctx.request_history_kline('HK.00700', start='2019-09-11', end='2019-09-18',
max_count=5) # 每页5个,请求第一页
if ret == RET_O... | shsun/i47 | bak/test2.py | test2.py | py | 1,070 | python | en | code | 0 | github-code | 1 |
13342435050 | import sys, os, time, random
from basic.constant import ROOT_PATH
from basic.common import makedirsforfile, checkToSkip, printStatus
from basic.annotationtable import readAnnotationsFrom, writeAnnotationsTo, readConcepts, writeConceptsTo
from util.simpleknn.bigfile import BigFile
from svms.mlengine_util import clas... | li-xirong/jingwei | model_based/negbp.py | negbp.py | py | 10,583 | python | en | code | 48 | github-code | 1 |
24631426240 | import pandas as pd
import numpy as np
from datetime import datetime
import talib
from ta.volatility import BollingerBands
from ta.trend import MACD
import plotly as py
from plotly import tools
import plotly.graph_objects as go
import re
file = r'dataset\data\USDJPY_H1.csv'
data = pd.read_csv(file)
data.columns =... | pannawit2541/Forex-Trend-Prediction | Project/SVR_model/preprocessingFix.py | preprocessingFix.py | py | 5,757 | python | en | code | 0 | github-code | 1 |
14498330916 | import re
fs = open('2020/day7/input.txt', 'r')
link = {}
inside = {}
line = fs.readline().strip('\n')
count = 1
def cAndB(bag):
if bag == 'no other':
return
s = bag.split(' ')
return (' '.join(s[1:]), s[0])
while line:
bag, contained = line.split(' bags contain ')
# print(contained.spli... | kwfk/advent-of-code | 2020/day7/sol.py | sol.py | py | 1,056 | python | en | code | 0 | github-code | 1 |
20509227195 | import copy
import numpy as np
from scipy.optimize import minimize
def objective_function_full(parameters: np.array, model, solution):
count = 0
for task in model.last_scenario.tasks:
if task != solution:
if model.comparison_function(parameters, task, solution) == solution:
... | QuimLaz/HackEPS | src/classes/selector.py | selector.py | py | 2,141 | python | en | code | 1 | github-code | 1 |
29280991881 | from setuptools import setup, find_packages
# requirement file
with open('requirements.txt') as f:
required = f.read().splitlines()
# readme file
with open('README.md') as f:
readme = f.read()
setup(
name='textstada',
version='0.0.1',
description='No frills text data cleaning methods. Stada mean... | jhags/text-stada | setup.py | setup.py | py | 979 | python | en | code | 0 | github-code | 1 |
7555976140 | from matplotlib import pyplot as plt
import numpy as np
from tensorflow import keras
def go():
X_train = np.linspace(0, 20, 100)
y_train = 3 * np.sin(X_train) + np.random.normal(0, 0.3, 100)
X_test = np.linspace(20, 30, 50)
y_test = 3 * np.sin(X_test) + np.random.normal(0, 0.3, 50)
model = keras.... | sesc-infosec/sesc-infosec.github.io | src/Lecture 15/NeuralNetworks/my_regression.py | my_regression.py | py | 965 | python | en | code | 0 | github-code | 1 |
32791046376 | # uncompyle6 version 3.8.0
# Python bytecode 3.8.0 (3413)
# Decompiled from: Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)]
# Embedded file name: hidden_treasure.pyw
import time, queue, msilib, threading, base64, struct, sys, hashlib
from Crypto.PublicKey import RSA
import platf... | PKU-GeekGame/geekgame-1st | writeups/players/thezzisu/data/Algorithm/电子游戏概论/auto_treasure_nox.py | auto_treasure_nox.py | py | 6,756 | python | en | code | 52 | github-code | 1 |
33519452722 | from functools import partial
from robotide.lib.robot.errors import VariableError
from robotide.lib.robot.utils import (is_dict_like, is_list_like, normalize,
RecommendationFinder)
def variable_not_found(name, candidates, msg=None, deco_braces=True):
"""Raise DataError for missing variab... | robotframework/RIDE | src/robotide/lib/robot/variables/notfound.py | notfound.py | py | 1,274 | python | en | code | 910 | github-code | 1 |
20350786195 | from detection import *
from get_url import *
from image import *
from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
import os
def auth():
l = []
k = []
k.append("your-key")
k.append("your-key")
k.append("your-key")
... | Canardier/Hackaton-Microsoft | python-server/recoco.py | recoco.py | py | 1,358 | python | en | code | 0 | github-code | 1 |
5856923631 |
from cgitb import html
from keras.models import load_model
from flask import *
from PIL import Image
from sqlalchemy import false, true
from werkzeug.utils import secure_filename
import cv2
import numpy as np
import easyocr
import os
model = load_model('icrecognition.h5')
classes = {
0 : 'No Pain',
1 : 'Pain... | Aqiliman24/icdetection | icrecognitionapp.py | icrecognitionapp.py | py | 2,261 | python | en | code | 0 | github-code | 1 |
34524998755 | # USAGE
# python gradient_descent.py
# import the necessary packages
import matplotlib.pyplot as plt
from sklearn.datasets.samples_generator import make_blobs
import numpy as np
import argparse
def sigmoid_activation(x):
return 1.0 / (1 + np.exp(-x))
def next_training_batch(X, y, batchSize):
for i in np.arange(... | huxiaoman7/learningdl | Chapter3/sgd/sgd.py | sgd.py | py | 1,991 | python | en | code | 256 | github-code | 1 |
72410871074 | import requests
import httpx
chrome_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' \
' (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
print(... | ElliotGarbus/MastodonExperiments | experiments/test_sleeping.py | test_sleeping.py | py | 870 | python | en | code | 0 | github-code | 1 |
39304816896 | '''
An efficient program to solve loopover
'''
from collections import deque
def SOLVED(scrambled, solved, INVERSE):
scrambled = list(map(lambda x: list(map(lambda y:INVERSE[tuple(y)], x)), scrambled))
return scrambled == solved
def parity(board):
Q = [[1 if board[i][j]!=[i, j] else 0 for j in range(len(boa... | XRFXLP/Puzzle-and-CSP-solvers | Loopover.py | Loopover.py | py | 8,573 | python | en | code | 0 | github-code | 1 |
25448667162 | from math import factorial
total = 0
for i in range(3,10000000):
digits = []
for num in str(i):
digits.append(int(num))
sum = 0
for j in digits:
sum += factorial(j)
#print(i, digits, sum)
if i == sum:
total += sum
print(total) | badmathematics/projecteuler | problem34.py | problem34.py | py | 302 | python | en | code | 0 | github-code | 1 |
36436502173 | # 参考 https://stats.stackexchange.com/questions/71335/decision-boundary-plot-for-a-perceptron
import numpy as np
from sklearn.linear_model import Perceptron
import matplotlib.pyplot as plt
def g(x):
if x > 0:
return 1
else:
return 0
def update_weights(w, X, y, a = 1):
py = 0... | fanqo/MMLwsl_2nd_zh | ch10/test.py | test.py | py | 1,558 | python | en | code | 0 | github-code | 1 |
71155389793 | import os
import csv
import copy
import textwrap
import string
import gzip
import shutil
import textwrap
import itertools
import math
# Relevant
import pandas
import sklearn
import scipy
import numpy
import statsmodels.api
# Custom
#dir()
#importlib.reload()
########################################################... | tcameronwaller/partner | package/utility.py | utility.py | py | 148,385 | python | en | code | 0 | github-code | 1 |
13762849770 | # 코드업 100제
# 6079번-[기초-종합]언제까지더해야할까?(py).py
'''
1, 2, 3 ... 을 계속 더해 나갈 때,
그 합이 입력한 정수(0 ~ 1000)보다 같거나 작을 때까지만
계속 더하는 프로그램을 작성해보자.
즉, 1부터 n까지 정수를 계속 더해 나간다고 할 때,
어디까지 더해야 입력한 수보다 같거나 커지는 지를 알아보고자하는 문제이다.
*****예시
-
*****입력
정수 1개가 입력된다.
*****출력
1, 2, 3, 4, 5 ... 를 순서대로 계속 더해 합을 만들어가다가,
입력된 정수와 같거나 커졌을 때, 마지막에 더한 정수... | irishNoah/Algorithm-Study | codeup(코드업)/기초100제/파이썬/012_기초-종합/6079번-[기초-종합]언제까지더해야할까(py).py | 6079번-[기초-종합]언제까지더해야할까(py).py | py | 877 | python | ko | code | 4 | github-code | 1 |
30710414666 | import matplotlib.pylab as plt
import numpy as np
import scipy
from scipy import interpolate
import sys
import os
from linetools.isgm.abscomponent import AbsComponent
import json
from pyigm.guis import igmguesses
from linetools.spectra.io import readspec
import spectrum_analysis_tools as spa
# inwave = REST wavelen... | ibutsky/synthetic_spectra | scripts/analysis/eqwrange.py | eqwrange.py | py | 11,423 | python | en | code | 0 | github-code | 1 |
26623887723 | # 第六章 字典
# 字典用放在方括号中的一系列键值对表示
alien_0 = {'color': 'green', 'point': 5}
print(alien_0['color']) # green
print(alien_0['point']) # 5
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0) # {'color': 'green', 'point': 5, 'x_position': 0, 'y_position': 25}
# 删除键-值对
alien_0 = {'color': 'green', 'point': 5... | kdjlyy/PythonCode | 《Python编程从入门到实践》/Chapter_6_字典.py | Chapter_6_字典.py | py | 3,673 | python | en | code | 1 | github-code | 1 |
23973134815 | #!/usr/bin/python3
def Tri(n):
p = int(n*(n+1)/2.);
return p
def main():
Starter = 20;
Value = 0;
NOD = 200; #//Number of divisiors required
while(True):
Current = Tri(Starter)
#print('Current tri is ',Current)
Count = 0
for p in range(1,Current+1):
... | pranphy/ProjectEuler | 12/HighlyDivisibleTriangularNumber.py | HighlyDivisibleTriangularNumber.py | py | 532 | python | en | code | 0 | github-code | 1 |
73944272352 | from functools import partial
import os
from argparse import ArgumentParser
import numpy as np
import open3d as o3d
from utils.dyn_feasibility_check import check_dyn_feasible, check_dyn_feasible_parallel, simple_check_dyn_feasible
from utils.kin_feasibility_check import check_kin_feasible, check_kin_feasible_parallel
... | Ericcsr/synthesize_pregrasp | data/scripts/generate_data_from_seeds.py | generate_data_from_seeds.py | py | 6,266 | python | en | code | 8 | github-code | 1 |
36982929768 | # !apt-get install -y xvfb python-opengl > /dev/null 2>&1
# !pip install gym pyvirtualdisplay > /dev/null 2>&1
import gym
import numpy as np
import random
import math
from tqdm import tqdm
# We can also use CartPole-v1 but it's slower
env_name = "CartPole-v0"
# Information from OpenAi Gym's repository, velocity and ... | z1q1chen/Reinforcement-Learning | Assignment 2/Assignment.py | Assignment.py | py | 3,726 | python | en | code | 1 | github-code | 1 |
322552777 | from graphviz import Digraph as DotGraph
from wordcloud import WordCloud
import matplotlib.pyplot as plt
def showGraph(dot, show=True, file_name='textgraph.gv'):
dot.render(file_name, view=show)
'''
def gshow0(g, file_name='textgraph.gv', show=True):
dot = DotGraph()
for e in g.edges():
f, t = e
# w = ... | ptarau/TextGraphCrafts | textcrafts/vis.py | vis.py | py | 832 | python | en | code | 4 | github-code | 1 |
1629924878 | import environ,os, boto3
from pathlib import Path
import base64
import hashlib
import datetime
BASE_DIR = Path(__file__).resolve().parent.parent
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))
env = environ.Env(
DEBUG=(bool, True)
)
def upload(user,image,*args):
s3 = boto3.client('s3',
aws_acce... | Super-fast-decision-making/Petrasche_back | user/s3upload.py | s3upload.py | py | 816 | python | en | code | 2 | github-code | 1 |
6697572936 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
# Reading the data
path = '/Users/iuliano/Documents/Proj/'
df = pd.read_excel(path + 'Dataset - Case Study - BI Analyst Wunderflats.xlsx')
# Rename columns
df = df.rename(columns={'dteday': 'date',
... | MarioIuliano87/project_wf | python_code.py | python_code.py | py | 6,217 | python | en | code | 0 | github-code | 1 |
23999954115 | """
Written by: Jonas Vander Vennet
on: 2019/12/30
Answer: 430
"""
def get_orbitmap(orbits):
orbitmap = {}
for center, orbiter in orbits:
if center not in orbitmap.keys():
orbitmap[center] = []
if orbiter not in orbitmap.keys():
orbitmap[orbiter] = []
orbitmap[c... | jonasvandervennet/adventofcode | 2019/06/part 2/main.py | main.py | py | 1,903 | python | en | code | 0 | github-code | 1 |
74252720032 | # udemy
# import Account as Acc
from operation import Operation
from os import system
accounts = []
op = Operation()
#print(Op)
if __name__ == "__main__":
while(True):
op.printOptions()
options='0'
options = input("Selection : ")
if options=="q":
break
elif (options!="clear"):
system("clear")
op.do... | jarvissuperuser/python_example | py.py | py.py | py | 369 | python | en | code | 0 | github-code | 1 |
11484444157 | from typing import Tuple
from neural import *
def parse_line(line: str) -> Tuple[List[float], List[float]]:
"""Splits line of CSV into inputs and output (transormfing output as appropriate)
Args:
line - one line of the CSV as a string
Returns:
tuple of input list and output list
"""
... | LT-Intro-To-AI/assignment7-BryanD17 | cleveland_data.py | cleveland_data.py | py | 3,872 | python | en | code | 0 | github-code | 1 |
39255159498 | """
1. Go to copart.com
2. Look at the Makes/Models section of the page
3. Create a two-dimensional list that stores the names of the Make/Model as well as their URLs
4. Check that each element in this list navigates to the correct page
"""
from pprint import pprint
MAKES_AND_MODELS = "//a[contains(@href, 'popular/mak... | ElSnoMan/twitch-challenges | copart_com/test_challenge_7.py | test_challenge_7.py | py | 726 | python | en | code | 6 | github-code | 1 |
13809327767 | from flask import render_template, Blueprint, flash
from flask import request, redirect, url_for, session
from suchwow.models import Post, Comment, Profile
from suchwow.utils.decorators import login_required
bp = Blueprint("comment", "comment")
@bp.route("/comment/create/post/<post_id>", methods=["GET", "POST"])
@lo... | t-900-a/suchwow | suchwow/routes/comment.py | comment.py | py | 1,087 | python | en | code | 0 | github-code | 1 |
34872350568 | from sys import argv
import jetson_inference as ji
import jetson_utils as ju
import time
from jetson_utils import cudaFont
import argparse
def draw_boxes(img, detections):
for detection in detections:
if detection.ClassID == 1:
left = int(detection.Left)
top = int(detection.Top)
... | strikerPro818/strikerBot | Xavier_NX/jetsonSimple.py | jetsonSimple.py | py | 2,035 | python | en | code | 0 | github-code | 1 |
28522503343 | import atexit
import sqlite3
import sys
import traceback
sys.path.append('./server')
from content import *
from helper import *
# Example value: 8_to_9
migration_numbers = sys.argv[1]
version = int(sys.argv[2])
# There must be two SQL files for each migration. One checks
# whether the migration has already occurred.... | srp33/CodeBuddy | front_end/migration_scripts/migrate.py | migrate.py | py | 1,175 | python | en | code | 8 | github-code | 1 |
30979904425 | # -*- coding: utf-8 -*-
"""
Created on Fri May 19 07:24:06 2017
@author: manuj
"""
import datetime
from django.utils import timezone
from dateutil.parser import parse
import datefinder
import difflib
import time
import numpy as np
import pandas as pd
from MovieScraper import MovieScraper
from MovieListCleaner import... | manujosephv/MovieScraper | movielistview/Utils.py | Utils.py | py | 8,333 | python | en | code | 0 | github-code | 1 |
33488482675 | import tensorflow.compat.v2 as tf
from scipy.optimize import minimize
import numpy as np
import tensorflow_probability as tfp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
np.sum(np.array([a for a in ra... | Mikhail-Klochkov/diploma_project | another_variant.py | another_variant.py | py | 5,991 | python | en | code | 0 | github-code | 1 |
13010327748 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
try:
bytes
except NameError:
bytes = str
str = unicode
def reverse(x):
'''We assume it is a helper function for something else.
It returns True to let other stuff work.
'''
if not isinstance(x, (bytes, s... | moskytw/clime | examples/reverse.py | reverse.py | py | 532 | python | en | code | 152 | github-code | 1 |
26469890697 | import os
import random
from collections import defaultdict
import nltk
from nltk.util import ngrams
# Step 1: Import necessary libraries
nltk.download('punkt')
# Step 2: Read and preprocess the text from the files
def read_text_files(folder_path):
text_corpus = []
for filename in os.listdir(folder_path):
... | Shilpi-droid/IR-Lab-Repository | Experiment1.py | Experiment1.py | py | 2,204 | python | en | code | 0 | github-code | 1 |
17646478091 |
import xml.etree.ElementTree as ET
import gpxpy
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from datetime import datetime,timedelta
import osmnx as ox
import networkx as nx
import xml.sax
import fiona
import csv
fr... | aceacedey/Mode_Detection_and_Parking_Data | TrainTestModechangesCWSelected.py | TrainTestModechangesCWSelected.py | py | 10,626 | python | en | code | 0 | github-code | 1 |
17506501348 | # A Simple Calculator using class and oops - Multiple inheritance
class Addition:
def __init__(self, number01, number02):
self.number01 = number01
self.number02 = number02
def add(self):
"""
This function takes two numbers as input and returns their sum
:return: the sum ... | anoopch/PythonExperiments | oops/Lab_Ex_114_Simple_Calc.py | Lab_Ex_114_Simple_Calc.py | py | 4,015 | python | en | code | 0 | github-code | 1 |
74257419234 | #from torchvision.datasets.vision import VisionDataset
from core.VisionDataset import VisionDataset
from PIL import Image
import os
import os.path
import imageio
import numpy as np
import random
from torchvision import transforms
import torch
def has_file_allowed_extension(filename, extensions):
"""Checks if... | cc-hpc-itwm/FacialGAN | Training/core/own_data_loader.py | own_data_loader.py | py | 10,969 | python | en | code | 16 | github-code | 1 |
5960545124 | cards = input().split()
shuffles_count = int(input())
middle_len = len(cards)//2
for _ in range(shuffles_count):
res = []
for index in range(middle_len):
first_card = cards[index]
second_card = cards[index + middle_len]
res.append(first_card)
res.append(second_card)
cards... | LachezarKostov/SoftUni | 01_Python-Basics/Lists/Faro Shuffle.py | Faro Shuffle.py | py | 339 | python | en | code | 1 | github-code | 1 |
6864810139 | import matplotlib.pyplot as plt
import visuals
import switch_functions as switch
import looper
import malus_calc
import numpy as np
"""
These are the used functions. For instructions on how to use them navigate to the README.md
solution = switch.single_loop():
switch.activity_switch_emptyslot(seconds,timeout_amount... | DutchProg/Roostermakers | __Main/rooster.py | rooster.py | py | 2,554 | python | en | code | 0 | github-code | 1 |
41266251835 | import pandas as pd
def simulate_retirement(df, savings, initial_withdrawal_rate,
adjustment_withdrawal_rate, retirement_length,
initial_equity_weight, equity_glide_adjustment,
success_rule=1):
"""A function to simulate the outcome of retirem... | Sdmillheim/retirement-simulator | retirement_simulator.py | retirement_simulator.py | py | 4,714 | python | en | code | 0 | github-code | 1 |
27190966619 | #Giải mã base64 --> ảnh
from base64 import b64decode
#print(b64decode('AQID'))
f = open('imagebase64.txt')
b64data = f.read()
f.close()
data = b64decode(b64data)
print(len(data))
f = open('out.png', 'wb')
f.write(data)
f.close() | pytutorial/py2011E | Day10/vd4.py | vd4.py | py | 236 | python | vi | code | 1 | github-code | 1 |
4033797824 | import sys
import socket
import re
# you may use urllib to encode data appropriately
import urllib.parse
def help():
print("httpclient.py [GET/POST] [URL]\n")
class HTTPResponse(object):
def __init__(self, code=200, body=""):
self.code = code
self.body = body
class HTTPClient(object):
#de... | kalegar/CMPUT404-assignment-web-client | httpclient.py | httpclient.py | py | 3,953 | python | en | code | null | github-code | 1 |
35077688849 | from django.db import models
from django.utils import timezone
from datetime import datetime, timedelta
from django import forms
#===========Project_Information=============================
class ProjectInformation(models.Model):
class Meta:
verbose_name = 'Project Information Record'
RESPON... | stan3000/Projectmanagement | management/models.py | models.py | py | 9,328 | python | en | code | 1 | github-code | 1 |
28698897403 | from sqlalchemy import Column, MetaData, Table, Integer, String, DateTime
from sqlalchemy.sql import func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.postgresql import JSON
Base = declarative_base()
class VcmsFeaturePklFile(Base):
__tablename__ = 'feature_pkl_files'
sn =... | clubfly/python_flask | orm_models/vcmsfeaturepklfile.py | vcmsfeaturepklfile.py | py | 2,353 | python | en | code | 1 | github-code | 1 |
31891553494 | # pp_session.py
import logging
from datetime import datetime
from enum import Enum
import pandas as pd
from typing import Optional
from binance import enums as k_binance
from src.pp_market import Market
from src.pp_order import Order, OrderStatus
from src.pp_account_balance import AccountBalance
from src.xb_pt_calcu... | xavibenavent/polaris_plus | src/pp_session.py | pp_session.py | py | 14,070 | python | en | code | 0 | github-code | 1 |
44649117734 | class Dictionary:
'''
Creating a Dictionary
'''
def create_dictionary(self):
my_dict ={"name": "john", "age": 24, "address": "vizag", "eduction": "masters"}
return my_dict
if __name__ == "__main__":
print(Dictionary().__doc__)
print(Dictionary().create_dictionary())
| TarakaKoda/Python-Data-Structures-and-Algorithms | 11 - Dictionaries/Dictionary Practice/01. Creating a Dictionary.py | 01. Creating a Dictionary.py | py | 309 | python | en | code | 0 | github-code | 1 |
72662517475 | import os
os.chdir("/home")
import numpy as np
from src.data.obtain import json_read, json_write
def persist(e):
"""
Convert a sklearn estimator into a JSON object for persistence
Parameters
----------
e: Estimator
An sklearn estimator
Returns
-------
persist: dic... | dushyantkhosla/ds-docker-walkthru-titanic | src/model/persist.py | persist.py | py | 1,165 | python | en | code | 0 | github-code | 1 |
72153307874 | """
Browser (:mod:`pydent.browser`)
=================================
.. versionadded:: 0.1
Browser class created
.. currentmodule:: pydent.browser
Browser class for searching and cacheing results.
"""
import re
from collections import OrderedDict
from difflib import get_close_matches
from pprint import pformat
... | aquariumbio/pydent | pydent/browser.py | browser.py | py | 47,188 | python | en | code | 6 | github-code | 1 |
8932034968 | from os import listdir
from os.path import isfile, join
def new_node(idd, label, value, r, g, b):
node = ''' <node id="%s" label='%s'>
<attvalues>
<attvalue for="modularity_class" value="0"></attvalue>
</attvalues>
<viz:size value="%s"></... | LuShengDong/handsomedong.github.com | generating.py | generating.py | py | 2,648 | python | en | code | 0 | github-code | 1 |
75213145312 | import pandas as pd
from pandas.core.frame import DataFrame
from decimal import Decimal
datas = pd.read_csv('Labeling_v3.2.csv').to_dict('records')
def get_txcount(data):
mint = int(data['mint_count'])
burn = int(data['burn_count'])
swap = int(data['swap_count'])
return mint + burn + swap
def get_h... | kangmyoungseok/RugPull-Prediction-AI | 2. Feature/4. Labeling File/Labeling_to_Dataset.py | Labeling_to_Dataset.py | py | 2,802 | python | en | code | 17 | github-code | 1 |
71869489635 | from os import path
from setuptools import setup, find_packages
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as readme_file:
readme = readme_file.read()
requirements = [
'click'
]
test_requirements = [
]
setup(
name='intercom',
version='0.9',... | bceylan/intercom | setup.py | setup.py | py | 1,088 | python | en | code | 0 | github-code | 1 |
19998514733 | import sqlite3
import re
import jwt
import base64
from flask import request, make_response
from utils.util import f, secret_key
from flask_restful import Resource, reqparse
from flask_jwt_extended import jwt_required, get_jwt_identity
from models.user import UserModel
from models.card import CardModel
class Card(R... | 8426988382/secure_api | resources/card.py | card.py | py | 7,420 | python | en | code | 0 | github-code | 1 |
21073123831 | '''
Created on 2019年4月8日
@author: bkd
'''
from traceback import format_exception
import sys
from PyQt5.QtWidgets import QMessageBox
class global_exception_hander:
def new_except_hook(self,etype, evalue, tb):
print(''.join(format_exception(etype, evalue, tb)))
QMessageBox.information(None,
... | bkdwei/kdFileFinder | kdFileFinder/exception_handler.py | exception_handler.py | py | 590 | python | en | code | 4 | github-code | 1 |
3002930568 | #!/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__':
print('処理対象の年度:範... | rise-pat/patent | fulltxt/Entry.py | Entry.py | py | 3,310 | python | en | code | 0 | github-code | 1 |
2441317746 | from asyncio import tasks
from airflow import DAG
from datetime import datetime, timedelta
from airflow.operators.bash_operator import BashOperator
default_args = {
'owner': 'airflow',
'retries': 2,
'retry_delay': timedelta(minutes=2)
}
with DAG(
dag_id='my_first_dag',
default_arg... | awaisajaz1/apache-airflow-yoda | dags/my_first_dags.py | my_first_dags.py | py | 1,412 | python | en | code | 1 | github-code | 1 |
482110124 | # Importing necessary files
import os
import discord
from dotenv import load_dotenv
import logging.handlers
# .env
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('GUILD_ID')
# Set up logging
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
logging.getLogger('discord.http').setL... | D111GENT/The-Hacker-Hut_Discord-Bot | bot.py | bot.py | py | 1,702 | python | en | code | 0 | github-code | 1 |
25202177087 | import re
import time
import scrapy
from common.domain.hotel import Hotel
from common.domain.review import Review
from database.database_connector import DatabaseConnector
from google_trans_new import google_translator
from scrapy import Request
from textblob import TextBlob
class TripAdvisorSpider(scrapy.Spider):
... | nbratanov/HotelSummaryGenerator | hotel_information/crawlers/spiders/trip_advisor_spider.py | trip_advisor_spider.py | py | 5,953 | python | en | code | 0 | github-code | 1 |
73799729633 | #Harris Collier, Jack Valladares
import numpy
# Different methods of the Q-Learning program
# s(playerPose + applePose + size + trail) = state of the current position relative to the apple and tail
# act(s) = best action so far given s
# rew = instant reward of taking this step
# s'(s, act) = new state
# Q(s... | harrisco4/snaQe | QLearning.py | QLearning.py | py | 3,140 | python | en | code | 1 | github-code | 1 |
31216769509 | import logging
from urllib.parse import unquote
from datetime import datetime
from biocontainers.common.models import MongoToolVersion, ContainerImage
from biocontainers.common.utils import call_api
from bs4 import BeautifulSoup
logger = logging.getLogger('biocontainers.singularity.models')
class SingularityReader:... | BioContainers/biocontainers-backend | biocontainers/singularity/models.py | models.py | py | 2,279 | python | en | code | 3 | github-code | 1 |
40543669494 | #!/usr/bin/env python
# coding: utf-8
# GETTING DATA
# In[1]:
import numpy as np
# In[2]:
data = np.load("./data.npz")
X_train = data["X_train"]
Y_train = data["Y_train"]
X_test = data["X_test"]
print("Shapes")
print("X_train:",X_train.shape)
print("Y_train:",Y_train.shape)
print("X_test:",X_test.shape)
# COM... | sakurusurya2000/Flipr-corona | main.py | main.py | py | 1,346 | python | en | code | 1 | github-code | 1 |
19059817629 | import pandas as pd #pip install pandas
import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install SpeechRecognition
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
# print(voices[1].id)
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio... | Ateeq1234/google_sheets | a.py | a.py | py | 1,291 | python | en | code | 0 | github-code | 1 |
31469702314 | import sys
import os
import re
targets = sys.argv[1:]
p = re.compile(r'.*[a-zA-Z]+0*')
for v in targets:
a = p.sub('', v)
print(a)
input()
os.rename(v, a)
input() | RayJi0428/python-tool | number_png.py | number_png.py | py | 182 | python | en | code | 0 | github-code | 1 |
37550127205 | import numpy as np
from scipy.stats import invwishart
import matplotlib.pyplot as plt
#Initialization
mu0 = [0, 0]
cov0 = [[5, 0], [0, 5]]
dim = 2
df = 10
scale = np.eye(dim)
scale[0,1] = 0.5
scale[1,0] = 0.5
#K = Number of Gaussian, N = Number of data per Gaussian
K = 3
N = 1000
means = []
covariances = []
#Randoml... | nlhoang/Machine-Learning | GMM_generate.py | GMM_generate.py | py | 1,628 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.