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
13563263971
import requests import time import json from hoshino import aiorequests apiroot = 'https://help.tencentbot.top' async def getprofile(viewer_id: int, interval: int = 1, full: bool = False) -> dict: reqid = json.loads(await aiorequests.get(f'{apiroot}/enqueue?full={full}&target_viewer_id={viewer_id}').content.decod...
pcrbot/arena_query_push
queryapi.py
queryapi.py
py
933
python
en
code
7
github-code
6
69894678589
import configparser from datetime import datetime import os from pyspark.sql import SparkSession from pyspark.sql.functions import udf, col, monotonically_increasing_id from pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, date_format from pyspark.sql import types as t # reading in the AWS confi...
greggwilliams58/data-lake
etl.py
etl.py
py
8,843
python
en
code
0
github-code
6
72137353787
import logging import json from discord import Interaction, app_commands, Role from discord.app_commands import Choice from discord.ext.commands import Bot, Cog logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) with open("config.json") as cfg_json: cfg = json.loads(cfg_json.read()) ...
tenacious210/dgg-relay
cogs.py
cogs.py
py
14,701
python
en
code
2
github-code
6
3344378919
import logging import sys from loguru import logger from starlette.config import Config from starlette.datastructures import Secret from app.core.logger import InterceptHandler config = Config(".env") API_PREFIX = "/api" VERSION = "0.1.0" DEBUG: bool = config("DEBUG", cast=bool, default=False) MAX_CONNECTIONS_COUN...
hieunt2501/text-augmentation
app/core/config.py
config.py
py
1,648
python
en
code
0
github-code
6
18132721237
from flask import Flask, redirect, render_template, request, url_for, session, flash from datetime import timedelta from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.secret_key = "hello" app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.sqlite3' # Things you have to set up before creating a dat...
JayChen1060920909/Projects
Login-Logout.py
Login-Logout.py
py
3,056
python
en
code
1
github-code
6
21346415865
problems = input() count_trust = 0 implemented_problems = 0 for i in range(0,int(problems)): trust_line = input() trust_line = trust_line.split(' ') for j in trust_line: if j=='1': count_trust+=1 if count_trust >1: implemented_problems +=1 count_trust = 0 print(impleme...
YahyaQandel/CodeforcesProblems
Team.py
Team.py
py
334
python
en
code
0
github-code
6
17953524197
# -*- coding: utf-8 -*- import numpy as np import torch import torch.nn as nn from lichee import plugin from lichee import config @plugin.register_plugin(plugin.PluginType.MODULE_LOSS, 'mse_loss') class MSELoss: @classmethod def build(cls, cfg): return nn.MSELoss() @plugin.register_plugin(plugin.P...
Tencent/Lichee
lichee/module/torch/loss/loss.py
loss.py
py
8,023
python
en
code
295
github-code
6
72067617789
import math as ma import multiprocessing as mp import time def first_test(n): """ test naïf de primalité retourne True si l'entier est premier, et inversement n : un entier naturel """ for a in range(2, int(ma.sqrt(n) + 1)): if n % a == 0: return False return True def pi(...
BasileLewan/ProjetCOMPLEX
Ex2.py
Ex2.py
py
3,830
python
fr
code
0
github-code
6
70111562749
import firstscript as sense import random import time def get_random_time(): random_time_frame = random.randrange(7,25) return random_time_frame def get_random(): numbers = [1,2,3,4,5,6,7,8,9] y = get_random_time() for i in range(y): sense.display_letter(str(random.choice(numbers))) ...
cthacker-udel/Raspberry-Pi-Scripts
py/randomnumber.py
randomnumber.py
py
477
python
en
code
7
github-code
6
38520392642
#!/usr/bin/python """ This is the code to accompany the Lesson 1 (Naive Bayes) mini-project. Use a Naive Bayes Classifier to identify emails by their authors authors and labels: Sara has label 0 Chris has label 1 """ import sys import time sys.path.append("../tools/") from email_prepr...
Vkadel/machineLearningNB
nb_author_id.py
nb_author_id.py
py
1,524
python
en
code
0
github-code
6
42940796937
from typing import List, Tuple import networkx as nx import numpy as np from matplotlib import pyplot as plt import time import copy from node import Node def get_graph(node: Node) -> Tuple[nx.Graph, List, List]: board_size = node.state.shape[0] G = nx.grid_2d_graph(board_size, board_size) diagonals = [] ...
Mathipe98/IT3105-Projects
Project 2/visualizer.py
visualizer.py
py
1,707
python
en
code
0
github-code
6
858399284
from __future__ import division from PyQt4 import QtCore, QtGui from vistrails.core.inspector import PipelineInspector from vistrails.gui.common_widgets import QToolWindowInterface from vistrails.gui.pipeline_view import QPipelineView from vistrails.gui.theme import CurrentTheme ######################################...
VisTrails/VisTrails
vistrails/gui/paramexplore/pe_pipeline.py
pe_pipeline.py
py
3,719
python
en
code
100
github-code
6
28220979750
#Import Necessary Packages import numpy as np import matplotlib.pyplot as plt from scipy import stats import seaborn as sns import ruptures as rpt from statistics import stdev import pandas as pd def load_rms(path, sect, ref): raw_string = open('../../' + path + '/rmsd_' + sect + '_ref_' + ref + '.txt').readlines(...
ajfriedman22/PTP1B
compare_mutant_scripts/rmsd_mut_compare.py
rmsd_mut_compare.py
py
30,484
python
en
code
0
github-code
6
6056862050
from datetime import datetime import csv def logReceivedGossip(file,gossipID,spreader,audience,awardedSP,targetCitizensSP,receivingAudienceKnownRumours,citizen_list,rumourTarget,sentiment): now = datetime.now() date_time = now.strftime("%m/%d/%Y %H:%M:%S:%f") # get total rumour count for key in citizen_list: kt...
murchie85/gossipSimulator
game/functions/logging.py
logging.py
py
822
python
en
code
25
github-code
6
70835728188
import json fs = open("G:\python\Analysis"+"\\"+'score.json', encoding='utf-8') ft = open("G:\python\Analysis"+"\\"+'template.json', encoding='utf-8') res1 = fs.read() data = json.loads(res1) res2 = ft.read() template = json.loads(res2) scoreKey = [] templateKey = template.keys() goal = {} for key in data: user...
nju161250023/Analysis
createFlag.py
createFlag.py
py
803
python
en
code
0
github-code
6
27196052204
import Node def readFile(filePath, heuristic=None): if heuristic is None: heuristic = {} with open("./data/" + filePath, 'r') as f: data = f.read().splitlines() initialState, goalState = None, [None] graph = dict() count = 0 for line in data: if line == '' or line ==...
EdiProdan/FER
Introduction to Artificial Intelligence/laboratory_exercise_1/utils.py
utils.py
py
2,163
python
en
code
0
github-code
6
33062234730
#!/usr/local/bin/python # -*- coding: utf-8 -* import requests class MetrikaAPI(object): def __init__(self, counter_id, token, host='https://api-metrika.yandex.ru'): self.counter_id = counter_id self.token = token self.host = host def _get_url(self, url='/stat/v1/data', params=None,...
swetlanka/py3
3-5/3-5.py
3-5.py
py
1,824
python
en
code
0
github-code
6
74281365627
from __future__ import annotations import re from dataclasses import asdict, dataclass from typing import Optional, Sized, TypeVar import torch import torchinfo from accelerate.utils.random import set_seed from torch.utils.data import DataLoader from simpletrainer.utils.common import pretty_repr T = TypeVar('T') se...
Moka-AI/simpletrainer
simpletrainer/utils/torch.py
torch.py
py
4,653
python
en
code
3
github-code
6
33229412854
# Implement the first move model for the Lego robot. # 02_a_filter_motor # Claus Brenner, 31 OCT 2012 from math import sin, cos, pi from pylab import * from lego_robot import * # This function takes the old (x, y, heading) pose and the motor ticks # (ticks_left, ticks_right) and returns the new (x, y, heading)...
jfrascon/SLAM_AND_PATH_PLANNING_ALGORITHMS
01-GETTING_STARTED/CODE/slam_02_a_filter_motor_question.py
slam_02_a_filter_motor_question.py
py
1,893
python
en
code
129
github-code
6
5569399042
"""Display image captured from image sensor""" import numpy as np import cv2 import socket import tkinter import pandas as pd import datetime import time import os class ImageGUI(object): def __init__(self): #self.buffer_size = 128 * 128 * 3 # picture size self.buffer_size = (16384 * 2 + 2048 * 2...
yg99992/Image_transfer_open_source
python_code/Image_show.py
Image_show.py
py
10,237
python
en
code
6
github-code
6
28400031595
import os import time from datetime import datetime import torch from torch import nn from torch.utils.tensorboard import SummaryWriter import torch.nn.functional as F from torch.autograd import Variable import pandas as pd import warnings warnings.filterwarnings("ignore") import random import numpy as np import utils....
houhsein/Spleen_injury_detection
classification/utils/training_torch_utils.py
training_torch_utils.py
py
19,509
python
en
code
1
github-code
6
18537216469
# prob_link: https://www.codingninjas.com/codestudio/problems/majority-element-ii_8230738?challengeSlug=striver-sde-challenge&leftPanelTab=0 from math import * from collections import * from sys import * from os import * def majorityElementII(arr): n = len(arr) # Write your code here. mp = {} ...
Red-Pillow/Strivers-SDE-Sheet-Challenge
P16_Majority Element-II.py
P16_Majority Element-II.py
py
549
python
en
code
0
github-code
6
14188272016
from fastapi import FastAPI app = FastAPI() COLUMN_NAME = "name" COLUMN_ID = "id" FAKE_DB = [ {"id": 1, "name": "Vladimir"}, {"id": 2, "name": "Polina"}, {"id": 3, "name": "Aleksander"} ] def find_friend_name(friend_id, db_name): for row in db_name: if row.get(COLUMN_ID) == friend_id: ...
DanilaLabydin/Python-tasks-solving-practice
app/main.py
main.py
py
715
python
en
code
0
github-code
6
5005445920
from __future__ import annotations from pathlib import Path from typing import Any, cast import _testutils import pytest from lxml.html import ( HtmlElement as HtmlElement, find_class, find_rel_links, iterlinks, make_links_absolute, parse, resolve_base_href, rewrite_links, ) reveal_ty...
abelcheung/types-lxml
test-rt/test_html_link_funcs.py
test_html_link_funcs.py
py
3,706
python
en
code
23
github-code
6
14565937194
# Check if a given parentheses string is valid # # Input: par: string # Output: true or false: bool # # We need a stack to store opening braces # We need a map to store types of braces # # Check the length of the string, if the length is odd, return False # Loop through the list, for each char, # - If it is an opening ...
HemlockBane/ds_and_algo
stacks/study_questions.py
study_questions.py
py
1,124
python
en
code
0
github-code
6
14098998919
#!/usr/bin/env python # -*- coding: utf-8 -*- """ =================================== Timer --- Create a timer decorator. =================================== Largely this module was simply practice on writing decorators. Might need to review logging best practices. I don't want the logger from this module to emit any...
farisachugthai/dynamic_ipython
default_profile/util/timer.py
timer.py
py
5,023
python
en
code
7
github-code
6
77938817
""" file structure: flip_labels_and_scans.py scan_directrory - raw scans folder label_directrory - labels folder save_dir_scan - flipped scans folder (where they will be saved) save_dir_labels - flipped labels folder (where they will be saved) This script flips nii (nifti) labels and scans along the sagittal ...
kylerioux/python_ML_scripts
3d_image_preprocessing/flip_scans_and_labels.py
flip_scans_and_labels.py
py
4,139
python
en
code
0
github-code
6
34214358930
import json # Set file paths basePath = 'D:\\NTCIR-12_MathIR_arXiv_Corpus\\' inputPath = basePath + "output_FeatAna\\" index_file = 'inverse_semantic_index_formula_catalog(physics_all).json' #basePath = 'D:\\NTCIR-12_MathIR_Wikipedia_Corpus\\' #inputPath = basePath + "output_RE\\" #index_file = 'inverse_semantic_index...
pratyushshukla19/Minor-Project-2
semanticsearch/modes13-15/evaluate_inverse_formula_index.py
evaluate_inverse_formula_index.py
py
2,411
python
en
code
0
github-code
6
44855958646
""" Source: https://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/ Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod ...
sandeepjoshi1910/Algorithms-and-Data-Structures
optimal_rod.py
optimal_rod.py
py
1,271
python
en
code
0
github-code
6
71476989628
import sys input = sys.stdin.readline dx = [1, 0] dy = [0, 1] T = int(input()) for tc in range(T): M, N, K = map(int, input().split()) original = [] stack = [] for _ in range(K): x, y = map(int, input().split()) original.append((x, y)) stack.append((x, y)) for nx, ny in o...
YOONJAHYUN/Python
BOJ/1012_2.py
1012_2.py
py
831
python
en
code
2
github-code
6
73083659707
import numpy as np from scipy.spatial.distance import cdist import matplotlib.pyplot as plt def has_converged(centers, new_centers): return set([tuple(a) for a in centers]) == set([tuple(a) for a in new_centers]) def kmeans(X, K): # centroids = X[np.random.choice(X.shape[0], K, replace=False)] centroids...
cuongdd2/cs582
lab6/prob4.py
prob4.py
py
1,807
python
en
code
0
github-code
6
41149275833
""" Internet Validators - ValidateEmail - ValidateIP - ValidateURL """ import socket import re from email_validator import validate_email, EmailNotValidError from flask_validator import Validator class ValidateEmail(Validator): """ Validate Email type. Check if the new value is a valid e-mail. Using t...
xeBuz/Flask-Validator
flask_validator/constraints/internet.py
internet.py
py
3,190
python
en
code
28
github-code
6
20662954004
# Imports from math import pi pi * 71 / 223 from math import sin sin(pi/2) # Function values max max(3, 4) f = max f f(3, 4) max = 7 f(3, 4) f(3, max) f = 2 # f(3, 4) # User-defined functions from operator import add, mul add(2, 3) mul(2, 3) def square(x): return mul(x, x) square(21)
Thabhelo/CS7
lab/lab1/code03.py
code03.py
py
295
python
en
code
1
github-code
6
18555731856
import Adafruit_DHT from main.SQL import TempHandler import time class Temps(): def __init__(self): self.sensor = Adafruit_DHT.DHT11 self.pin = 17 self.humidity = 0 self.temperature = 0 def getDHT(self): self.humidity, self.temperature = Adafruit_DHT.read_retry(self.sen...
chinazkk/raspberry_car
main/Temps.py
Temps.py
py
736
python
en
code
0
github-code
6
39204707046
""" 题目介绍:剑指 Offer 48. 最长不含重复字符的子字符串 请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度 """ def length_of_longest_substring(s): dic = {} res = tmp = 0 for j in range(len(s)): # 获取索引i i = dic.get(s[j], -1) # 更新哈希表 dic[s[j]] = j tmp = tmp + 1 if tmp < j - i else j - i res = ...
Davidhfw/algorithms
python/dp/48_lengthOfLongestSubstring.py
48_lengthOfLongestSubstring.py
py
856
python
en
code
1
github-code
6
74866931066
import datetime as dt import matplotlib.pyplot as plt import numpy as np import os class HobsHeader(object): sim_head = '"SIMULATED EQUIVALENT"' obs_head = '"OBSERVED VALUE"' obs_name = '"OBSERVATION NAME"' date = 'DATE' dyear = 'DECIMAL_YEAR' header = {sim_head: None, ...
jlarsen-usgs/HydrographTools
hobs_output.py
hobs_output.py
py
22,180
python
en
code
1
github-code
6
33837428124
import array import struct import sys from collections import namedtuple import plotly.express as px import numpy as np from scipy.ndimage import uniform_filter1d from statsmodels.nonparametric.smoothers_lowess import lowess import matplotlib.pyplot as plt from math import degrees, atan import scipy.signal TYPE_DIGIT...
nkelly1322/analog_analysis
AnalogAnalysis.py
AnalogAnalysis.py
py
4,559
python
en
code
0
github-code
6
74732381948
import numpy as np import tensorflow as tf import cv2 def colormap_jet(img): color_image = cv2.applyColorMap(np.uint8(img), cv2.COLORMAP_JET) return color_image def color_disparity(disparity): with tf.variable_scope('color_disparity'): batch_size = disparity.shape[0] color_maps = [] ...
fabiotosi92/monoResMatch-Tensorflow
utils.py
utils.py
py
677
python
en
code
117
github-code
6
21916066362
#condig=utf-8 ###二叉树 #树节点 class Node(object): def __init__(self,elem=-1, lchild =None,rchild = None): #节点的值 self.elem = elem #左节点 self.lchild = lchild #右节点 self.rchild = rchild #树 class Tree(object): def __init__(self): self.root = Node() self.my...
DC-Joney/Machine-Learning
Arithmetic/nodetree.py
nodetree.py
py
4,247
python
en
code
1
github-code
6
24698015874
## # The model uses elements from both the Transformer Encoder as introduced in # “Attention is All You Need” (https://arxiv.org/pdf/1706.03762.pdf) and the # Message Passing Neural Network (MPNN) as described in "Neural Message Passing # for Quantum Chemistry" paper (https://arxiv.org/pdf/1704.01212.pdf) . # # T...
robinniesert/kaggle-champs
model.py
model.py
py
17,738
python
en
code
48
github-code
6
17692957276
import os import re import asyncio import time from pyrogram import * from pyrogram.types import * from random import choice from Heroku import cloner, ASSUSERNAME, BOT_NAME from Heroku.config import API_ID, API_HASH IMG = ["https://telegra.ph/file/cefd3211a5acdcd332415.jpg", "https://telegra.ph/file/30d743cea510c563af...
Amahocaam/SmokeX
Heroku/plugins/clone.py
clone.py
py
2,063
python
en
code
0
github-code
6
26436839942
from PIL import Image imgx = 512 imgy = 512 image = Image.new("RGB",(imgx,imgy)) for x in range(imgx): for y in range(imgy): if ((x//64)%2 == 1) or ((x//64)%2 == 2) and (y//64)%2 == 1 or ((y//64)%2 == 2): image.putpixel ((x,y), (0,0,0) ) else: image.putpixel ((x,y), (250,0,0) ) image.save("demo_image...
gbroady19/CS550
intropil.py
intropil.py
py
334
python
en
code
0
github-code
6
26625288006
from decimal import Decimal from django import template from livesettings import config_value from product.utils import calc_discounted_by_percentage, find_best_auto_discount from tax.templatetags import satchmo_tax register = template.Library() def sale_price(product): """Returns the sale price, including tax if...
dokterbob/satchmo
satchmo/apps/product/templatetags/satchmo_discounts.py
satchmo_discounts.py
py
6,222
python
en
code
30
github-code
6
18769293531
from random import randrange with open("in0210_2.txt","w") as f: for _ in range(20): W,H = randrange(1,31),randrange(1,31) f.writelines("%d %d\n"%(W,H)) arr = ["".join("....##ENWSX"[randrange(11)] for _ in range(W)) for _ in range(H)] arr[0] = "".join("##X"[randrange(3)] for _ in ra...
ehki/AOJ_challenge
python/0210_2.py
0210_2.py
py
590
python
en
code
0
github-code
6
32644908087
"""Guide Eye 01 module""" from functools import partial from mgear.shifter.component import guide from mgear.core import transform, pyqt from mgear.vendor.Qt import QtWidgets, QtCore from maya.app.general.mayaMixin import MayaQWidgetDockableMixin from maya.app.general.mayaMixin import MayaQDockWidget from . import s...
mgear-dev/mgear4
release/scripts/mgear/shifter_classic_components/eye_01/guide.py
guide.py
py
5,095
python
en
code
209
github-code
6
71617385147
import pandas as pd # Load the original CSV file df = pd.read_csv('data.csv') # Calculate the number of rows in each output file num_rows = len(df) // 10 # Split the dataframe into 10 smaller dataframes dfs = [df[i*num_rows:(i+1)*num_rows] for i in range(10)] # Save each dataframe to a separate CSV file for i, df i...
charchitdahal/GameDay-Analytics-Challenge
convert.py
convert.py
py
388
python
en
code
0
github-code
6
20216292952
from model.flyweight import Flyweight from model.static.database import database class Name(Flyweight): def __init__(self,item_id): #prevents reinitializing if "_inited" in self.__dict__: return self._inited = None #prevents reinitializing self.item_id = item_id...
Iconik/eve-suite
src/model/static/eve/name.py
name.py
py
655
python
en
code
0
github-code
6
40187097853
"""https://open.kattis.com/problems/piglatin""" VOWEL = {'a', 'e', 'i', 'o', 'u', 'y'} def is_begin_with_consonant(word, vowel=VOWEL): return word[0] not in vowel def is_begin_with_vowel(word, vowel=VOWEL): return word[0] in vowel def get_next_vowel_index(word, vowel=VOWEL): index = 0 for i in wo...
roycehoe/algo-practice
practice/kattis/2/piglatin.py
piglatin.py
py
691
python
en
code
1
github-code
6
40527670685
from django import forms from django.forms import TextInput, SplitDateTimeWidget class NumberInput(TextInput): """ HTML5 Number input Left for backwards compatibility """ input_type = 'number' class AdminDateWidget(forms.DateInput): @property def media(self): js = ["calendar.js...
ricardochaves/django-adminlte
adminlte/widgets.py
widgets.py
py
1,631
python
en
code
1
github-code
6
12646834769
import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression df = pd.read_csv('dividedsamples/training.csv') dfval = pd.read_csv('dividedsamples/testing.csv') train_features = df.copy() test_features = d...
WayneFerrao/autofocus
linreg.py
linreg.py
py
717
python
en
code
2
github-code
6
3026345716
# -*- coding: utf-8 # Testing facet-sphere interaction in periodic case. # Pass, if the sphere is rolling from left to right through the period. from woo import utils sphereRadius=0.1 tc=0.001# collision time en=0.3 # normal restitution coefficient es=0.3 # tangential restitution coefficient density=2700 friction...
Azeko2xo/woodem
scripts/test-OLD/facet-sphere-ViscElBasic-peri.py
facet-sphere-ViscElBasic-peri.py
py
1,352
python
en
code
2
github-code
6
70943332987
_base_ = [ './uvtr_lidar_base.py' ] point_cloud_range = [-54, -54, -5.0, 54, 54, 3.0] pts_voxel_size = [0.075, 0.075, 0.2] voxel_size = [0.15, 0.15, 8] lidar_sweep_num = 10 # For nuScenes we usually do 10-class detection class_names = [ 'car', 'truck', 'construction_vehicle', 'bus', 'trailer', 'barrier', ...
dvlab-research/UVTR
projects/configs/uvtr/lidar_based/uvtr_l_v0075_h5.py
uvtr_l_v0075_h5.py
py
4,629
python
en
code
199
github-code
6
35987738740
import torch from tsf_baselines.modeling import build_network ALGORITHMS = [ 'BasicTransformerEncoderDecoder' ] def get_algorithm_class(algorithm_name): """Return the algorithm class with the given name.""" if algorithm_name not in globals(): raise NotImplementedError("Algorithm not found: {}".fo...
zhaoyang10/time-series-forecasting-baselines
tsf_baselines/algorithm/build.py
build.py
py
3,942
python
en
code
3
github-code
6
14712079581
from typing import List, Optional from fastapi import APIRouter, Header from fastapi.exceptions import HTTPException from server.models.subscription import ( ExchangeKlineSubscriptionRequest, ExchangeSubscription, ExchangeSubscriptionType, ) router = APIRouter() @router.get("/") async def list(x_connec...
masked-trader/raccoon-exchange-service
src/server/routes/subscription/kline.py
kline.py
py
3,263
python
en
code
0
github-code
6
72784206907
# https://www.codewars.com/kata/5fc7d2d2682ff3000e1a3fbc import re def is_a_valid_message(message): valid = all(int(n) == len(w) for n,w in re.findall(r'(\d+)([a-z]+)',message, flags = re.I)) # in the name of readability if valid and re.match(r'((\d+)([a-z]+))*$',message, flags = re.I): return True...
blzzua/codewars
6-kyu/message_validator.py
message_validator.py
py
910
python
en
code
0
github-code
6
14400394656
#!/usr/bin/env python3.8 def missing_element(arr1, arr2): arr1.sort() arr2.sort() for num1, num2 in zip(arr1, arr2): if num1 != num2: return num1 return -1 def missing_element1(arr1, arr2): count = {} output = [] for i in arr1: if i in count: count[i] += 1 else: count[i] = 1 for i in arr2: ...
dnootana/Python
concepts/arrays/find_missing_element.py
find_missing_element.py
py
950
python
en
code
0
github-code
6
9270774406
class Solution: def smallestEqual(self, nums: List[int]) -> int: output = [] for i in range(len(nums)): if i % 10 == nums[i]: output.append(i) if len(output) > 0: return min(output) else: return -1
nancyalaa/LeetCode
2057-smallest-index-with-equal-value/2057-smallest-index-with-equal-value.py
2057-smallest-index-with-equal-value.py
py
294
python
en
code
1
github-code
6
10233608865
from __future__ import annotations import re from typing import TYPE_CHECKING from twitchio import User, PartialUser, Chatter, PartialChatter, Channel, Clip from .errors import BadArgument if TYPE_CHECKING: from .core import Context __all__ = ( "convert_Chatter", "convert_Clip", "convert_Channel", ...
PythonistaGuild/TwitchIO
twitchio/ext/commands/builtin_converter.py
builtin_converter.py
py
2,755
python
en
code
714
github-code
6
18660136090
import os import sys try: from dreamberd import interprete except ModuleNotFoundError: sys.exit("Use -m keyword.") from argparse import ArgumentParser parser = ArgumentParser( prog="DreamBerd Interpreter (Python)", description="The perfect programming language.", ) parser.add_argument("content", help...
AWeirdScratcher/dreamberd-interpreter
dreamberd/__main__.py
__main__.py
py
559
python
en
code
0
github-code
6
36776570545
class Solution: def combination(self, visited, idx): if sum(visited) == self.target: self.ans.append(list(visited)) return if sum(visited) > self.target: return for i in range(idx, len(self.candidates)): visited.append(self.candidates[...
nathy-min/Competitive_Programming2
0039-combination-sum/0039-combination-sum.py
0039-combination-sum.py
py
640
python
en
code
1
github-code
6
3574016217
"""Python module for common workflows and library methods. Authors: Prasad Hegde """ import os import json import pathlib import inspect import random import string class Workflows(): """ Common Workflows and library methods """ def get_config_data(self, test_method): """ This routin...
prasadhegde60/showoff.ie
workflows/workflows.py
workflows.py
py
3,021
python
en
code
0
github-code
6
4432774556
import random trials = 100000 budget = 1000 bet = 100 goal = 2 * budget probability = 18/37 def gamblers_ruin(budget, bet, goal, probability): current_budget = budget num_bets = 0 while current_budget > 0 and current_budget < goal: num_bets += 1 if random.random() < probabilit...
ander428/Computational-Economics-MGSC-532
In Class Code/GamblersRuin.py
GamblersRuin.py
py
1,224
python
en
code
0
github-code
6
2018211678
#!/usr/bin/env python import os from applicake.app import WrappedApp from applicake.apputils import validation from applicake.coreutils.arguments import Argument from applicake.coreutils.keys import Keys, KeyHelp class Dss(WrappedApp): """ The DSS is often a initial workflow node. Requesting a workdir has th...
lcb/applicake
appliapps/openbis/dss.py
dss.py
py
3,044
python
en
code
1
github-code
6
73652373309
# 编写一个算法来判断一个数 n 是不是快乐数。 # “快乐数” 定义为: # 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。 # 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。 # 如果这个过程 结果为 1,那么这个数就是快乐数。 class Solution(object): def isHappy(self, n): """ :type n: int :rtype: bool """ visited = {n} while (True): next =...
xxxxlc/leetcode
array/isHappy.py
isHappy.py
py
860
python
zh
code
0
github-code
6
372063532
#!/usr/bin/env python3 import socketserver, socket, threading upload = {} download = {} threadList = [] terminate = False def shutdownServer(): global server server.shutdown() def handlethread(socketup, socketdown): data = socketup.recv(512) while data: socketdown.send(data) data = ...
rainagan/cs456
a1/server.py
server.py
py
3,642
python
en
code
1
github-code
6
4755956537
import argparse import os import sys import time import json import pickle from nltk.corpus import wordnet as wn import numpy as np import torch import random from aligner import Aligner import log logger = log.get_logger('root') logger.propagate = False def get_print_result(sample_group: dict, sample_result: dict...
lksenel/CoDA21
Evaluation/evaluate_PLMs.py
evaluate_PLMs.py
py
4,847
python
en
code
2
github-code
6
27094902824
from typing import Any, Callable, Dict from torchvision import transforms as T from rikai.types.vision import Image """ Adapted from https://github.com/pytorch/pytorch.github.io/blob/site/assets/hub/pytorch_vision_resnet.ipynb """ # noqa E501 def pre_processing(options: Dict[str, Any]) -> Callable: """ Al...
World-shi/rikai
python/rikai/contrib/torchhub/pytorch/vision/resnet.py
resnet.py
py
1,166
python
en
code
null
github-code
6
27453799884
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ ...
dreamebear/Coding-interviews
BFS/LC637-Avg-Level-Binary-Tree/LC637.py
LC637.py
py
794
python
en
code
0
github-code
6
23515271400
# First Solution: 58476KB / 200ms / 674B def BS(array,start,end): while start<=end: mid = (start+end)//2 if array[mid][1] == 1 and array[mid-1][1]==2: return mid elif array[mid][1] == 2: start = mid+1 else: end = mid-1 return None def Solution(data): data = sorted(data.items...
Soohee410/Algorithm-in-Python
BOJ/Silver/1764.py
1764.py
py
1,094
python
en
code
6
github-code
6
17433175980
import os import sys import unittest sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from chvote.Utils.Utils import AssertList def CheckVerificationCodes(rc_bold, rc_prime_bold, s_bold): """ Algorithm 7.29: Checks if every displayed verification code RC'_i i matches wi...
nextgenevoting/visualizer
backend/chvote/VotingClient/CheckVerificationCodes.py
CheckVerificationCodes.py
py
1,079
python
en
code
3
github-code
6
25760579432
from opencage.geocoder import OpenCageGeocode import xlrd import xlwt from xlwt import Workbook import pandas as pd key ="fd4f682cf2014f3fbd321ab141454138" # get api key from: https://opencagedata.com geocoder = OpenCageGeocode(key) loc = ("/Users/ashwinisriram/Documents/Lat long/corrected.xlsx") wb = xl...
Ashwini-Sriram/Latlong
alter.py
alter.py
py
2,116
python
en
code
0
github-code
6
38703775254
import json def getAdminAccount(): with open("./Data/admins.json", "r") as file: JSON = file.read() accounts = json.loads(JSON) return accounts def getAccount(): with open("./Data/accounts.json", "r") as file: JSON = file.read() accounts = json.loads(JSON) return...
Coincoin008/DrawPlz-localhost-version-
getAccounts.py
getAccounts.py
py
333
python
en
code
0
github-code
6
29528497286
#!/usr/bin/python3 import html import re import random import json import requests from bs4 import BeautifulSoup PATTERN = re.compile(r'/video(\d+)/.*') def _fetch_page(page_number): url = 'https://www.xvideos.com/porn/portugues/' + str(page_number) res = requests.get(url) if res.status_code != 200: ...
marquesgabriel/bot-xvideos-telegram
xvideos.py
xvideos.py
py
2,846
python
en
code
2
github-code
6
41589531993
L = [("Rimm",100), ("FengFeng",95), ("Lisi", 87), ("Ubuntu", 111)] def by_name(n): x = sorted(n[0], key=str.lower) return x out = sorted(L, key=by_name) print(out) def by_score(n): x = sorted(range(n[1]), key=abs) return x o = sorted(L, key=by_score, reverse=True) print(o)
Wainemo/PythonPractice
tuple表示学生名和成绩 用sorted排序.py
tuple表示学生名和成绩 用sorted排序.py
py
295
python
en
code
0
github-code
6
29608054037
''' NEURAL NETWORK FOR DIGIT DETECTION This program is a shallow Neural Network that is trained to recognize digits written in a 5x3 box ''' import random import math import csv # Hyperparameters: # speed (magnitude) at which algorithm adjusts weights LEARNING_RATE = 0.3 # Feature –> individual and independent varia...
DinglyCoder/Neural_Network_Digit_Classifier
Digit_NN.py
Digit_NN.py
py
9,468
python
en
code
0
github-code
6
33828906255
import subprocess import os from concurrent.futures import ThreadPoolExecutor spiders = subprocess.run(["scrapy", "list"], stdout=subprocess.PIPE, text=True).stdout.strip().split('\n') def run_spider(spider_name): log_file = f"logs/{spider_name}_logs.txt" os.makedirs(os.path.dirname(log_file), exist_ok=True) w...
hassaan-ahmed-brainx/enpak_scrappers
run_spiders.py
run_spiders.py
py
615
python
en
code
0
github-code
6
71362184827
import os import sys sys.path.insert(0, os.path.abspath('..')) # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information project = 'PythonPDB' copyright = '2023, Benjamin McMaster' author = 'Benjamin McMaster' # ...
benjiemc/PythonPDB
docs/conf.py
conf.py
py
864
python
en
code
0
github-code
6
5308859090
# 예상등수 A , 실제등수 B, 불만도 = |A-B| # 불만도 최소값 -> 학생등수매기기 # 1 5 3 1 2 -> sorting 1 1 2 3 5 # 1 2 3 4 5 n = int(input()) guess_rank = [int(input()) for _ in range(n)] rank = [i for i in range(1, n+1)] worst_score = 0 for a, b in zip(rank, sorted(guess_rank)): worst_score += abs(a - b) print(worst_score)
louisuss/Algorithms-Code-Upload
Python/FastCampus/greedy/2012.py
2012.py
py
352
python
en
code
0
github-code
6
71455581947
import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression, LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.neural_network import MLPClassifier from sklearn.metrics import accuracy_score, roc_auc_score, roc_curve import matplotlib.pyplot as plt from pathl...
anmol6536/binder_project
hw6_comparing_models.py
hw6_comparing_models.py
py
4,387
python
en
code
0
github-code
6
42455383816
from model.contact import Contact from model.group import Group import random def test_add_contact_to_group(app, db, check_ui): # checks whether there are contacts available. If not - create one if len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname="Name for deletion")) # check ...
1kpp/python_trainnig
test/test_add_contact_to_group.py
test_add_contact_to_group.py
py
1,312
python
en
code
0
github-code
6
21881567037
# app.py from fastapi import FastAPI, HTTPException from pydantic import BaseModel from fastapi.middleware.cors import CORSMiddleware from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB import pandas as pd import uvicorn app = FastAPI() # This middleware is requir...
pnavab/tweet-sentiment-NLP
app.py
app.py
py
2,079
python
en
code
0
github-code
6
43391996015
import os; from random import shuffle def create_data_sets(): imagesPath = "ImagesTrain_Sorted/" textFilesPath = "" classifiers = {} classifierIndex = 0 images_per_folder = [] for folderName in os.listdir(imagesPath): classifiers.update({folderName: classifierIndex}) classifier...
lealex262/Machine-Learned-Image-Classification-
createdatasets.py
createdatasets.py
py
1,519
python
en
code
1
github-code
6
21312898418
import math class Point: """ Represents a point in 2-D geometric space """ def __init__(self, x=0, y=0): """ Initializes the position of a new point. If they are not specified, the point defaults to the origin :param x: x coordinate :param y: y coordinate ...
matthewkirk203/intermediatePython
python/day1/testLiveTemplate.py
testLiveTemplate.py
py
1,363
python
en
code
0
github-code
6
2794147606
#ENTRENAMIENTO DE RED CONVOLUCIONAL 2D - CLASIFICACION HSI #Se utiliza PCA para reduccion dimensional y estraccion de caracteristicas espectrales. A la red convolucional se introduce #una ventana sxs de la imagen original para la generacion de caracteristicas espaciales a partir de la convolucion. #Se utiliza como ca...
davidruizhidalgo/unsupervisedRemoteSensing
2_Redes Supervisadas/hsi_CNN2D.py
hsi_CNN2D.py
py
4,213
python
es
code
13
github-code
6
19399678889
class Solution: def backspaceCompare(self, S: str, T: str) -> bool: s = self.simulate(S) t = self.simulate(T) # print(s, t) return s == t def simulate(self,S): arr = list(S) result = [] for each in arr: if each == '#': if len(r...
Yigang0622/LeetCode
backspaceCompare.py
backspaceCompare.py
py
507
python
en
code
1
github-code
6
27259910110
"""We are the captains of our ships, and we stay 'till the end. We see our stories through. """ """617. Merge Two Binary Trees """ class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None class Solution: def mergeTrees(self, t1, t2): if not ...
asperaa/back_to_grind
Trees/merge_trees.py
merge_trees.py
py
537
python
en
code
1
github-code
6
6018276646
# https://pypi.org/project/emoji/ from PIL import Image, ImageDraw, ImageFont import emoji print(emoji.demojize('Python 👍')) print(emoji.emojize("Python :thumbs_up:")) # 创建一个空白的RGBA模式图像 img = Image.new('RGBA', (200, 200), color='white') # 获取Emoji字符的Unicode字符串 emoji_unicode = emoji.emojize(':thumbs_up:'...
Yuelioi/Program-Learning
Python/modules/utils/_emoji.py
_emoji.py
py
1,542
python
en
code
0
github-code
6
42411367389
# -*- coding: utf-8 -*- # # File: BPDProgramable.py # # Copyright (c) 2011 by Conselleria de Infraestructuras y Transporte de la # Generalidad Valenciana # # GNU General Public License (GPL) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public...
carrascoMDD/gvSIG-bpd
gvSIGbpd/BPDProgramable.py
BPDProgramable.py
py
4,774
python
en
code
0
github-code
6
25055000504
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib, urllib2 from urllib2 import HTTPError class HttpRequest(object): ''' HTTP 호출 ''' def param_encode(self, params): return urllib.urlencode(params) def request(self, request_url, request_type="GET", params=None, header...
developer-sdk/oozie-webservice-api
oozie-webservice-api/oozie/httputil2.py
httputil2.py
py
1,335
python
en
code
1
github-code
6
2714558577
#상속 # : 클래스들이 중복된 코드를 제거하고 유지보수를 # 편하게 하기 위해 사용. # 부모 클래스 class Monster: def __init__(self,name, health, attack): self.name = name self.health = health self.attack = attack def move(self): print(f"[{self.name}]지상에서 이동하기") # 자식 클래스 class Wolf(Monster): pass class Shark(Monste...
Monsangter/pythonweb
python_basic/myvenv/chapter8/04.상속.py
04.상속.py
py
731
python
ko
code
0
github-code
6
12746754821
import requests from bs4 import BeautifulSoup as bs import smtplib URL = "https://www.amazon.in/9500-15-6-inch-i7-10750H-NVIDIA1650-Graphics/dp/B08BZPRWR5/ref=sr_1_4?dchild=1&keywords=Dell+XPS+15&qid=1602254565&sr=8-4" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (K...
Programmer-X31/PythonProjects
Project Amazon Scraper/main.py
main.py
py
1,679
python
en
code
0
github-code
6
39485139620
#!/usr/bin/env python3 """lc3_achi.py -- achivements module""" import time import dataset from flask import session lc3_achivements = [{'id': 0, 'hidden': False, 'title': 'Sleepless', 'desc': 'Submit a correct flag at night'}, {'id': 3, 'hidden': False, 'title': 'CTF Initiate', 'desc': 'Solve one ...
Himanshukr000/CTF-DOCKERS
lc3ctf/examples/lc3achi/lc3achi.py
lc3achi.py
py
922
python
en
code
25
github-code
6
24199870907
# -*- coding: utf-8 -*- """ Created on Fri Jul 12 15:21:43 2019 @author: Administrator """ class Solution: def uniquePathsWithObstacles(self, obstacleGrid): m = len(obstacleGrid) if not m: return n = len(obstacleGrid[0]) memo = [[0 for _ in range(n)] f...
AiZhanghan/Leetcode
code/63. Unique Paths II.py
63. Unique Paths II.py
py
1,255
python
en
code
0
github-code
6
73590131389
"""__author__ = 余婷""" # 1.文本文件相关的操作 def get_text_file_content(file_path): """ 获取文本文件的内容 :param file_path: 文件路径 :return: 文件的内容 """ try: with open(file_path, 'r', encoding='utf-8') as f: return f.read() except FileNotFoundError: print('Error:文件不存在!!!') ret...
gilgameshzzz/learn
day10Python_pygame/day10-管理系统/system/fileManager.py
fileManager.py
py
960
python
zh
code
0
github-code
6
4041441314
__author__ = 'yueli' import numpy as np import matplotlib.pyplot as plt from config.config import * mrList = np.linspace(1, 13, 13) negativeList = [-1, -1, -10, -10, -1, -1, -1, -10 ,-1, -1, -1, -10, -10] noMapReplyList = np.linspace(0, 0, 13) rlocSet1 = [-10, 1, 1, 1, -10, -10, 1, 1, 1, -10, 1, 1, 1] rlocSet2 = [-10,...
hansomesong/TracesAnalyzer
Plot/Plot_variable_MR/Plot_variable_MR.py
Plot_variable_MR.py
py
1,248
python
en
code
1
github-code
6
35031212514
import io import webbrowser video_links_dict = {} video_links = open("C:\\users\lcrum\documents\mypythonprograms\musicvideolinks.txt", "r") for i in video_links: var = video_links.readline() varKey, varExcess, varVal = var.partition(' ') video_links_dict[varKey] = varVal video_links.close def song_selec...
linseycurrie/FilmMusicVideos
MusicVideos.py
MusicVideos.py
py
893
python
en
code
0
github-code
6
18266500320
"""This is Slate's Linear Algebra Compiler. This module is responsible for generating C++ kernel functions representing symbolic linear algebra expressions written in Slate. This linear algebra compiler uses both Firedrake's form compiler, the Two-Stage Form Compiler (TSFC) and COFFEE's kernel abstract syntax tree (AS...
hixio-mh/firedrake
firedrake/slate/slac/compiler.py
compiler.py
py
22,060
python
en
code
null
github-code
6
6018330446
from playwright.sync_api import sync_playwright def test_props(): with sync_playwright() as p: browser = p.chromium.launch(headless=False) page = browser.new_page() page.goto("https://image.baidu.com/") # 上传文件 file_path = r"C:/Users/yl/Desktop/1.png" pag...
Yuelioi/Program-Learning
Python/modules/web/Playwright/元素操作.py
元素操作.py
py
987
python
en
code
0
github-code
6
30502016476
from django.urls import path from . import views app_name = 'home' urlpatterns = [ path('', views.index, name='index'), path('login/', views.login_view, name='login'), path('registration/', views.registration, name='registration'), path('logout/', views.logout_view, name='logout'), path('profile/'...
Arctik124/tekken_league
home/urls.py
urls.py
py
434
python
en
code
0
github-code
6
21833663632
from flask import Flask, render_template, request from werkzeug.utils import redirect from scrapper import weather_search app = Flask("Weather Scrapper") @app.route("/") def home(): area = request.args.get('area') if area: weather_element = weather_search(area) print(weather_eleme...
Sunggjinn/weather-closet
app.py
app.py
py
509
python
en
code
0
github-code
6