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
35361620995
import pygame, sys, os from pygame.locals import * pygame.init() DISPLAYSURF = pygame.dispay.set_mode((400,300),0,32) pygame.display.set_caption('Drawing') black = [0,0,0] white = [255,255,255] red = [255,0,0] green = [0,255,0] blue = [0,0,255] DISPLAYSURF.fill(white) pygame.draw.polygon(DISPLAYSURF, green ((146,0)...
shrikrushnazirape/Python-Game-Development
tutefour.py
tutefour.py
py
628
python
en
code
0
github-code
13
38371228067
"""name: Lyle Martin """ from kivy.app import App from kivy.lang import Builder from kivy.uix.button import Button class CreateWidgetApp(App): def __init__(self, **kwargs): super().__init__(**kwargs) self.names = ['Lyle', 'David', 'Martin'] def build(self): self.title = "Dynamic Wid...
jc304696/Practicals
Lab6/dynamic_widgets.py
dynamic_widgets.py
py
628
python
en
code
0
github-code
13
33105364661
#!/usr/bin/env python3 from os import system,path,listdir,geteuid from shutil import move,copy,copytree import gzip import subprocess import sys import urllib.request def space(n): for i in range(n): print("") def sudo_check(): if geteuid() == 0: print("We're Root!") print("Moving on...") else: ...
bigogre55/Try_Linux
setup/setup.py
setup.py
py
9,681
python
en
code
0
github-code
13
6112575807
# thanks to: https://github.com/lucidrains/byol-pytorch/blob/master/byol_pytorch/byol_pytorch.py import torch import torchvision.models from torch import nn import copy import collections import src.optimizers.loss as losses def load_model(config, model_name, checkpoint_path=None): model = None if model_name...
waverDeep/ImageBYOL
src/models/model.py
model.py
py
9,147
python
en
code
0
github-code
13
28008866559
#Velocidades del carro y distancias del carro #Primer gráfica # Primer grafica # Velocidad del carro X=0-------100;20 km/m # Segunda gráfica # Distancia al auto X=20-------80;20 m #Tercera grafica X=0-------12.5;2.5 km/h #Velocidad del peaton #Cuarta gráfica agregado import numpy as np import skfuz...
felipeflourwears/Fundamentacion-Robotica
Control Inteligente/FuzzySets/actividad.py
actividad.py
py
843
python
es
code
0
github-code
13
15603269902
from copy import deepcopy def n_arr(sizes): if len(sizes) == 0: return [] current_size = sizes[-1] if len(sizes) == 1: return ['""'] * current_size else: sizes = sizes[:-1] nested_arr = n_arr(sizes) return [deepcopy(nested_arr) for _ in range(current_size)] ...
MaksTresh/python-hw-course
hw23/main.py
main.py
py
375
python
en
code
0
github-code
13
26727342571
from selenium import webdriver from NotABot import Logger driver = webdriver.Chrome('C:\\chromedriver_win32\\chromedriver.exe') def Site_parser(URL): a = [] b = [] driver.get(URL) try: table = driver.find_element_by_css_selector('body > div.layout-wrapper.padding-top-default.bg-white.position...
deimosfox/ExchangeRatesTelegramBot
NotABot/SiteParser.py
SiteParser.py
py
1,977
python
en
code
0
github-code
13
16778985513
#!/usr/bin/env python n = int(input()) for TC in range(1, n+1): print(f"Case {TC}: ", end="") y = int(input()) if ((y % 4 == 0) and (y % 100 != 0)) or (y % 400 == 0): print("a leap year") else: print("a normal year")
10946009/yuihuang_zj_ans
syntax/python/zj-d072.py
zj-d072.py
py
251
python
en
code
0
github-code
13
72329907217
# coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import os import zipfile from tensor2tensor.data_generators import generator_utils from tensor2tensor.data_generators import problem from tensor2tensor.data_generators import t...
Cyber-Neuron/nlp_proj
comp550/amzreviews.py
amzreviews.py
py
7,261
python
en
code
1
github-code
13
41633302193
from fastapi import FastAPI from pydantic import BaseModel import uvicorn try: from typing import Literal except ImportError: from typing_extensions import Literal import numpy as np import pandas as pd import joblib from starter.ml.data import process_data from starter.ml.model import inference app = FastAPI(...
NajlaSaud/predict_person_income
.ipynb_checkpoints/main-checkpoint.py
main-checkpoint.py
py
5,645
python
en
code
0
github-code
13
28127517162
import sys from .Player import Player sys.path.append('../') from const import * from utils import * from rule_checker import rule_checker, get_opponent_stone, get_legal_moves from board import make_point, board, get_board_length, make_empty_board, parse_point class AlphaBetaPlayer(Player): def __init__(self, dep...
MicahThompkins/go_project
Deliverables/10/10.1/tournament/player_pkg/AlphaBetaPlayer.py
AlphaBetaPlayer.py
py
2,943
python
en
code
0
github-code
13
1457730055
n = int(input()) d = input().strip() p = [*map(int, input().strip().split())] if 'RL' not in d: print(-1) else: di = iter(d) t = 2e9 i = 0 for _ in di: if d[i : i + 2] == 'RL': t = min(t, (p[i + 1] - p[i]) // 2) next(di) i += 1 i += 1 print(t)
userr2232/PC
Codeforces/A/699.py
699.py
py
319
python
en
code
1
github-code
13
2199252767
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from urllib.parse import urlparse, urlsplit mapping = { 'realtime.china': '即时报道;中港台即时', 'realtime.world': '即时报道;国际即时', 'news.china': '新闻;中国新闻', 'news.world': '新闻;国际新闻' } # mapping2 = { # 'realtime': { # 'china': '中港台即时', # 'world': '国...
a289237642/companySpider
news/news/testcode/zaobao.py
zaobao.py
py
645
python
en
code
0
github-code
13
370918942
import pandas as pd import math from sklearn.model_selection import train_test_split, GridSearchCV import xgboost as xgb from sklearn.metrics import mean_squared_error,r2_score #1.加载数据 file_path = '../datas/slump_test.txt' df = pd.read_csv(file_path, sep=',') # print(help(pd.read_csv)) # print(df.head(5)) #2.获取特征矩...
yyqAlisa/python36
自学/sklearn self-study/Ensemble learing/XGBoost案例代码.py
XGBoost案例代码.py
py
1,329
python
en
code
0
github-code
13
41841594272
# import PIL module from screeninfo import get_monitors from PIL import Image import numpy as np import cv2 as cv # screen dimintions screen_width = get_monitors()[0].width screen_height = get_monitors()[0].height unite = int(screen_height*.1) def paste_buttons(back,front_left=None,front_right=None,front_midel =None)...
Eslamomar007/LaRose
paste_buttons.py
paste_buttons.py
py
1,580
python
en
code
0
github-code
13
8801596830
import torch from torch.utils.data import DataLoader import torchvision import torchvision.transforms as transforms from sklearn.preprocessing import LabelEncoder, OneHotEncoder from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix from os.path import isfile, join from os imp...
ece324-2019/-hashtag
Assignment_4_2/main_2.py
main_2.py
py
11,992
python
en
code
0
github-code
13
73883212497
from django.urls import path from . import views urlpatterns = [ path('', views.blog_home, name='blog_home'), path('post/<slug:slug>/', views.view_blog_article, name='view_post'), path('like/<slug:slug>/', views.PostLikes.as_view(), name='post_likes'), path( 'dislike/<slug:slug>/', vie...
SamuelUkachukwu/PICKnSTRUM
blog/urls.py
urls.py
py
389
python
en
code
1
github-code
13
3759861646
# coding=utf-8 import urllib import urllib2 import json from utils import xml_to_json import logging # from google.appengine.api import urlfetch # urlfetch.set_default_fetch_deadline(45) base_url = 'http://rs.mgimo.ru' url = base_url + "/ReportServer/Pages/ReportViewer.aspx?%2freports%2f%D0%A0%D0%B0%D1%81%D0%BF%D0%B8...
swoopyy/MGIMO-timetable
backend/scrapper.py
scrapper.py
py
3,311
python
en
code
0
github-code
13
34183126799
import json import csv from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage from rest_framework import serializers, viewsets from rest_framework.decorators import action from rest_framework.response import Response from django.http.response import HttpResponse from dj...
codingwarriors01/PsychomatricAssessment
Assesment/views.py
views.py
py
16,257
python
en
code
0
github-code
13
14994549713
# Exercício 2.2 # Dada uma sequência de números inteiros diferentes de zero, terminada por # um zero, calcular a sua soma. Por exemplo, para a sequência: # 12 17 4 -6 8 0 # o seu programa deve escrever o número 35. # link: https://panda.ime.usp.br/aulasPython/static/aulasPython/aula02.html def main(): nu...
josenaldo/python-learning
exercicios/extras/ex-s03e2.2-soma.py
ex-s03e2.2-soma.py
py
643
python
pt
code
1
github-code
13
3895730767
from tkinter import * import random import datetime from tkinter import messagebox, filedialog operador = "" precios_comida = [1.32, 1.65, 2.31, 3.22, 1.22, 1.99, 2.05, 2.65, 1, 2] precios_bebida = [0.25, 0.99, 1.21, 1.54, 1.08, 1.10, 2.00, 1.58, 1, 2] precios_postres = [1.54, 1.68, 1.32, 1.97, 2.55, 2.14, 1.94, 1.74,...
Oviwan999/Arabots-Classes2
Clase Phyton/Clase Presencial restauriante.py
Clase Presencial restauriante.py
py
18,457
python
es
code
0
github-code
13
15584052354
from decimal import Decimal import requests import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from flask import Flask, abort, jsonify from markupsafe import escape from order_service.connector import ConnectorFactory app = Flask(__name__) connector = ConnectorFactor...
YusufnoorEWI/scylladb_postgres_group-5
order_service/service.py
service.py
py
5,608
python
en
code
0
github-code
13
412320647
def remove_dup(arr): # consider arr is sorted or else arr = sorted(arr) print("input arr {}".format(arr)) i = 1 insert_pos = 1 while i < len(arr): if arr[i] != arr[insert_pos-1]: arr[insert_pos] = arr[i] insert_pos += 1 i += 1 print("modified arr {}".forma...
atulkumar-mittal/cp
arrays/remove_duplicates.py
remove_duplicates.py
py
435
python
en
code
0
github-code
13
25320356819
import re from functools import reduce from itertools import groupby import numpy as np in_file = "input.txt" def read_input_lines(): with open(in_file, 'r') as f: data = [x.strip() for x in f.readlines()] data.append("") return data def format_input(in_list): ticketdata_list = (list(data_...
voidlessVoid/advent_of_code_2020
day_16/dominik/main.py
main.py
py
3,350
python
en
code
0
github-code
13
45195018406
from random import randint def partition(T, p, r): x = T[r] i = p - 1 for j in range(p, r): if T[j] <= x: i += 1 T[i], T[j] = T[j], T[i] T[i+1], T[r] = T[r], T[i+1] return i+1 def quickersort(T, p, r): while p < r: q = partition(T, p, r...
kkorta/ASD
SortingAlgorithms/quickosrt.py
quickosrt.py
py
618
python
en
code
0
github-code
13
43010057746
import tkinter as tk from tkinter import ttk,messagebox from tkinter.constants import ANCHOR, CENTER, LEFT, N, NW, RIGHT, TOP, W game = tk.Tk() game.title('Falcon Game') game.geometry('300x350+500+50') a = '\U0001F600' entry_1 = tk.Label(game,text=a,font='arial 50') entry_1.grid(row=1,column=0,padx=10) entry_2 = tk.L...
mdsahil369/Python-Problem-Solve
3 emoji wining game.py
3 emoji wining game.py
py
1,818
python
en
code
0
github-code
13
10587837536
import numpy as np def distance(a, b): """ 返回两个向量间的欧式距离 """ return np.sqrt(np.sum(np.power(a - b, 2))) def rand_center(data, k): """ 随机设置k个中心点 """ m = data.shape[1] # 数据的维度 centroids = np.zeros((k, m)) for j in range(m): d_min, d_max = np.min(data[:, j]), np.max(data...
IOTDB-Elites/ClassificationAndClustering
clustering/kmeans/k_means.py
k_means.py
py
1,792
python
en
code
0
github-code
13
14042599067
# URL du site main_url = "https://www.cessionpme.com" # Liste des départements à traiter en associant les clés aux valeurs correspondante departement_imo = { "64": "93", "33": "87" } # Rubrique à traiter rubrique_imo = { "Locaux, Entrepôts, Terrains": "2", "Bureaux, Coworking": "52" } # Bien à la ve...
FannyDFT/python_immo
scrap/conf.py
conf.py
py
345
python
fr
code
0
github-code
13
72053136977
import threading import tkinter as tk from functools import partial from tkinter import messagebox import numpy as np import Controller as gc # thread class GuiInterface: event = gc.Event() arrButton = {} memory = [] sizeRow = 13 sizeCol = 13 checked = np.zeros((sizeRow, sizeCol)) def ...
tryCod3/PyThon-Caro
Enviroment/MyGame/Gui.py
Gui.py
py
4,477
python
en
code
0
github-code
13
25259027504
#!/usr/bin/env python3 import argparse import sys def get_fh(filename, mode): """ get_fh function will 1) read in file name. 2) open a file and 'read' or 'write' Purpose of the function is to open the file name passed in and pass back the file handle. * All opening and closing of files in your program shou...
Parinitha-kompala/Nucleotide-Analysis-from-FASTA-files
nucleotide_statistics_from_fasta22.py
nucleotide_statistics_from_fasta22.py
py
2,914
python
en
code
0
github-code
13
43403295483
import os #Manually fix the GPU os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]="0" import sys #Add EDM to path to load models properly # change this line to point to your specific path sys.path.append("/home/sravula/MRI_Sampling_Diffusion/edm") from utils.exp_utils import set_all...
Sriram-Ravula/MRI_Sampling_Diffusion
main.py
main.py
py
813
python
en
code
4
github-code
13
28773531340
"""Auxiliary functions.""" try: import cPickle as pickle except ImportError: import pickle import re import os from SPARQLWrapper import SPARQLWrapper, JSON YAGO_ENPOINT_URL = "https://linkeddata1.calcul.u-psud.fr/sparql" RESOURCE_PREFIX = 'http://yago-knowledge.org/resource/' def safe_mkdir(dir_name): ...
MIREL-UNC/mirel-scripts
yago_scripts/utils.py
utils.py
py
4,600
python
en
code
0
github-code
13
70268962578
from setuptools import setup, Extension from setuptools.command.test import test as TestCommand import sys install_requires = [ 'colorama', 'enum34', 'tabulate', 'six', 'mako', 'Twisted', 'autobahn', 'ply' ] tests_requires = [ 'tox', 'virtualenv' ] class Tox(TestCommand): user_options = [('tox-...
happz/ducky-legacy
setup.py
setup.py
py
2,992
python
en
code
5
github-code
13
43082687746
#! /usr/bin/env python # # -*- coding: utf-8 -* """ rcs-keywords-post-checkout This module provides code to act as an event hook for the git post-checkout event. It detects which files have been changed and forces the files to be checked back out within the repository. If the checkout event is a file based event, ...
mdrotthoff/git-rcs-keywords
dist/rcs-post-checkout.py
rcs-post-checkout.py
py
7,461
python
en
code
3
github-code
13
14583375235
from umqtt.simple import MQTTClient from machine import Pin led=Pin(5, Pin.OUT) led.value(1) def msg(a,b): data=(str(b,'utf-8')) print(data) if "LED on" in data: led.value(0) if "LED off" in data: led.value(1) def client(): server="test.mosquitto.org" c = ...
freedomwebtech/raspberry-pi-4-voice-homeautomation-part2
esp8266sub.py
esp8266sub.py
py
509
python
en
code
1
github-code
13
31234485909
def homework_1(nums): # 請同學記得把檔案名稱改成自己的學號(ex.1104813.py) max = 1 count = 1 for i in range(len(nums)): if i==(len(nums)-1): break x = nums[i] if x == nums[i+1]: count+=1 a = count if a > max: max = a else: ...
daniel880423/Member_System
file/hw1/1100434/s1100434_10.py
s1100434_10.py
py
508
python
en
code
0
github-code
13
6799671932
"""" Tgus module handles the windowing fucntions for ImageWatcher""" from src.ui.imageviewerkeyhandler import ImageViewerKeyHandler from src.ui.utils import get_resolution_linux, print_cb_data import dearpygui.dearpygui as dpg import logging import time from PIL import Image class ImageViewerWindow: def __init_...
burstMembrane/imagewatcher
src/ui/imageviewerwindow.py
imageviewerwindow.py
py
7,968
python
en
code
0
github-code
13
25540710754
from rest_framework import serializers from heroes.models import ( Resource, Town, Class, SecondarySkill, Spell, Creature, Specialty, Hero, ) class ResourceSerializer(serializers.ModelSerializer): class Meta: model = Resource fields = ("id", "name", "picture_url") ...
volodymyr-vereshchak/heroes3-rest-api
heroes/serializers.py
serializers.py
py
4,891
python
en
code
0
github-code
13
24654334231
__author__ = 'Michael Kaldawi' """ Programmer: Michael Kaldawi Class: CE 4348.501 Assignment: P01 (Program 1) Program Description: This program implements a prime number finder utilizing the sieve of Eratosthenes, multiprocessing, and communication via pipes. """ # Note: we are using numpy for our array processing t...
michael-kaldawi/Prime-Number-Multiprocessing
PipeTest.py
PipeTest.py
py
4,121
python
en
code
1
github-code
13
17057594194
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class PageVisitDataResponse(object): def __init__(self): self._page_pv = None self._page_uv = None self._url = None @property def page_pv(self): return self._pa...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/PageVisitDataResponse.py
PageVisitDataResponse.py
py
1,702
python
en
code
241
github-code
13
31741741795
# 初始化 from time import time import numpy as np import matplotlib.pyplot as plt from matplotlib import rc from skimage import io # from __future__ import print_function # %matplotlib内联 plt.rcParams['figure.figsize'] = (15.0, 12.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams...
lixixi89055465/py_stu
segment/train.py
train.py
py
2,657
python
en
code
1
github-code
13
22984748178
""" Реализуйте класс Version, описывающий версию программного обеспечения. При создании экземпляра класс должен принимать один аргумент: version — строка из трех целых чисел, разделенных точками и описывающих версию ПО. Например, 2.8.1. Если одно из чисел не указано, оно считается равным нулю. Например, ве...
Archangel-Ray/OOP_Generation-Python_course-on-Stepik
5. Магические методы/5.3 Сравнение объектов/04 сравнить строку из трёх чисел.py
04 сравнить строку из трёх чисел.py
py
6,421
python
ru
code
0
github-code
13
8961097609
import pytest from asynctest import TestCase, logging from Trader import Trader from OrderRequest import OrderRequest, OrderRequestStatus, OrderRequestType, OrderRequestList, SegmentedOrderRequestList import jsonpickle POLONIEX = 'poloniex' BINANCE = 'binance' KRAKEN = 'kraken' BITSTAMP = 'bitstamp' COINBASEPRO = 'co...
gbarany/crypto-arbitrage-finder
src/Trader_e2e_test.py
Trader_e2e_test.py
py
2,487
python
en
code
4
github-code
13
39859177360
from typing import Optional import flet as ft from switchpokepilot.mainwindow.state import MainWindowState from switchpokepilot.mainwindow.ui.command_area import CommandArea from switchpokepilot.mainwindow.ui.log_area import LogArea from switchpokepilot.mainwindow.ui.video_area import VideoArea class ToolsArea(ft.U...
carimatics/switch-poke-pilot
switchpokepilot/mainwindow/ui/tools_area.py
tools_area.py
py
2,693
python
en
code
3
github-code
13
73314022099
import os import sys import time import numpy as np import argparse import torch import torch.backends.cudnn as cudnn import torch.nn as nn from datetime import datetime import scipy.io as scio from util.SetRandomSeed import set_seed, worker_init from util.SaveChkp import save_checkpoint from util.MakeDataList import...
Depth2World/Under-scanning_NLOS
validate_utils/tra_algo.py
tra_algo.py
py
5,353
python
en
code
1
github-code
13
37154804684
from __future__ import print_function, absolute_import, division import six import operator import itertools import warnings import mmap from distutils.version import LooseVersion import sys import pytest import astropy from astropy.io import fits from astropy import units as u from astropy.wcs import WCS from astro...
mevtorres/astrotools
spectral_cube/tests/test_spectral_cube.py
test_spectral_cube.py
py
69,166
python
en
code
0
github-code
13
1985561854
#!/usr/bin/env -S ipython --matplotlib=auto #%% import matplotlib.pyplot as pp import numpy as np import os path = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(path, 'nft-rates.csv') data = np.genfromtxt(path, delimiter=',')[2:] year = data[:, 0] unit = data[:, 6] kilo = data[:,12] mega = data[:,18...
blackhan-software/xpower-hh
params/nft-rates/nft-rates.py
nft-rates.py
py
1,362
python
en
code
6
github-code
13
10739185005
''' Get ariana's pics in JinRiTouTiao, some problems can't be solved, weird! Try to use MongoDB, and download pics. ''' import json from urllib.parse import urlencode import requests from requests.exceptions import RequestException import pymongo import os from hashlib import md5 from multiprocessing import Pool from ...
parkerhsu/Web_Scraping
toutiao.py
toutiao.py
py
2,447
python
en
code
0
github-code
13
22803961239
import requests from bs4 import BeautifulSoup import numpy as np from scipy.stats import poisson def obtener_Liga(nombre_pais): print('Buscando equipo...') # URL de la página de resultados del equipo base_url = 'https://fbref.com/en/squads' # Realizar la solicitud GET a la página response = reques...
Juanromrod/Football-Predictions
Football_Predictions/FootballPredictionsApp/footballData.py
footballData.py
py
17,715
python
es
code
0
github-code
13
16084629172
""" Author: Missy Shi Course: math 458 Date: 04/23/2020 Project: A3 - 2 Description: Implementation of Fast Powering Algorithm Task: Compute the last five digits of the number 2 ** (10 ** 15) """ def bin_expansion(p: int) -> int: """ find binary expansions from given exponent p """ count = 0 ...
missystem/math-crypto
fastpowering.py
fastpowering.py
py
1,066
python
en
code
0
github-code
13
74599209618
# 원형 큐 디자인 # https://leetcode.com/problems/design-circular-queue/ # page.259 class MyCircularQueue: def __init__(self, k: int): self.front = 0 self.rear = 0 self.q = [None] * k self.maxlen = k def enQueue(self, value: int) -> bool: if self.q[self.rear] is None: ...
ChanYoung-dev/python
HelloWorld/2. CodingTEST/Level 1/circular-que.py
circular-que.py
py
1,396
python
en
code
0
github-code
13
20042539057
# Echo server program from pynput import keyboard from threading import Thread from threading import Event import hashlib import pyaudio import datetime import socket import time start=1 CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 RECORD_SECONDS = 4 WIDTH = 2 delimiter = "|:|:|";...
MikeLin0206/Network
NetworkProtocol/RUDP/PressToTalk/server.py
server.py
py
5,772
python
en
code
0
github-code
13
10973470469
import pandas as pd from time import time_ns import timing from tqdm import tqdm from random import shuffle # TODO: Put timing in this!!! # TODO: Use ordered list for logn times # note that neighbors for sake of this research are in-neighbors only. # 1. number of active neighboors # 2. Personal Network Exposure # ...
clcannon/CalSysUserEngagement
getFeatures.py
getFeatures.py
py
11,753
python
en
code
0
github-code
13
31930300219
#código adaptado dessa fonte: #https://github.com/ashik0007/mlpr1_iris from sklearn import naive_bayes, svm, neighbors, ensemble #import das bibliotecas numpy e pandas import numpy as np import pandas as pd # (1). df = pd.read_csv('iris.data.csv') data = np.array(df) # (2). np.random.shuffle(data) # (3). X_train ...
KevinTome/Unifesp
inteligencia_artificial/aprendizado_de_maquina_2/analise_MLP.py
analise_MLP.py
py
743
python
pt
code
0
github-code
13
6911465555
from services.pdf_service import PdfService def main(): # Example usage of the tokenization module directory = 'C:/Users/john/OneDrive/Documents/FORBIDDEN KNOWLEDGE' # Create an instance of PdfService pdf_service = PdfService(directory) # Process the PDFs using PdfService pdf_service.process_...
threewisewomen/aesirmimir
main.py
main.py
py
578
python
en
code
0
github-code
13
6922626368
''' Interviewing.io #Reference: https://interviewing.io/recordings/Java-Google-2/ ''' ''' 1st approach: Sort everything then query the 3rd element Time Complexity: O(nlogn) Can we do better? Yes. Lets try a dynamic approach, as we iterate we sort. In the end we will traverse the list only once, So time complexity has...
Oushesh/CODING_INTERVIEW
interviewing.io/GoogleEngineer_3rd_Smallest_Number.py
GoogleEngineer_3rd_Smallest_Number.py
py
2,643
python
en
code
0
github-code
13
6014520026
from PIL import ImageTk, Image import tkinter def titleBar(topF): img = ImageTk.PhotoImage(Image.open( r"C:\Users\Admin\Downloads\fol\fol\iiit.jpg").resize((400, 120), Image.ANTIALIAS)) logo = tkinter.Label(topF, bg="red", borderwidth=0, image=img, height=120, width=400) l...
soham04/Library_Management_System
student_package/topF_module.py
topF_module.py
py
367
python
en
code
0
github-code
13
18770698979
# 키패드 누르기 문제 # n: numbers 의 길이 # 시간복잡도 : O(n), 공간 복잡도 : O() # destination 과의 거리를 비교해주는 함수 def compare_distance(left_hand: int, right_hand: int, destination: int, hand: str) -> int: ly, lx = keypad[left_hand] ry, rx = keypad[right_hand] dy, dx = keypad[destination] if abs(dy - ly) + abs(dx - lx) < abs(d...
galug/2023-algorithm-study
level_1/press_keypad.py
press_keypad.py
py
1,491
python
ko
code
null
github-code
13
26454942323
def count_drop(server): dropCount = 0 numThreads = 0 for i in range(len(server)): if server[i] > 0: numThreads = numThreads + server[i] elif server[i] == -1: if numThreads > 0: print("thread less->") numThreads = numThreads - 1 ...
Eyakub/Problem-solving
HackerRank/Python/request_processing_server.py
request_processing_server.py
py
542
python
en
code
3
github-code
13
71612528338
with open('input.txt') as file: nums = [int(num) for num in file] cals = {} for i, num in enumerate(nums): diff = 2020 - num if diff in cals: print(num * nums[cals[diff]]) break cals[num] = i
FilipBudac/adventofcode
2020/01/day1.py
day1.py
py
225
python
en
code
0
github-code
13
7326516314
import base64 from io import BytesIO from django.shortcuts import render, get_object_or_404, redirect from .forms import * from .models import * from .miband4_func import get_activity_logs, sleeping, sleep_graph, colors from datetime import datetime from django.contrib import messages from django.contrib.auth import lo...
krisrrr/SIMS2_0
activity/views.py
views.py
py
6,286
python
en
code
0
github-code
13
31042809956
# databaseAccessExample.py # # Example access script for SQLite database # # More resources: # https://www.tutorialspoint.com/sqlite/sqlite_python.htm # https://www.w3schools.com/sql/ # import sqlite3 import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np import dat...
ngc1535git/UKIRT_database
queryDB_1.py
queryDB_1.py
py
6,884
python
en
code
0
github-code
13
27643795894
import csv, pickle import pandas as pd input_file = "raw_data/buchwald.csv" # input_file = "raw_data/uspto_raw_head5k.txt" # output_file = "processed_data/buchwald.csv" output_file = "processed_data/buchwald.pkl" with open(input_file, 'r') as csvfile: rows = list(csv.reader(csvfile, delimiter = ','))[1:] # with ope...
kexinhuang12345/data_process
data_process/buchwald_yield.py
buchwald_yield.py
py
1,525
python
en
code
1
github-code
13
39532118985
import statistics import numpy as np import pandas as pd from osu_analysis import BeatmapIO, ReplayIO, StdMapData, StdReplayData, StdScoreData, Gamemode from app.misc.Logger import Logger from app.misc.utils import Utils from app.misc.osu_utils import OsuUtils class ScoreNpy(): logger = Logger.get_logger(__nam...
abraker-osu/osu-play-analyzer
app/data_recording/score_npy.py
score_npy.py
py
6,923
python
en
code
2
github-code
13
33004282725
import io import time import picamera import logging import socketserver from threading import Condition from http import server from google.cloud import vision from google.cloud.vision_v1 import types from google.oauth2 import service_account # Constants credentials = service_account.Credentials.from_service_account_...
AlexandruSto/Smart_Mirror
homepage.py
homepage.py
py
5,683
python
en
code
0
github-code
13
20993682701
import json import glob # Helper function to extract individual name from filepath def remove_prefix(my_string, prefix, suffix): my_string = my_string.lstrip(prefix) my_string = my_string.rstrip(suffix) return my_string file_list = glob.glob("../PoplarVCFsAnnotated/*.filter.vcf") data = {} ...
LZhang98/snp-viewer
glob_test.py
glob_test.py
py
515
python
en
code
0
github-code
13
73282811219
import os import base64 import zipfile import logging import collections from bs4 import BeautifulSoup logger = logging.getLogger(__name__) class FB2: def __init__(self, filename): self.filename = filename self.zip_file = None self.xml = None self.metadata = None self.co...
BasioMeusPuga/Lector
lector/readers/read_fb2.py
read_fb2.py
py
5,534
python
en
code
1,479
github-code
13
9857583041
#Exercicio 4 #Faça um programa em Python que solicite ao usuário sua altura e sexo, #calcule e imprima o seu peso ideal. Utilize a seguinte convenção: #▪ Para homens: (72.7*h) – 58 #▪ Para mulheres: (62.1*h) – 44.7 alt = float(input('Digite sua altura em metros: ')) sexo = input('Digite o seu genero h/m: ') ...
Lipesti/Exercicios6
exerc4.py
exerc4.py
py
567
python
pt
code
0
github-code
13
9638945222
import requests import xml.etree.ElementTree as ET import tkinter as tk import ssl ssl._create_default_https_context = ssl._create_unverified_context def fetch_rates(event=None): selected_currency = currency_entry.get() url = "https://www.tcmb.gov.tr/kurlar/today.xml" response = requests.get(url=url) t...
unsatisfieddeveloper/currencyApi
currencyTracker.py
currencyTracker.py
py
1,195
python
en
code
0
github-code
13
27309135585
from clef.esdoc import get_doc, get_wdcc, errata, retrieve_error, citation from esdoc_fixtures import * from code_fixtures import dids6 #import pytest def test_esdoc_urls(): #dids=[] assert True def test_get_model_doc(): assert True @pytest.mark.xfail def test_get_doc(): base = 'https://api.es-doc....
coecms/clef
test/test_esdoc.py
test_esdoc.py
py
2,084
python
en
code
7
github-code
13
30784723375
# -*- coding: utf-8 -*- fichier=open("GDN_pos_filtered.txt") dico=dict() for ligne in fichier: words=ligne.split(" ") for w in words: if w not in dico: dico[w]=0 dico[w]+=1 distribution=open("distribution_gdn.txt", "w") for word in dico: distribution.write(word + " "+str(dico[w...
nicolasdugue/hackatal2019
EtudeEmbeddings/distrib.py
distrib.py
py
352
python
en
code
3
github-code
13
6148837196
import uos import settings from time import sleep_ms from machine import Pin from primitives.pushbutton import Pushbutton from homie.node import HomieNode from homie.device import HomieDevice from homie.property import HomieProperty from homie.constants import TRUE, FALSE, BOOLEAN def reset(led): import machine...
microhomie/microhomie
examples/gosund/main.py
main.py
py
1,906
python
en
code
78
github-code
13
18609597674
# -*- coding: utf-8 -*- """ Created on Mon May 31 18:20:27 2021 @author: dongting """ import os import time import socket import numpy import time """ Dynamixel Initialaztion """ # if os.name == 'nt': # import msvcrt # def getch(): # # return msvcrt.getch().decode() # return msvcrt....
DuxtX/code_equipment
python/idealab_equipment/control_dynamixel_servo.py
control_dynamixel_servo.py
py
4,900
python
en
code
0
github-code
13
39859190810
from typing import Callable, Self import flet as ft class Button(ft.ElevatedButton): def __init__(self, text: str, on_click: Callable[[Self, ft.ControlEvent], None] | None = None, visible: bool = True, disabled: bool = False): super().__...
carimatics/switch-poke-pilot
switchpokepilot/ui/button.py
button.py
py
751
python
en
code
3
github-code
13
18927276001
# we have to decide which are dark beans # and which are light beans import os import cv2 import numpy as np import pandas as pd import matplotlib.pyplot as plt # from skimage.filters import threshold_otsu from joblib import Parallel, delayed from demo_new_trial_light_end_to_end_catch import mask_for_beans_l...
srvanderplas/jellybean
Codes_Jellybean/decide_Scripts.py
decide_Scripts.py
py
2,679
python
en
code
0
github-code
13
25372728427
import psycopg2 from psycopg2 import sql from datetime import datetime def create_customers_table(): commands = ( """ CREATE TABLE IF NOT EXIST customers( id INTEGER PRIMARY KEY, first_name text, last_name text, created_at timestampz NOT NULL, ...
saromanov/postgesql-experiments
generator/generator.py
generator.py
py
1,073
python
en
code
0
github-code
13
23748743145
import os import time import datetime import logging log = logging.getLogger(__name__) import numpy as np import tensorflow as tf from brooksrfigan.generator import Unet_default from brooksrfigan.discriminator import ConvNet_default bce_loss = tf.keras.losses.BinaryCrossentropy() mae_loss = tf.keras.losses.MeanAbsol...
JakeEBrooks/BrooksRFIGAN
brooksrfigan/training.py
training.py
py
10,254
python
en
code
0
github-code
13
16809194124
from collections import namedtuple import pytest from hypothesis import settings as Settings from hypothesis.stateful import Bundle, RuleBasedStateMachine, precondition, rule from hypothesis.strategies import booleans, integers, lists Leaf = namedtuple("Leaf", ("label",)) Split = namedtuple("Split", ("left", "right"...
HypothesisWorks/hypothesis
hypothesis-python/tests/nocover/test_stateful.py
test_stateful.py
py
4,631
python
en
code
7,035
github-code
13
15021570770
""" Program to step towards cosmological analysis By creating a slightly more complicated model using real parameters, corresponding data points and performing chi squared analysis author: Rhys Seeburger """ #import relevant packages import numpy as np import matplotlib.pyplot as plt from chainconsumer import...
RhysSeeburger/2019_summer
omsig_model.py
omsig_model.py
py
5,289
python
en
code
1
github-code
13
5213747275
#coding=utf-8 #Version: python3.6.0 #Tools: Pycharm 2017.3.2 _author_ = ' Hermione' count=0 alp=0 dig=0 blank=0 oth=0 s=[] while True: a=list(input()) count+=1 s.extend(a) if len(s)+count>10: count-=1 break for i in s: if i.isalpha(): alp+=1 elif i.isdigit(): d...
Harryotter/zhedaPTApython
ZheDapython/z4/z4.14.py
z4.14.py
py
558
python
en
code
1
github-code
13
72032906258
import torch from torch.utils.data import DataLoader from pytorch_lightning.core.lightning import LightningModule from torch.optim import RMSprop from torch.optim.lr_scheduler import CosineAnnealingLR from datasets import MapDataset from models import SurfaceMapModel from models import InterMapModel from loss import...
luca-morreale/neural_surface_maps
mains/intersurface_map_train.py
intersurface_map_train.py
py
2,824
python
en
code
53
github-code
13
7042586918
from tensorflow import keras import tensorflow as tf import os import argparse import numpy as np import matplotlib.pyplot as plt from plotting import plot_pred_dots import scipy.sparse # current working directory if(os.getcwd()[-1] == '/'): cwd = os.getcwd() else: cwd = os.getcwd() + '/' MODEL_PATH = cwd + '...
C16Mftang/front-end-CNN
firing_rate.py
firing_rate.py
py
12,893
python
en
code
0
github-code
13
42014946135
#!/home/halvard/miniconda3/bin/python import pprint import subprocess import sys import os GET_RUNNING_KERNELS_SCRIPT = os.environ['HOME'] + '/bin/get_running_kernels.sh' # use -a to print all kernels, including those without GPUs args = " ".join(sys.argv[1:]) print_all = args == "-a" def get_gpu_processes(): ...
halvarsu/bin
print_jupyter_kernel_GPU_usage.py
print_jupyter_kernel_GPU_usage.py
py
2,783
python
en
code
0
github-code
13
10773390853
#!/usr/bin/env python # coding: utf-8 import requests import json import datetime import os def save_tokens(filename, tokens): with open(filename, "w") as fp: json.dump(tokens, fp) def load_tokens(filename): with open(filename) as fp: tokens = json.load(fp) return tokens def update_tok...
bibersay/Toy-project
toy_project/_6_dont_sleep/kakao_utils.py
kakao_utils.py
py
1,399
python
en
code
0
github-code
13
26192782996
import os import json from typing import Iterable from harquery.query import parse from harquery.endpoint import HeadersBase class HeadersPreset(HeadersBase): def __init__(self, workspace: 'Workspace', name: str): self._workspace = workspace self._name = name path = os.path.join( ...
evaneldemachki/harquery
harquery/preset.py
preset.py
py
4,671
python
en
code
0
github-code
13
74718330896
from abc import ABC from typing import Optional, List import marshy from marshy.types import ExternalItemType from servey.security.authorization import Authorization from servey.security.authorizer.jwt_authorizer_abc import ( JwtAuthorizerABC, date_from_jwt, ) from persisty.security.permission import Permissi...
tofarr/persisty
persisty/security/jwt_permission_authorizer_abc.py
jwt_permission_authorizer_abc.py
py
1,417
python
en
code
1
github-code
13
13578668300
"""Test runway.core.providers.aws._account.""" # pylint: disable=no-self-use from runway.core.providers.aws import AccountDetails class TestAccountDetails(object): """Test runway.core.providers.aws._account.AccountDetails.""" def test_aliases(self, runway_context): """Test aliases.""" aliases...
muni77-sh/runway
tests/unit/core/providers/aws/test_account.py
test_account.py
py
1,121
python
en
code
null
github-code
13
20049395966
import tkinter as tk from game_logic.bot import Bot from display.gameboard import Gameboard from display.player_hand import Player_hand class Menu: def __init__(self, game): """ Create the welcome window. Args: game (Game): The game to launch. """ self.game = g...
T0UT0UM/6QP
display/main.py
main.py
py
5,606
python
en
code
0
github-code
13
15703036625
import cv2 import os # Crear objeto VideoCapture cap = cv2.VideoCapture(0) # Comprobar si la cámara se abrió correctamente if not cap.isOpened(): print("Error al abrir la cámara.") exit() # Variables para contar el número de fotos tomadas y el límite de fotos a capturar contador = 0 limite_fotos = 5 ruta_gua...
NotAndeer/PythonScripts
CAMARA/cam-foto.py
cam-foto.py
py
1,009
python
es
code
0
github-code
13
11363827023
import logging, config, command, news_sender from storage import storage from aiogram import Bot, Dispatcher, executor config.init() storage.init() logging.info(f'Started bot with config: config = {config.bot_config}') def start(): bot = Bot(token=config.bot_config.token) db = Dispatcher(bot) for nam...
vitalii-honchar/hacker-bot
src/bot.py
bot.py
py
558
python
en
code
0
github-code
13
1678759199
g = open('wasteland', mode='rt', encoding='utf-8') g.read() # entire file g.seek(0) # points to the start of the file g.readline() # reads a single line g.seek(0) l = g.readlines() print(l) g.close()
alexbujenita/python-learning
files/read_files.py
read_files.py
py
201
python
en
code
0
github-code
13
8838019435
def arithmetic_arranger(problems, results=False): # Raise error if problems' length is greater than 5 if len(problems) > 5: return 'Error: Too many problems.' # Split problems on space; obatin 3 strings per problem. lines = ['', '', ''] problems_split = [] for i, el in...
lucferre/scientific_computing_with_python
arithmetic_arranger.py
arithmetic_arranger.py
py
3,578
python
en
code
0
github-code
13
29913478016
from botocore.exceptions import ClientError import boto3 import configparser import json import pandas as pd import s3fs from time import sleep def create_role(iam, role_name): print("Creating IAM role...") try: role = iam.create_role( Path='/', RoleName=role_name, ...
tommytracey/udacity_data_engineering
p3_data_warehouse_redshift/create_cluster.py
create_cluster.py
py
6,638
python
en
code
2
github-code
13
16291863980
#import the library to control the GPIO pins import RPi.GPIO as GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) #import the time library import time led_pin = 8 #setup the pin, and make it be off to start with GPIO.setup(led_pin, GPIO.OUT) #turn on the led print(True) GPIO.output(led_pin, True) #wait for 0.5 ...
mattvenn/raspi-workshop
www/flash.py
flash.py
py
404
python
en
code
2
github-code
13
25666877236
import json import platform from collections import OrderedDict, namedtuple from pathlib import Path import os import cv2 import numpy as np import torch import torch.nn as nn from PIL import Image import urllib import requests import subprocess import logging import pkg_resources as pkg def autopad(k, p=None): # ke...
skarlett992/yolo_v5_tracking
src/yolov5_utils.py
yolov5_utils.py
py
20,026
python
en
code
0
github-code
13
74564453138
#!/usr/bin/env python """ _AutoIncrementCheck_ AutoIncrement Check Test to properly set the autoIncrement value First, find the highest jobID either in wmbs_job or in wmbs_highest_job Then reset AUTO_INCREMENT to point to that. """ __all__ = [] import logging from WMCore.Database.DBFormatter import DBFormatter cl...
dmwm/WMCore
src/python/WMCore/WMBS/MySQL/Jobs/AutoIncrementCheck.py
AutoIncrementCheck.py
py
1,389
python
en
code
44
github-code
13
5323200784
import numpy as np from timeit import default_timer as timer from numba import cuda import numpy as np import math def mandel(x, y, max_iters): """ Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iteratio...
CJRockball/Mandelbrot
mandel_calc.py
mandel_calc.py
py
2,600
python
en
code
0
github-code
13
652639867
import sys import matplotlib.pyplot as plt import numpy as np sys.path.insert(1, '../') from pmt_he_study.models import * from ReadRED import sndisplay as sn tdc2ns = 0.390625 adc2mv = 0.610352 def get_template(): template = [] with open("/Users/williamquinn/Desktop/commissioning/template_1_0_1_run_104.csv...
SuperNEMO-DBD/PMT-ShapeAnalysis
commissioning/pmt_shape_analysis.py
pmt_shape_analysis.py
py
8,720
python
en
code
0
github-code
13
31741782145
# encoding: utf-8 """ @author: nanjixiong @time: 2020/6/28 22:07 @file: example04.py @desc: """ import numpy world_alcohol = numpy.genfromtxt("./world_alcohol.txt", delimiter=',', dtype=str, skip_header=1) print(world_alcohol) uruguay_other_1986 = world_alcohol[1, 4] print(uruguay_other_1986) third_country = world_al...
lixixi89055465/py_stu
tangyudi/base/numpy/example04.py
example04.py
py
827
python
en
code
1
github-code
13
72987579857
# -*- coding: utf-8 -*- # @author: Darren Vong import urllib import urllib2 import json from bs4 import BeautifulSoup from utils import find_recursive_dict_key AGENT_NAME = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0" headers = {"User-Agent": AGENT_NAME} def get_num_links(soup): r...
frazerbw/wikitrumps
server/page_data_extractor.py
page_data_extractor.py
py
3,055
python
en
code
0
github-code
13