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
7161765994
from typing import List class Solution: def calculate(self, nums, k, max_len, s, nums_len): if nums[s:] == []: print("max_len=",max_len) return max_len else: i = 0 temp = k ans = [] temp_nums = nums[s:] print("nums...
CompetitiveCodingLeetcode/LeetcodeEasy
JuneLeetcodeChallenge/MaxConsecutiveOnesIII.py
MaxConsecutiveOnesIII.py
py
1,280
python
en
code
0
github-code
6
22095502736
from django.urls import path from user import views urlpatterns = [ path('fun',views.fun), path('fun1',views.fun1), path('u',views.us, name='uuu'), path('user',views.user, name='aaaa'), ]
anshifmhd/demo
user/urls.py
urls.py
py
205
python
en
code
0
github-code
6
37895365689
# Python Number Guessing Game import random game_over = False # To check if out of guesses. guesses = 0 # Set value for guesses def play_again(): """Function to reset game""" global game_over if again == 'y': game_over = False def check_num(): """Function to check if guess is correct, if...
agentc13/number-guessing-project
main.py
main.py
py
1,530
python
en
code
0
github-code
6
14565939884
# Input: s and t : strings # Output: bool # Input: s = "anagram", t = "nagaram" # Output: true # QED def is_anagram(s: str, t: str) -> bool: return sorted(s) == sorted(t) # Input: s and t: str # Output: true or false: bool # We'll frequency count # Loop through strings s and t, then store the chars # and freqs ...
HemlockBane/ds_and_algo
strings/study_questions.py
study_questions.py
py
2,921
python
en
code
0
github-code
6
29214262320
import os.path import unittest from pathlib import Path from sflkit.analysis.analysis_type import AnalysisType from sflkit.analysis.spectra import Spectrum from sflkit.analysis.suggestion import Location from tests4py import framework from tests4py.constants import DEFAULT_WORK_DIR from utils import BaseTest class ...
smythi93/Tests4Py
tests/test_sfl.py
test_sfl.py
py
3,851
python
en
code
8
github-code
6
22175885434
# Author:Zhang Yuan from MyPackage import * import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.patches as patches import seaborn as sns import statsmodels.api as sm from scipy import stats # ------------------------------------------------------------ __mypath__ = MyPath.MyClass_P...
MuSaCN/PythonProjects2023-02-14
Project_Papers文章调试/4.如何在MQL5中使用ONNX模型.py
4.如何在MQL5中使用ONNX模型.py
py
14,235
python
zh
code
1
github-code
6
5384270592
from Chem_Equation_Balancer import * from EmpiricalFormulas import * from Number_Validation import * def Chapter4_Menu(): #Submenu for Chaper 4 print ("\nChapter 4 Menu:\n") while True: print ("Enter 0 to find total mass of a compound") print ("Enter 1 to test whether an equation is balanced") ...
NightHydra/HonChemCalc
Chapter_1_4_Menu.py
Chapter_1_4_Menu.py
py
3,255
python
en
code
0
github-code
6
43213705575
#!/usr/bin/env python3 """ Program to decode the first sprite of a CTHG 2 file. Mainly intended as a test for the checking the encoder, but also a demonstration of how to decode. """ _license = """ Copyright (c) 2013 Alberth "Alberth" Hofkamp Permission is hereby granted, free of charge, to any person obtaining a cop...
CorsixTH/CorsixTH
SpriteEncoder/decode.py
decode.py
py
5,314
python
en
code
2,834
github-code
6
5216056710
"""Pure Python implementation of EM algorithm.""" from array import array import random class Cluster: """Implementation of EM clustering.""" def __init__(self, filename, dim, num_entry, num_cluster=10): self.float_size = 4 self.dim = dim self.num_entry = num_entry self.data = ...
uniglot/pure-python-em
clustering.py
clustering.py
py
3,163
python
en
code
0
github-code
6
23950521358
#!/usr/bin/python3 import argparse from iCEburn.libiceblink import ICE40Board def rtype(x): return ('R', int(x, 16)) def wtype(x): return ('W', [int(i,16) for i in x.split(':')]) def main(): ap = argparse.ArgumentParser() ap.add_argument("-r", "--read", dest='actions', type=rtype, action='append') ...
davidcarne/iceBurn
iCEburn/regtool.py
regtool.py
py
868
python
en
code
32
github-code
6
21812044102
import pytest from src.error import InputError from src.auth import auth_register_v2 from src.user import user_profile_v2 from src.other import clear_v1 @pytest.fixture def register_user(): clear_v1() user = auth_register_v2("johnsmith@gmail.com", "123456", "john", "smith") token = user['token'] id = u...
TanitPan/comp1531_UNSW_Dreams
tests/user_profile_test.py
user_profile_test.py
py
857
python
en
code
0
github-code
6
39252790870
import time import logging from django.contrib import admin from django.contrib import messages from django.contrib.admin import helpers from django.urls import reverse from django.db import transaction from django.db.models import Count from django.template.response import TemplateResponse from django.utils.html impo...
mangaki/mangaki
mangaki/mangaki/admin.py
admin.py
py
28,860
python
en
code
137
github-code
6
70063460029
MAX_QSIZE = 10 class CircularQueue : def __init__( self ) : self.front = 0 self.rear = 0 self.items = [None] * MAX_QSIZE def isEmpty( self ) : return self.front == self.rear def isFull( self ) : return self.front == (self.rear+1)%MAX_QSIZE def clear( se...
kimmoonwoong/Data-Structures-using-python
실습과제7.py
실습과제7.py
py
5,896
python
en
code
0
github-code
6
38591123500
class Item: owners = [] def __init__(self, name, quantity, price, owners): self.name = name self.quantity = quantity self.price = price self.owners = owners # Define the parts of a basic restaurant check class Check: def __init__(self, items): self.title = ""...
curtis-marten/check-split
src/check.py
check.py
py
838
python
en
code
0
github-code
6
72005748348
lista = [] try: #assert False # lista[0] a = 1 / 0 #except: <-- łap wszystkie błędy - zła praktyka #except Exception: --//-- except ZeroDivisionError: print("Dzielono przez zero, ale idziemy dalej") a = 0 except IndexError as e: print("Pojwił się błąd indeksowania:", e) a = None else: # ki...
jakubnowicki/python-prog
wyjatki.py
wyjatki.py
py
1,528
python
pl
code
0
github-code
6
40458088335
# general imports for EMISSOR and the BRAIN from cltl import brain from emissor.representation.scenario import ImageSignal # specific imports from datetime import datetime import time import cv2 import pathlib import emissor_api #### The next utils are needed for the interaction and creating triples and capsules impo...
leolani/cltl-chatbots
src/chatbots/bots/episodic_image_memory.py
episodic_image_memory.py
py
5,114
python
en
code
0
github-code
6
8926064474
import pandas as pd from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time import requests import shutil import os.path import docx2txt from webdriver_manager.chrome import ChromeDriverManager from datetime import datetime from selenium.webdriver.support.ui import We...
priyankathakur6321/WebScraping-Automation
ctcfp/main.py
main.py
py
5,904
python
en
code
0
github-code
6
32058216442
import sys input = sys.stdin.readline n = int(input()) sell = {} for i in range(n): name = input() if name not in sell: sell[name] = 1 else: sell[name] += 1 max_value = max(sell.values()) best = [] for key, value in sell.items(): if value == max_value: ...
doll2gom/Algorithm
백준/Silver/1302. 베스트셀러/베스트셀러.py
베스트셀러.py
py
378
python
en
code
0
github-code
6
27592910479
import numpy as np from collaborativefiltering import top_users, b2 from cfub import cfub from cfib import recommend_similar_books from new import new_user # Initialisation de l'utilisateur def run(): print("(paramètre de requête API) : ID utilisateur, ou 'NEW' pour un nouvel utilisateur.") print("Liste d'I...
Thuy9906/bookreco
test.py
test.py
py
1,028
python
fr
code
0
github-code
6
37600184033
import torch from safetensors.torch import save_file import argparse from pathlib import Path def main(args): input_path = Path(args.input_path).resolve() output_path = args.output_path overwrite = args.overwrite if input_path.suffix == ".safetensors": raise ValueError( f"{input_p...
p1atdev/sd_ti_merge
to_safetensors.py
to_safetensors.py
py
1,560
python
en
code
0
github-code
6
10233643835
from typing import List, Optional from twitchio import PartialUser, Client, Channel, CustomReward, parse_timestamp __all__ = ( "PoolError", "PoolFull", "PubSubMessage", "PubSubBitsMessage", "PubSubBitsBadgeMessage", "PubSubChatMessage", "PubSubBadgeEntitlement", "PubSubChannelPointsMe...
PythonistaGuild/TwitchIO
twitchio/ext/pubsub/models.py
models.py
py
15,690
python
en
code
714
github-code
6
20538355959
# https://leetcode.com/problems/trim-a-binary-search-tree/ """ Time complexity:- O(N) Space Complexity:- O(H) H = height of BST (call stack ) """ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.ri...
Amit258012/100daysofcode
Day49/trim_a_bst.py
trim_a_bst.py
py
1,165
python
en
code
0
github-code
6
25503087204
from django.shortcuts import render, redirect from django.urls import reverse from django.contrib.auth.decorators import login_required from .models import ListingComment, Listing, Bid, Category from .forms import CreateListingForm import os import boto3 def home(request): listings = Listing.objects.filter(is_ac...
samyarsworld/social-network
auction/views.py
views.py
py
5,652
python
en
code
0
github-code
6
35416294037
import rdflib from rdflib import Graph from scipy.special import comb, perm from itertools import combinations g = Graph() g.parse(r'/Users/shenghua/Desktop/ontology/ontology.owl') deleted_str=r"http://www.semanticweb.org/zhou/ontologies/2020/3/untitled-ontology-19#" len_deleted_st=len(deleted_str) query = """ SE...
0AnonymousSite0/Data-and-Codes-for-Integrating-Computer-Vision-and-Traffic-Modelling
3. Shared codes/Codes for SPARQL query in the CV-TM ontology/Query of CV-TM Ontology.py
Query of CV-TM Ontology.py
py
5,900
python
en
code
4
github-code
6
36025283136
from ..Model import BootQModel from Agent import Agent import random from chainer import cuda try: import cupy except: pass import numpy as np import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) class BootQAgent(Agent): """ Deep Exploration via Bootstrapped DQN Args: ...
ppaanngggg/DeepRL
DeepRL/Agent/BootQAgent.py
BootQAgent.py
py
7,856
python
en
code
29
github-code
6
8649575468
# 2839 : 설탕 배달 *** 해결 x while True : n = int(input("킬로그램 수 : ")) k5 = int(n / 5) k3 = int((n - 5*k5) / 3) if n % 5 == 0 : print(n / 5) elif (3*k3 + 5*k5) == n : print(k3 + k5) elif (3*k3 + 5*k5) != n : if k5 <= 2 : if (n-5*(k5-1)) % 3 == 0 : print( (n-5*(k5-1)) / 3 + k5-1) ...
kimhn0605/BOJ
fail/2839.py
2839.py
py
729
python
ko
code
0
github-code
6
10711040761
import tensorflow as tf from tensorflow import keras import numpy as np import os import sys sys.path.append(os.getcwd()) from utils.prepareReviewDataset import intToWord, return_processed_data_and_labels def decode_review(text): return " ".join([intToWord.get(i, "?") for i in text]) train_data, train_labels, test_d...
tung2389/Deep-Learning-projects
Text Classification/trainModel.py
trainModel.py
py
1,347
python
en
code
0
github-code
6
40080606131
import os import connexion from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow from flask_bcrypt import Bcrypt basedir = os.path.abspath(os.path.dirname(__file__)) # Create the Connexion application instance connex_app = connexion.App(__name__, specification_dir=...
tuvetula/ApiRestFlask_videos
config.py
config.py
py
950
python
en
code
0
github-code
6
41543430774
import re import sys from .ply import lex from .ply.lex import TOKEN class CLexer(object): """ A lexer for the C- language. After building it, set the input text with input(), and call token() to get new tokens. The public attribute filename can be set to an initial filaneme, but ...
ricoms/mips
compiladorCminus/pycminus/c_lexer.py
c_lexer.py
py
4,426
python
en
code
0
github-code
6
24370177566
import unittest class TestImageGen(unittest.TestCase): def test_image_gen(self): from src.dataio import GridIO, FlowIO from src.create_particles import Particle, LaserSheet, CreateParticles from src.ccd_projection import CCDProjection from src.intensity import Intensity fro...
kalagotla/syPIV
test/test_image_gen.py
test_image_gen.py
py
3,247
python
en
code
0
github-code
6
40029073689
from_path = "D:/PasaOpasen.github.io/images/Миша Светлов/вторая съемка/отбор2" to_path = "D:/PasaOpasen.github.io/images/Миша Светлов/вторая съемка/отбор2ориги" where = "C:/Users/qtckp/YandexDisk/Загрузки/ДИМА" import glob import os import shutil files = [ os.path.splitext(os.path.basename(file))[0] + '.cr2' for ...
PasaOpasen/PasaOpasen.github.io
images/Миша Светлов/вторая съемка/migrate.py
migrate.py
py
551
python
en
code
2
github-code
6
24046293426
# Autor: João PauLo Falcão # Github: https://github.com/jplfalcao # Data de criação: 09/10/2023 # Data de modificação: # Versão: 1.0 # Importando a biblioteca import yt_dlp # Endereço do vídeo a ser baixado url = input("Digite a url do vídeo: ") # Especificando o formato '.mp4' para o vídeo ydl_opts = { 'format...
jplfalcao/python
youtube_video_download/ytvd.py
ytvd.py
py
532
python
pt
code
0
github-code
6
21763755802
# Approach 1: Coloring by Depth-First Search # Time: O(N + E), N = no. of node_idxs, E = no. of edges # Space: O(N) class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: color = {} for node_idx in range(len(graph)): if node_idx not in color: stack = [n...
jimit105/leetcode-submissions
problems/is_graph_bipartite?/solution.py
solution.py
py
785
python
en
code
0
github-code
6
22340672031
#!/usr/bin/env python def read_input(): with open('./inputs/day04') as f: return [l.strip() for l in f.readlines()] def _to_range(pair): return range(int(pair[0]), int(pair[1]) + 1) def get_pairs(): for line in read_input(): yield ( set(_to_range(p.split('-'))) fo...
denkl/advent-of-code
day04.py
day04.py
py
685
python
en
code
1
github-code
6
30311558976
# -*- coding: utf-8 -*- from __future__ import print_function from os import sep from os.path import dirname, normpath from pickle import HIGHEST_PROTOCOL #------------------------------------------------------------------------- # Paths #------------------------------------------------------------------------- PROGRA...
bmcage/centrifuge-1d
centrifuge1d/const.py
const.py
py
1,505
python
en
code
0
github-code
6
45517639514
company_motto = "Copeland's Corporate Company helps you capably cope with the constant cacophony of daily life" # Find the second to last character in company_motto. second_to_last = company_motto[-2:-1] print(second_to_last) # f # create a slice of the last 4 characters in company_motto. final_word = company_mott...
candytale55/working-with-strings
working_with_strings_all.py
working_with_strings_all.py
py
2,505
python
en
code
0
github-code
6
10699368918
# -*- coding:utf-8 -*- import cv2 import os from glob import glob import numpy as np import shutil '''处理原图片得到人物脸部图片并按比例分配train和test用于训练模型''' SRC = "Raw" # 待处理的文件路径 DST = "data2" # 处理后的文件路径 TRAIN_PER = 5 # train的图片比例 TEST_PER = 1 # test的图片比例 def rename_file(path, new_name="", start_num=0, file_type=""): if n...
mikufanliu/AnimeCharacterRecognition
get_faces.py
get_faces.py
py
5,231
python
en
code
4
github-code
6
6814941665
from urllib.request import urlopen from pdfminer.high_level import extract_text def pdf_to_text(data): with urlopen(data) as wFile: text = extract_text(wFile) return text docUrl = 'https://diavgeia.gov.gr/doc/ΩΕΚ64653ΠΓ-2ΞΡ' print(pdf_to_text(docUrl))
IsVeneti/greek-gov-nlp
Preprocessing/ConvertPdf.py
ConvertPdf.py
py
280
python
en
code
1
github-code
6
70159895227
__all__ = [ 'points_to_morton', 'morton_to_points', 'points_to_corners', 'coords_to_trilinear', 'unbatched_points_to_octree', 'quantize_points' ] import torch from kaolin import _C def quantize_points(x, level): r"""Quantize :math:`[-1, 1]` float coordinates in to :math:`[0, (2^{level...
silence394/GraphicsSamples
Nvida Samples/kaolin/kaolin/ops/spc/points.py
points.py
py
5,820
python
en
code
0
github-code
6
30099457858
from unittest.mock import Mock from .imapclient_test import IMAPClientTest class TestFolderStatus(IMAPClientTest): def test_basic(self): self.client._imap.status.return_value = ( "OK", [b"foo (MESSAGES 3 RECENT 0 UIDNEXT 4 UIDVALIDITY 1435636895 UNSEEN 0)"], ) out...
mjs/imapclient
tests/test_folder_status.py
test_folder_status.py
py
1,969
python
en
code
466
github-code
6
18020255074
import random,argparse,sys parser = argparse.ArgumentParser() import numpy as np class PlannerEncoder: def __init__(self, opponent, p,q) -> None: self.p = p; self.q = q self.idx_to_states = {} self.opp_action_probs = {} with open(opponent,'r') as file: i = 0 ...
kiluazen/ReinforcementLearning
Policy Iteration/encoder.py
encoder.py
py
10,197
python
en
code
0
github-code
6
37686992982
import socket import random server_address = ('127.0.0.1', 5001) server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(server_address) while True: data, client_address = server_socket.recvfrom(1024) if random...
studiawan/network-programming
bab07/server-udp2.py
server-udp2.py
py
549
python
en
code
10
github-code
6
25145650810
import pytest import datetime import pytz from mixer.backend.django import mixer from telegram_message_api.helpers import ( ParsedData, ParseText, CategoryData, ) @pytest.mark.parametrize( 'text', [ '150 test', '150 test 150', '150', ] ) def test_parsetext_dataclass(text): ""...
enamsaraev/telegram_bot_api
telegram_message_api/tests/test_helpers.py
test_helpers.py
py
1,071
python
en
code
0
github-code
6
30455799471
import pandas as pd import tensorflow as tf import argparse from . import data TRAIN_URL = data.TRAIN_URL TEST_URL = data.TEST_URL CSV_COLUMN_NAMES = data.CSV_COLUMN_NAMES LABELS = data.LABELS def maybe_download(): train_path = tf.keras.utils.get_file(TRAIN_URL.split('/')[-1], TRAIN_URL) test_path = tf.ker...
RajithaKumara/Best-Fit-Job-ML
classifier/estimator/model.py
model.py
py
3,077
python
en
code
1
github-code
6
858848514
from __future__ import division from HTMLParser import HTMLParser import os import re from .https_if_available import build_opener re_url = re.compile(r'^(([a-zA-Z_-]+)://([^/]+))(/.*)?$') def resolve_link(link, url): m = re_url.match(link) if m is not None: if not m.group(4): # http://...
VisTrails/VisTrails
vistrails/packages/URL/http_directory.py
http_directory.py
py
6,294
python
en
code
100
github-code
6
5432720139
from sklearn.metrics import pairwise_distances import numpy as np import pandas as pd from scipy.sparse import spmatrix from anndata import AnnData from scipy.stats import rankdata from typing import Optional from . import logger from .symbols import NOVEL, REMAIN, UNASSIGN class Distance(): """ Class that dea...
Teichlab/cellhint
cellhint/distance.py
distance.py
py
26,272
python
en
code
4
github-code
6
709779467
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import string import pandas as pd from gensim.models import KeyedVectors import time from sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS #x=find_department('Mortage requirements specified are incorrect', False) def find_department(single_query,only_depar...
ankitd3/Assist-ANS
NLP/distance.py
distance.py
py
6,026
python
en
code
1
github-code
6
74059033149
#coding:utf-8 class Fiab(object): def __init__(self, num): self.num = num self.a = 0 self.b = 1 self.n = 0 def __iter__(self): return self def __next__(self): self.a, self.b = self.b, self.a + self.b self.n += 1 if self.n > self.num: ...
HarveyWang81/PythonScript
Study-01/fibs/by_iter.py
by_iter.py
py
497
python
en
code
0
github-code
6
18718175573
from django.shortcuts import render, HttpResponse, redirect from .models import Note from django.urls import reverse # Create your views here. def index(request): context = { "notes": Note.objects.all(), } return render(request, 'notes/index.html', context) def create(request): if request.me...
mtjhartley/codingdojo
dojoassignments/python/django/full_stack_django/ajax_notes/apps/notes/views.py
views.py
py
846
python
en
code
1
github-code
6
42924345016
import sys import os import time import re import csv import cv2 import tensorflow as tf import numpy as np #import pandas as pd from PIL import Image from matplotlib import pyplot as plt from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as vis_util # if len(sys.a...
ppalantir/axjingWorks
AcademicAN/TwoStage/test_batch.py
test_batch.py
py
5,072
python
en
code
1
github-code
6
31525994513
# _*_ coding: utf-8 _*_ __author__ = 'Steven' __date__ = '2017/8/21 21:47' import xadmin from .models import BugetItem class BugetItemAdmin(object): list_display = ["custom_id", "buget_type", "name", "desc", "standard", "edit_dept", "approve_dept", "account_item", "add_user", "add_time"] ...
stevenlu77/HOMS
apps/buget/adminx.py
adminx.py
py
682
python
en
code
0
github-code
6
8768680597
dict1 = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 } dict2 = { 'a': 1, 'b': 2, 'g': 33, 'h': 44, 'e': 55 } output = "" for key1 in dict1.keys(): for key2 in dict2.keys(): if key2 == key1: output += key1 + " " print(output.rstrip())
barelyturner/hometask5
hometask5.1/main.py
main.py
py
298
python
en
code
0
github-code
6
25178584436
from summarize import * from rbm_dae.deepAE import * import rouge def summarize_sentence_vectors(df, vector_set): """ Function applying the summarization function to get the ranked sentences. Parameters: df: dataframe containing the data to summarize vector_set: the column name of the ve...
MikaelTornwall/dd2424_project
evaluate.py
evaluate.py
py
15,618
python
en
code
1
github-code
6
9093463058
def load_data(file): with open(file) as f: data = f.readlines() data = [line.strip() for line in data] # убираем переносы строк data = [x.rsplit() for x in data] # разбиваем линию на команду и шаг data = [(x[0], int(x[1])) for x in data] # приводим элементы к кортежам retu...
lapssh/advent_of_code
2021/day02/02-position.py
02-position.py
py
1,569
python
en
code
0
github-code
6
73968831228
"""Analyzes the MCTS explanations output by run_mcts.py in terms of stress and context entropy.""" import pickle from pathlib import Path import matplotlib.pyplot as plt import numpy as np from scipy.stats import wilcoxon def analyze_mcts_explanations(explanations_path: Path, save_dir: ...
swansonk14/MCTS_Interpretability
analyze_mcts_explanations.py
analyze_mcts_explanations.py
py
6,053
python
en
code
3
github-code
6
40876617434
"""All formatters from this pacakge should be easily mixed whith default ones using this pattern: >>> from code_formatter.base import formatters >>> from code_formatter import extras >>> custom_formatters = formatters.copy() >>> custom_formatters.register(extras.UnbreakableTupleFormatter, ...
paluh/code-formatter
code_formatter/extras/__init__.py
__init__.py
py
12,919
python
en
code
8
github-code
6
17519855782
""" Example of custom metric script. The custom metric script must contain the definition of custom_metric_function and a main function that reads the two csv files with pandas and evaluate the custom metric. """ import numpy as np def CAPE_CNR_function(dataframe_y_true, dataframe_y_pred): """ CAPE (Cumulated Ab...
gaspardbb/astreos
CAPE_CNR_metric.py
CAPE_CNR_metric.py
py
1,479
python
en
code
2
github-code
6
30546132474
# %% import matplotlib.pyplot as plt import networkx as nx import pandas as pd import seaborn as sns from src import consts as const from src.processing import attribute_builder as ab from src.processing import plotting, refactor sns.set(palette="Set2") # Output Configurations pd.set_option('display.max_rows', 60) ...
ajmcastro/flight-time-prediction
src/processing/eda.py
eda.py
py
5,177
python
en
code
1
github-code
6
43200145217
"""empty message Revision ID: 5b1f1d56cb45 Revises: 934b5daacc67 Create Date: 2019-06-03 19:02:22.711720 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '5b1f1d56cb45' down_revision = '934b5daacc67' branch_labels = None...
tgalvinjr/blog-ip
migrations/versions/5b1f1d56cb45_.py
5b1f1d56cb45_.py
py
830
python
en
code
0
github-code
6
3642648813
class CommentStringParser(): def __init__(self,verbose=True): self.verbose = verbose self.special_cases = [['"', '"', 'strings'], ["'", "'", 'strings'], ["//", "\n", 'comments'], ["/*", "*/", 'comments']] ...
matisyo/vulnerability_detection
Notebooks/utils/code_helpers.py
code_helpers.py
py
1,500
python
en
code
0
github-code
6
33628818675
# -*- coding: utf-8 -*- """ Created by Safa Arıman on 12.12.2018 """ import base64 import json import urllib.request, urllib.parse, urllib.error import urllib.request, urllib.error, urllib.parse import urllib.parse from ulauncher.api.client.EventListener import EventListener from ulauncher.api.shared.action.DoNothingAc...
safaariman/ulauncher-jira
jira/listeners/extension_keyword.py
extension_keyword.py
py
3,484
python
en
code
10
github-code
6
72536666107
from dataclasses import asdict, dataclass from functools import cached_property from time import sleep from typing import Any, Dict, List, Optional, Union from airflow import AirflowException from airflow.models.taskinstance import Context from airflow.providers.http.hooks.http import HttpHook from constants import CR...
ksh24865/cryptocurrency-data-pipeline
Airflow/dags/operators/cryptocurrency/price/sourcing_stream.py
sourcing_stream.py
py
4,859
python
en
code
0
github-code
6
34958665792
# -*- coding: utf-8 -*- import numpy as np import os import time import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torchvision.transforms as trn import torchvision.datasets as dset import torch.nn.functional as F import json from attack_methods import pgd from models.wrn import WideResNet f...
arthur-qiu/adv_vis
cifar10_wrn_at.py
cifar10_wrn_at.py
py
10,072
python
en
code
0
github-code
6
8929962174
nums = [1,2,3,4,5,6,7,8,9,10] #Print the even numbers even_numbers = list(filter(lambda x: x % 2 == 0, nums)) print(even_numbers) #Print the odd numbers odd_numbers = list(filter(lambda x: x % 2 != 0, nums)) print(odd_numbers) names = ['Adam', 'Ana', 'Kevin', 'Daniel', 'Michael'] #Filter the names that have more th...
moreirafelipegbt/udemy-python
s17/s17-138.py
s17-138.py
py
434
python
en
code
0
github-code
6
39760240581
# -*- coding: utf-8 -*- from django.conf.urls import patterns, include, url urlpatterns = patterns('CiscoDxUketsukeApp.views', # url(r'^$', 'CiscoDxUketsuke.views.home', name='home'), # url(r'^getData/' 'CiscoDxUketsuke.views.getData'), url(r'^member_tsv/$','member_tsv'), url(r'^member_json/$','member...
fjunya/dxApp
src/CiscoDxUketsukeApp/urls.py
urls.py
py
1,254
python
en
code
0
github-code
6
21738440212
import cv2 # Problem 4. # Rescale the video vid1.jpg by 0.5 and display the original video and the rescaled one in separate windows. def rescaleFrame(frame, scale): width = int(frame.shape[1] * scale) height = int(frame.shape[0] * scale) dimensions = (width, height) return cv2.resize(frame, dimension...
markhamazaspyan/Python_2_ASDS
opencvHW1/problem4.py
problem4.py
py
799
python
en
code
0
github-code
6
28965388899
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from seleni...
krzysztofzajaczkowski/newdemy
utils/WebCrawler/main.py
main.py
py
5,352
python
en
code
0
github-code
6
73813844989
import io import numpy as np import sys from gym.envs.toy_test import discrete from copy import deepcopy as dc UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 class GridworldEnv(discrete.DiscreteEnv): metadata = {'render.modes': ['human', 'ansi']} def __init__(self, shape = [4, 4]): if not isinstance(shape, (li...
hyeonahkimm/RLfrombasic
src/common/gridworld.py
gridworld.py
py
2,222
python
en
code
0
github-code
6
4206104345
# pylint: disable=no-member, no-name-in-module, import-error from __future__ import absolute_import import glob import distutils.command.sdist import distutils.log import subprocess from setuptools import Command, setup import setuptools.command.sdist # Patch setuptools' sdist behaviour with distutils' sdist behaviou...
jbarlow-mcafee/opendxl-misc
setup.py
setup.py
py
1,654
python
en
code
0
github-code
6
21998859226
from typing import List class Solution: def deleteAndEarn(self, nums: List[int]) -> int: max_val = max(nums) total = [0] * (max_val + 1) for val in nums: total[val] += val def rob(nums): first = nums[0] second = max(nums[0], nums[1]) ...
hangwudy/leetcode
700-799/740. 删除并获得点数.py
740. 删除并获得点数.py
py
475
python
en
code
0
github-code
6
17654474137
import string import os import csv from datetime import datetime from datetime import date import re #debugging debug = False print() def extract(inputFile: string, outputFile: string): specialTitle = False fileIndex = 1 with open(outputFile,'w',newline='', encoding="utf8") as writefile,...
ABbuff/DumpstateDataExtraction
Extract.py
Extract.py
py
22,516
python
en
code
0
github-code
6
26257812486
# Imports import sqlalchemy as sa from sqlalchemy.ext.declarative import declarative_base import users from datetime import datetime """ Модуль для поиска атлетов по парамтрам пользователя """ # Variables Base = declarative_base() # Class definitions class Athlette(Base): __tablename__ = "Athelete" id = sa....
vsixtynine/sf-sql-task
find_athlete.py
find_athlete.py
py
3,609
python
ru
code
0
github-code
6
9324466807
from flask import Blueprint, render_template, url_for lonely = Blueprint('lonely', __name__, template_folder='./', static_folder='./', static_url_path='/') lonely.display_name = 'Lonely' lonely.published = True lonely.description = "An interac...
connerxyz/exhibits
cxyz/exhibits/lonely/lonely.py
lonely.py
py
437
python
en
code
0
github-code
6
21881174301
from selenium import webdriver from selenium.webdriver.common.by import By import time import os try: link = "http://suninjuly.github.io/file_input.html" browser = webdriver.Chrome() browser.get(link) elements = browser.find_elements(By.CSS_SELECTOR, ".form-control") for element in elements:...
Mayurityan/stepik_auto_tests_course
lesson 2.2 send file form.py
lesson 2.2 send file form.py
py
1,034
python
ru
code
0
github-code
6
11951082453
def convert_ascii(letter): result = ord(letter) return result def convert_binary(num): result = bin(num) return result def menu(): print("=============\nMenu\n=============\n 1. Character\n 2. Word") option = int(input("Please select an option to convert into binary: ")) if option ==...
Juanjo2354/EvaluacionFinal
convertBinary.py
convertBinary.py
py
1,250
python
en
code
0
github-code
6
70713803708
import re import os import sys import nltk import json import wandb import joblib import datasets import numpy as np import pandas as pd from time import process_time from nltk import word_tokenize from nltk.stem import WordNetLemmatizer from sklearn.svm import LinearSVC from sklearn.pipeline import make_pipeline from ...
JesseBrons/Webpageclassification
training/train_model_SVM.py
train_model_SVM.py
py
3,173
python
en
code
1
github-code
6
27483903677
from django.shortcuts import render, redirect from django.contrib import messages from .models import User from .forms import RegisterForm, LoginForm from .utils import require_login def login_page(request): context = {"reg_form": RegisterForm(), "login_form": LoginForm()} return render(request, "users/login.html", ...
madjaqk/django_user_dashboard
apps/users/views.py
views.py
py
2,061
python
en
code
0
github-code
6
35164165716
#!/usr/bin/python3 import subprocess import json import requests import time import logging import os #bin Paths ipfspath = '/usr/local/bin/ipfs' wgetpath = '/usr/bin/wget' wcpath = '/usr/bin/wc' #Basic logging to ipfspodcastnode.log logging.basicConfig(format="%(asctime)s : %(message)s", datefmt="%Y-%m-%d %H:%M:%S",...
Cameron-IPFSPodcasting/podcastnode-Umbrel
ipfspodcastnode.py
ipfspodcastnode.py
py
6,566
python
en
code
4
github-code
6
33729704432
from flask_app import app, db, render_template, request, redirect, bcrypt, session, flash, url_for, EMAIL_REGEX, verify_logged_in, datetime, timedelta from models import User, Movie, Post, Comment, favorites, post_likes, comment_likes, faved @app.route('/') def index(): upms = db.session.query(User, Post, Movie)....
cmderobertis/ReDirector
flask_app/controllers/users.py
users.py
py
3,467
python
en
code
0
github-code
6
3508455471
#!/usr/bin/env python3 import numpy as np import operator if __name__ == "__main__": log = None for l in open('3-input'): *l, = map(int, l.strip()) if log is None: log = np.ndarray((1, len(l)), dtype=int) log[0] = l else: log = np.vstack([log, l]) ...
pboettch/advent-of-code
2021/3.py
3.py
py
1,069
python
en
code
1
github-code
6
30367917171
"""Tutorial 8. Putting two plots on the screen This tutorial sets up for showing how Chaco allows easily opening multiple views into a single dataspace, which is demonstrated in later tutorials. """ from scipy import arange from scipy.special import jn from enable.api import ComponentEditor from traits.api import Ha...
enthought/chaco
examples/tutorials/tutorial8.py
tutorial8.py
py
1,873
python
en
code
286
github-code
6
42937022866
import datetime import sqlite3 import os import sys from PyQt6.QtWidgets import * from PyQt6.QtCore import Qt from docxtpl import DocxTemplate class mailbackGenWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Test Mailback Letter Generator") self.setFixedSiz...
Centari2013/PublicMailbackGeneratorTest
main.py
main.py
py
8,527
python
en
code
0
github-code
6
41958018958
from waterworld.waterworld import env as custom_waterworld from potential_field.potential_field_policy import PotentialFieldPolicy from utils import get_frames from pettingzoo.utils import average_total_reward from multiprocessing import Pool, cpu_count import tqdm import numpy as np from matplotlib import pyplot as...
ezxzeng/syde750_waterworld
test_policy.py
test_policy.py
py
4,604
python
en
code
0
github-code
6
32840040688
from scipy.sparse import csr_matrix from .text import WordPieceParser from collections.abc import Mapping, Iterable class RecordVectorMap(Mapping): def __init__(self, records, wp_model_path, vec_format='bag-of-words'): text_parser = WordPieceParser(wp_model_path) self.rec_seq_map, self.reco...
rmhsiao/CAGNIR
utils/data/record.py
record.py
py
2,182
python
en
code
1
github-code
6
24200508437
# #!/bin/python # # -*- coding: utf8 -*- # import sys # import os # import re #请完成下面这个函数,实现题目要求的功能 #当然,你也可以不按照下面这个模板来作答,完全按照自己的想法来 ^-^ #******************************开始写代码****************************** def pathInZigZagTree(label): """ Args: label: int Return: list[int] """ l...
AiZhanghan/Leetcode
秋招/小米/1/1.py
1.py
py
1,565
python
en
code
0
github-code
6
72531840829
"""Adds column to use scicrunch alternative Revision ID: b60363fe438f Revises: 39fa67f45cc0 Create Date: 2020-12-15 18:26:25.552123+00:00 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "b60363fe438f" down_revision = "39fa67f45cc0" branch_labels = None depends_o...
ITISFoundation/osparc-simcore
packages/postgres-database/src/simcore_postgres_database/migration/versions/b60363fe438f_adds_column_to_use_scicrunch_alternative.py
b60363fe438f_adds_column_to_use_scicrunch_alternative.py
py
1,066
python
en
code
35
github-code
6
21247913444
import unittest from unittest.mock import patch import os from typing import Optional from dataclasses import dataclass from io import StringIO from ml_project.train_pipeline import run_train_pipeline from ml_project.predict_pipeline import run_predict_pipeline from sklearn.preprocessing import StandardScaler from m...
made-mlops-2022/alexey_sklyannyy
tests/test_end2end_training.py
test_end2end_training.py
py
2,397
python
en
code
0
github-code
6
33124682966
import json import os import docx with open(f'disciplinas.json') as f: data = json.load(f) # print(df.columns.values) for index, discpln in data.items(): print(f'{discpln["sigla"]} - {discpln["nome"]}') doc = docx.Document() doc.add_heading(f'{discpln["sigla"]} - {discpln["nome"]}') doc.add_hea...
luizeleno/pyjupiter
_python/gera-doc-pdf-unificado.py
gera-doc-pdf-unificado.py
py
2,978
python
es
code
2
github-code
6
22167366155
import time from functools import wraps from MatrixDecomposition import MatrixDecomposition from MatrixGeneration import MatrixGeneration def fn_timer(function): @wraps(function) def function_timer(*args, **kwargs): t0 = time.time() result = function(*args, **kwargs) t1 = time.time() ...
g3tawayfrom/appmath_lab4
Analyzer.py
Analyzer.py
py
1,953
python
en
code
0
github-code
6
35792097840
#!/usr/bin/env python # coding: utf-8 # In[ ]: from selenium import webdriver from selenium.webdriver.common.by import By import time from selenium.webdriver.support.ui import WebDriverWait import random def get_sore_and_Price(store_id,internet_id): driver = webdriver.Chrome('C:/Users/cunzh/Desktop/chromedriver...
JiyuanZhanglalala/Web-Scraping-
Home Depot Web Scraping Function.py
Home Depot Web Scraping Function.py
py
2,398
python
en
code
0
github-code
6
9634583525
# Builds some spectra and self-energies using the aux.Aux functionality import numpy as np from auxgf import mol, hf, aux, agf2, grids from auxgf.util import Timer timer = Timer() # Build the Molecule object: m = mol.Molecule(atoms='H 0 0 0; Li 0 0 1.64', basis='cc-pvdz') # Build the RHF object: rhf = hf.RHF(m) rh...
obackhouse/auxgf
examples/06-spectra.py
06-spectra.py
py
1,839
python
en
code
3
github-code
6
32941642034
import numpy as np import matplotlib from matplotlib.colors import ListedColormap SLACred = '#8C1515' SLACgrey = '#53565A' SLACblue = '#007C92' SLACteal = '#279989' SLACgreen = '#8BC751' SLACyellow = '#FEDD5C' SLACorange = '#E04F39' SLACpurple = '#53284F' SLAClavender = '#765E99' SLACbrown = '#5F574F' SLACcolors = [S...
DanielMDouglas/SLACplots
SLACplots/colors.py
colors.py
py
1,729
python
en
code
0
github-code
6
72946559547
import socket import struct import os import time import hashlib HOST = '192.168.1.76' PORT = 8000 BUFFER_SIZE = 1024 FILE_NAME = 'usertrj.txt' # Change to your file FILE_SIZE = os.path.getsize(FILE_NAME) HEAD_STRUCT = '128sIq32s' # Structure of file head def send_file(): # Create a TCP/IP socket sock = s...
cash2one/brush-1
slave/scripts/test/connect.py
connect.py
py
1,878
python
en
code
0
github-code
6
25847181178
import tkinter as tk import sqlite3 def guardar_palabras(): palabras = [entrada1.get(), entrada2.get(), entrada3.get(), entrada4.get(), entrada5.get()] # Conexión a la base de datos conexion = sqlite3.connect('basedatos.db') cursor = conexion.cursor() # Crear la tabla "palabras" si no existe ...
AlejandroAntonPineda/ArtPersonality
base_datos.py
base_datos.py
py
3,754
python
es
code
0
github-code
6
27385560013
from road import Road from copy import deepcopy from collections import deque from vehicleGenerator import VehicleGenerators import numpy as np from scipy.spatial import distance import random class Simulator: def __init__(self, config = {}) -> None: self.setDefaultConfig() #update vals for...
EHAT32/alg_labs_sem_7
lab3/simulator.py
simulator.py
py
4,713
python
en
code
0
github-code
6
25971386553
""" .. testsetup:: * from zasim.cagen.utils import * """ # This file is part of zasim. zasim is licensed under the BSD 3-clause license. # See LICENSE.txt for details. from ..features import HAVE_TUPLE_ARRAY_INDEX from itertools import product import numpy as np if HAVE_TUPLE_ARRAY_INDEX: def offset_pos(po...
timo/zasim
zasim/cagen/utils.py
utils.py
py
4,490
python
en
code
4
github-code
6
20043759155
# Given the names and grades for each student in a class of students, store them in a # nested list and print the name(s) of any student(s) having the second lowest grade. # Note: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line. # Print...
Elevenv/HackerRank-Python-challenges
nested_list.py
nested_list.py
py
1,025
python
en
code
2
github-code
6
32787034238
""" URL configuration for backend project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home...
wncc/SoC-Portal
backend/backend/urls.py
urls.py
py
2,001
python
en
code
12
github-code
6
12866597010
import sys from collections import defaultdict def tpsortutil(u, visited, stack, cur): visited[u] = True for i in graph[u]: if not visited[i]: tpsortutil(i, visited, stack, cur) elif i in cur: return stack.append(u) def topologicalsort(graph, vertices): visited ...
tyao117/AlgorithmPractice
TopologicalSort/TopologicalSort.py
TopologicalSort.py
py
825
python
en
code
0
github-code
6
225835019
import streamlit as st import calculator_logic st.title("Calculator App") num1 = st.number_input("Enter the first number:") num2 = st.number_input("Enter the second number:") operation = st.selectbox("Select an operation", calculator_logic.OPERATIONS) if st.button("Calculate"): result = calculator_logic.calculat...
shib1111111/basic_calculator
app.py
app.py
py
1,113
python
en
code
0
github-code
6