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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
19844055653 |
import os
class Memento:
def __init__(self, file, content):
self.file = file
self.content = content
class FileWriterUtility:
def __init__(self, file):
self.file = file
self.content = ""
self.states = []
def write(self, string):
self.content += string
def save(self):
if len(self.states) == 4:
... | Fernando1225/UADER_IS2_PEREZ | src/patrones de comportamiento/TP3_5_taller_memory.py | TP3_5_taller_memory.py | py | 2,185 | python | es | code | 0 | github-code | 36 |
70105956265 | #%%
import torch
from torch.utils.data import Dataset, DataLoader
import glob
from sklearn.model_selection import train_test_split
labeled_dir = "D:/Images_segmentation/Ellipse/pseudo_training/6_images_pt_512"
mask_dir = "D:/Images_segmentation/Ellipse/pseudo_training/6_masks_pt_512"
unlabeled_dir = "D:/Images_nanoma... | lucasdegeorge/NW_SemSeg | dataloader.py | dataloader.py | py | 2,241 | python | en | code | 0 | github-code | 36 |
719866394 | # -*- coding: utf-8 -*-
from Acquisition import aq_base
from plone.app.contenttypes.testing import PLONE_APP_CONTENTTYPES_FIXTURE
from plone.app.discussion.interfaces import IDiscussionSettings
from plone.app.testing import FunctionalTesting
from plone.app.testing import PLONE_FIXTURE
from plone.app.testing import Plon... | collective/collective.honeypot | collective/honeypot/testing.py | testing.py | py | 3,337 | python | en | code | 3 | github-code | 36 |
72170371625 | import streamlit as st
from streamlit_lottie import st_lottie
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from lightgbm import LGBMClassifier
from catboost import CatBoostClassifier
import json
import joblib
import pickle
import shap
from webapp.pred_pipeline_user_input_... | dagartga/Boosted-Models-for-Parkinsons-Prediction | streamlit_app.py | streamlit_app.py | py | 17,417 | python | en | code | 0 | github-code | 36 |
6273981963 | import os
from tests.e2e.terraform.alicloud.testing import _test_template
root = os.path.dirname(os.path.abspath(__file__))
tf_plan_path = os.path.join(root, "main.tfplan")
tpl = {
"ROSTemplateFormatVersion": "2015-09-01",
"Resources": {
"alicloud_slb_acl.listener": {
"Type": "ALIYUN::SLB... | aliyun/alibabacloud-ros-tool-transformer | tests/e2e/terraform/alicloud/slb_listener/test_template.py | test_template.py | py | 2,146 | python | en | code | 16 | github-code | 36 |
40901959216 | import zorg
import time
def work(my):
my.speech.start()
my.speech.set_voice(1)
my.speech.speak("Upgrade in progress")
count = 0
while True:
my.speech.speak(count)
print(count)
count = count + 1
# Wait 1 second before doing it again
time.sleep(1)
robot ... | zorg/zorg-emic | examples/emic_example.py | emic_example.py | py | 756 | python | en | code | 3 | github-code | 36 |
37834490417 | from os import path
import os, subprocess, os, shutil, re
def main():
base=path.dirname(path.dirname(__file__))
# Create config if it doesn't exist
if not path.exists(path.join(base, "config")):
shutil.copy(path.join(base, "config.dist"), path.join(base, "config"))
# Read the config
... | hafriedlander/idea2art-aio | scripts/install_or_update.py | install_or_update.py | py | 2,057 | python | en | code | 27 | github-code | 36 |
70437779623 | import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton, QVBoxLayout, QWidget, QFileDialog, QTextEdit
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix
c... | kgurudarshan/Heart-Failure-Prediction | UI.py | UI.py | py | 2,907 | python | en | code | 0 | github-code | 36 |
73243811305 | def get_functions_root(f, x0: float, alpha: float, eps: float, maxiter: int) -> tuple:
"""
Get the root of the function f.
:param f: The function
:param x0: Starting point
:param alpha: Parameter of searching speed
:param eps: Acceptable error
:param maxiter: Maximum number of iterations
... | OlafSwiac/QEcon | src/Problem Set 1/Task2.py | Task2.py | py | 2,058 | python | en | code | 0 | github-code | 36 |
20115366362 | #Faturamento mensal por estado
fat = {
'SP': 67836.43,
'RJ': 36678.66,
'MG': 29229.88,
'ES': 27165.48,
'Outros': 19849.53
}
#Calcula o faturamento total da distribuidora
faturamento_total = sum(fat.values())
#Calcula o percentual de cada estado no faturamento total
percent = {estado: faturamento /... | jotapedz/jobrotation | questoes2a5/questao4.py | questao4.py | py | 510 | python | pt | code | 0 | github-code | 36 |
955558812 | pkgname = "python-cairo"
pkgver = "1.25.0"
pkgrel = 0
build_style = "python_module"
hostmakedepends = ["pkgconf", "python-setuptools"]
makedepends = ["cairo-devel", "python-devel"]
checkdepends = ["python-pytest"]
depends = ["python"]
pkgdesc = "Python bindings for the Cairo graphics library"
maintainer = "q66 <q66@chi... | chimera-linux/cports | main/python-cairo/template.py | template.py | py | 815 | python | en | code | 119 | github-code | 36 |
8986849807 | from winstealer import *
import json
winstealer_script_info = {
"script": "Vision Tracker",
"author": "bckd00r",
"description": "Tracks enemy invisible objects and clones",
}
show_clones, show_wards, show_traps, ward_awareness = None, None, None, None
blue_to_side_brush = {
"clickPosition": Vec3(2380... | 8C/Xopher-lol | GameplayScripts/vision_tracker.py | vision_tracker.py | py | 8,011 | python | en | code | 14 | github-code | 36 |
17448102081 | from lumicube.standard_library import *
# needs to be imported now and into your pythin environment
import cffi
# Enter the address or hostname of your lumicube
cube = None
if isRunningOnCube():
# connect locally if running locally
cube = LumiCube();
else:
# connect to my remote cube if not running loc... | paultough/lumicube | speaker.py | speaker.py | py | 1,053 | python | en | code | 0 | github-code | 36 |
34609629578 | """
871. Minimum Number of Refueling Stops
"""
def min_refuels_dfs(target, stations, fuel, pos):
"""
Naive depth first search - try all available possibilities recursively.
Paramters
---------
target : Target distance to reach.
stations : Each station contains (position, fuel).
fuel : The ... | wuihee/data-structures-and-algorithms | programming-paradigm/dynamic_programming/min_max_path/min_refuels.py | min_refuels.py | py | 3,545 | python | en | code | 0 | github-code | 36 |
2846448684 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 30 17:52:31 2018
@author: khanhdeux
"""
import numpy as np
import matplotlib.pyplot as plt
from lib import plot_decision_regions
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
def sigmoid(z):
... | khanhdeux/ml | logisticRegression.py | logisticRegression.py | py | 3,857 | python | en | code | 0 | github-code | 36 |
21756497537 | # parallel is the key
# if it's not parallel , i don't yet know how to solve it
while 1:
try:
data = [int(i) for i in input().split()]
# there are two point , a and b
a_x , a_y , b_x , b_y = data
#check if a and b is vertical or horizontal
if a_x == b_x:
side_le... | nikita-sunyata/codeforces | 459A/459A.py | 459A.py | py | 1,071 | python | en | code | 0 | github-code | 36 |
27037952147 | import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import torch
import os
def plot_pcu(vector):
fig = plt.figure()
ax = plt.axes(projection='3d')
xdata = vector[:, 0]
ydata = vector[:, 1]
zdata = vector[:, 2]
ax.scatter3D(xdata, ydata, zdata, cmap='Greens')
plt.... | AbdullrahmanHMD/TransformersFor3dPointCLouds | utils.py | utils.py | py | 1,284 | python | en | code | 0 | github-code | 36 |
37268264175 | import html
from telegram import Chat, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode, Update
from telegram.error import BadRequest, Unauthorized
from telegram.ext import (
CallbackContext,
CallbackQueryHandler,
CommandHandler,
Filters,
MessageHandler,
run_async,
)
from telegram.utils.he... | Mizo-Noob-Developer/Sangtei | Sangtei/modules/reporting.py | reporting.py | py | 11,411 | python | en | code | null | github-code | 36 |
22636055069 | import os
import functools
import copy
import mimetypes
import urllib.parse
import email
import logging
import tracemalloc
import feedparser
from lxml import etree # nosec B410
logger = logging.getLogger(__name__)
# Configure the XML parser as securely as possible since we're parsing XML from
# untrusted sources:
... | rpatterson/feed-archiver | src/feedarchiver/utils.py | utils.py | py | 8,034 | python | en | code | 2 | github-code | 36 |
25532345794 | from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
import vk_api
from PIL import Image,ImageOps, ImageDraw,ImageFont
import requests
from io import BytesIO
import requests
token='27b7ab9bb881978742286fd17cd604145d22f365a8d2f8d8e6bcb149fe87cb86d4aac1e7671f1b43ad0a6'
vk = vk_api.VkApi(token=token)
ses_api= v... | kiritodyat/my-bot-for-vk | get.py | get.py | py | 3,032 | python | en | code | 0 | github-code | 36 |
26833501385 | file = open('day10.txt')
cmds = [line.strip() for line in file]
file.close()
cycle = 1
process_finish = 1
i = 0
x = 1
cycle_check = [40*n+20 for n in range(6)]
strengths = 0
#CPU clock
while cycle <= cycle_check[5]:
if process_finish == cycle:
if i > 0 and cmds[i-1].split()[0] == "addx":
x = x +... | MusicMan241504/adventofcode | day10.py | day10.py | py | 624 | python | en | code | 2 | github-code | 36 |
10408549623 | import numpy as np
import math
import scipy
from stl import mesh
from mpl_toolkits import mplot3d
from matplotlib import pyplot
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
from pyquaternion import Quaternion
equidistant_step_size = 3
p... | manuelEAProject/EAProject | stl_preprocessing_Wenzel.py | stl_preprocessing_Wenzel.py | py | 101,321 | python | en | code | 0 | github-code | 36 |
30303644357 | #Import Sleeper Functions
import SleeperFunctions.sleeperfunctions as sleeperData
#Import Keep,Trade,Cut Functions
import KeepTradeCutFunctions.KTCfunctions as KTCdata
import pandas as pd
from UserLeagueClass.user_league_info_class import user_league_info
from UserLeagueClass.user_league_users_class import user... | jpagel1/Sleeper_KTC_Streamlit_Version | UserLeagueClass/user_sleeperleague_class.py | user_sleeperleague_class.py | py | 15,793 | python | en | code | 0 | github-code | 36 |
31097536057 | from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from pytesserac... | akash-attri/legality | crawler.py | crawler.py | py | 3,557 | python | en | code | 0 | github-code | 36 |
3289421742 | """Automatically initialize variables."""
from __future__ import division
import textwrap
from pyomo.core.base.var import Var
from pyomo.core.kernel.numvalue import value
from pyomo.core.plugins.transform.hierarchy import IsomorphicTransformation
from pyomo.util.plugin import alias
class InitMidpoint(IsomorphicTran... | igorsowa9/vpp | venv/lib/python3.6/site-packages/pyomo/contrib/preprocessing/plugins/init_vars.py | init_vars.py | py | 2,978 | python | en | code | 3 | github-code | 36 |
38802287949 | #!/usr/bin/python3
import logging
import sys
from scapy.all import *
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
def parsePacket(packet):
if not packet.haslayer("TCP") or not packet.haslayer("Raw"):
return
# Return if packet doesn't use HTTP protocol or isn't a GET request
if b'HT... | TateRCXVII/4440-NetSec | attack2.py | attack2.py | py | 762 | python | en | code | 0 | github-code | 36 |
29714851942 | import socket
# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to a specific IP and port
host = '0.0.0.0' # Use 0.0.0.0 to listen on all available interfaces
port = 86 # Choose a port number for the communication
server_socket.bind((host, port))
# Star... | NathanArunaaa/E.L.A.R.T-Robot-Framework | Ap_SensorConnection/Receiver-S.py | Receiver-S.py | py | 607 | python | en | code | 2 | github-code | 36 |
26409051759 | def test_2_wei_bag_problem1(weight, value, bagweight):
#明确dp数组含义,dp[i][j]表示从序号为[0,i]的物品中任选放进容量为j的书包达到的最大价值
dp = [[0] * (bagweight+1) for _ in range(len(weight))]
#初始化第一行第一列
#第一列是背包容量为0的时候 所以价值都应该初始化为0
#第一行是只能放物品0的时候,所以如果背包容量允许,价值就是物品0的价值,容量不允许,就是0
for j in range (bagweight + 1):
if... | lpjjj1222/leetcode-notebook | 0-1背包二维数组.py | 0-1背包二维数组.py | py | 1,927 | python | zh | code | 0 | github-code | 36 |
26793988072 | from django.shortcuts import render
from django.http import HttpResponse
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
from surprise import Reader, Dataset, SVD
from surprise.model_selection import KFold
import pickl... | yadavgaurav251/Context-Aware-Recommender | UI/rec/views.py | views.py | py | 22,276 | python | en | code | 19 | github-code | 36 |
3212721770 | import re
from itertools import groupby
from operator import itemgetter
def part1(rows):
result = 0
for row in rows:
_, identifier, real = id_if_real(row)
if real:
result += identifier
return result
def part2(rows):
for row in rows:
name, identifier, real = id_if_... | heijp06/AoC-2016 | day04/lib.py | lib.py | py | 1,283 | python | en | code | 0 | github-code | 36 |
71234329065 | #!/usr/bin/env python
# coding: utf-8
# In[12]:
# Faça um Programa que leia um vetor de 5 números inteiros e mostre-os.
lista1=[]
num1 = input ("Digite um numero inteiro.")
num2= input ("Digite outro numero inteiro.")
num3 = input ("Digite mais um numero inteiro.")
num4 = input ("Digite mais outro numero i... | evelynmartins/Exercicios-lista-python | Exercícios - Lista.py | Exercícios - Lista.py | py | 25,474 | python | pt | code | 0 | github-code | 36 |
4676474414 | #!/usr/bin/env python3
"""Module defines `filter_datum` function
"""
import logging
import mysql.connector
from os import environ
import re
from typing import List
PII_FIELDS = ("name", "email", "phone", "ssn", "password")
class RedactingFormatter(logging.Formatter):
""" Redacting Formatter class
"""
... | leykun-gizaw/alx-backend-user-data | 0x00-personal_data/filtered_logger.py | filtered_logger.py | py | 3,115 | python | en | code | 0 | github-code | 36 |
26317282313 | import base64
import datetime
import glob
import logging
import os
import re
import time
import types
from importlib import util
from random import Random, shuffle
import toml
import yaml
from kapitan import cached, defaults, utils
from kapitan.errors import CompileError
from six import string_types
logger = logging.... | kapicorp/kapitan | kapitan/inputs/jinja2_filters.py | jinja2_filters.py | py | 6,140 | python | en | code | 1,719 | github-code | 36 |
18252140550 | import random, json
def create_random_graph(n, connectivity=2):
# Creates a random potentially disjoint directed graph of
# a defined number of nodes (n) and connectivity
graph = {x:[] for x in range(n)}
for _ in range(n*connectivity):
graph[random.randint(0,n-1)].append(random.randint(0,n-1))
retur... | frank-lynam/self-pruning-spanning-tree | spst.py | spst.py | py | 2,818 | python | en | code | 0 | github-code | 36 |
34796837508 | # load packages
import pandas as pd
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import MaxNLocator
from scipy.optimize import curve_fit
from tqdm import tqdm
from scipy.signal import find_peaks
plt.close('all')
#%% Define functions used in this code
... | meaton212/Raman_Code_Analysis | Python Code/RamanAnalysis_nanomaterials.py | RamanAnalysis_nanomaterials.py | py | 42,378 | python | en | code | 0 | github-code | 36 |
41924656937 | import json # JSON modülünü içe aktar
from kafka import KafkaConsumer # kafka kütüphanesinden KafkaConsumer sınıfını içe aktar
kafka_bootstrap_servers = 'localhost:9092' # Kafka başlangıç sunucularını belirle
kafka_topic = 'your_kafka_topic' # Kafka konusunu belirle
consumer = KafkaConsumer( # KafkaConsumer nes... | sumeyyenacar/Kafka-CDC-Producer-Consumer-Mongodb-Project | consumer/tuketici.py | tuketici.py | py | 904 | python | tr | code | 0 | github-code | 36 |
71075424425 | class Solution:
def minLength(self, s: str) -> int:
stack = []
for n in s:
if stack and (stack[-1] + n == 'AB' or stack[-1] + n == "CD"):
stack.pop()
else:
stack.append(n)
return len(stack)
| nango94213/Leetcode-solution | 2696-minimum-string-length-after-removing-substrings/2696-minimum-string-length-after-removing-substrings.py | 2696-minimum-string-length-after-removing-substrings.py | py | 291 | python | en | code | 2 | github-code | 36 |
28136082705 | # coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
from flask i... | OctoPrint/OctoPrint-Netconnectd | octoprint_netconnectd/__init__.py | __init__.py | py | 6,382 | python | en | code | 8 | github-code | 36 |
19090796379 | from __future__ import annotations # postpone evaluation of annotations
import pandas as pd
from itertools import combinations, product, permutations, repeat, chain
import numpy as np
import math
from sklearn.metrics import auc
import pickle
import gzip
from scipy.special import stdtr
from scipy.stats import pearsonr
... | QuantitativeBiology/MiguelThesisPrecisionMed | src/resources/classes.py | classes.py | py | 135,744 | python | en | code | 0 | github-code | 36 |
43288664474 | """
Graph file parsing.
"""
from __future__ import print_function, absolute_import
import sys, re
import subprocess
from dotviewer import msgstruct
from dotviewer.strunicode import forcestr, forceunicode
re_nonword = re.compile(forcestr(r'([^0-9a-zA-Z_.]+)'))
re_plain = re.compile(forcestr(r'graph [-0-9.]+ [-0-9.... | mozillazg/pypy | dotviewer/graphparse.py | graphparse.py | py | 4,897 | python | en | code | 430 | github-code | 36 |
73377146025 | class Solution(object):
def getIntersectionNode(self, headA, headB):
if headA is None or headB is None:
return None
l1 = self.getCount(headA)
l2 = self.getCount(headB)
p1 = headA
p2 = headB
if l1 > l2:
p1 = self.cutDiff(p1, (l1 - l2))
e... | galedr/LeetCodePractice | LinkedList/IntersectionOfTwoLinkedLists_160/answer.py | answer.py | py | 869 | python | en | code | 0 | github-code | 36 |
10603784501 | import pandas as pd
def resize_data_frame(df, size, ratio, threshold):
positive = round(size * ratio)
negative = round(size * (1 - ratio))
df1 = fetch_border_data(df, positive, threshold, True)
df2 = fetch_border_data(df, negative, threshold, False)
return pd.concat([df1, df2])
def fetch_border_... | kakubin/review_vital | utils/review_data.py | review_data.py | py | 1,051 | python | en | code | 0 | github-code | 36 |
74803616744 | import os
os.system('cls')
menu = """
MENU (CRUD)
1.Altas (C)
2.Bajas (D)
3.Consultas (R)
4.Actualizar (U)
5.Reportes (R)
6.Sair
"""
op = None
numcta = []
nombres = []
edades = []
carreras = []
promedios = []
while op != 6:
os.system('cls')
print... | EduardoCGarcia/CursoPython | 17.MenuListas.py | 17.MenuListas.py | py | 3,689 | python | es | code | 0 | github-code | 36 |
7490994611 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
HEADER_TEMPLATE = "templates/stack.h"
SOURCE_TEMPLATE = "templates/stack.c"
def write_header(template, filename, prefix, name, T):
return template.format(filename=filename.replace(".", "_").upper(),
prefix=prefix,
... | ZeronSix/technotrack | CPU/stack_gen.py | stack_gen.py | py | 1,458 | python | en | code | 1 | github-code | 36 |
39277791022 | import os
import tempfile
from PIL import Image
class Generator(object):
def __init__(self, name, defaults):
self.defaults = {
"frame_duration": 50
}
self.defaults.update(defaults)
self.name = name
def generate(self, original_name, input_path, output_dir, options)... | grdaneault/emojigen | api/generators/generator.py | generator.py | py | 1,643 | python | en | code | 0 | github-code | 36 |
40860207729 | import logging
import time
from airhockey.utils import Timeout
class AwaitVideoHandler(object):
SUCCESS = "SUCCESS"
TIMEOUT = "TIMEOUT"
def __init__(self, video_stream, timeout):
self.video_stream = video_stream
self.timeout = timeout
self.logger = logging.getLogger(__name__)
... | peter-svintsitskyi/airhockey | airhockey/handlers/await_video.py | await_video.py | py | 799 | python | en | code | 0 | github-code | 36 |
74321443942 | from datetime import date, datetime
from flask import abort
from apo import app, db
from apo.models import LostReports
# Constants
LOST_REPORTS_SELECT = db.select(LostReports)
def lost_report_locations_output(locations: str) -> list:
if locations is None:
abort(500)
return locations.split(",")
de... | alpha-phi-omega-ez/apoez.org-flask | apo/helpers/lostreports.py | lostreports.py | py | 6,701 | python | en | code | 0 | github-code | 36 |
6255601256 | '''
Escribir un programa que acepte una lista de valores numericos y obtenga su valor maximo sin utilizar la funcion max( )
Entrada: [6,3,9,2,10,31,15,7]
Salida: 31
Reto*, usar los indices y el ciclo FOR (editado)
'''
print("SIN USAR LA FUNCION MAX-----------------------------------------------------------------------... | yonch100/python | proyectojavi - listas/Ejercicio7 - listas.py | Ejercicio7 - listas.py | py | 1,179 | python | es | code | 0 | github-code | 36 |
35563148498 |
from keras.preprocessing import image
from keras.preprocessing.image import load_img, img_to_array
from keras import models
import numpy as np
import matplotlib.pyplot as plt
import os
img_path = 'cats_and_dogs_small/test/cats/cat.1502.jpg'
model_path = '02_cats_and_dogs_small_2.h5'
now_path = os.ge... | yasaisen/try_keras | 02_lab/layer_output.py | layer_output.py | py | 1,981 | python | en | code | 0 | github-code | 36 |
72593481705 | import re
import json
from random import randint
from datetime import datetime
# FORMATTING
############
def format_processo_juridico(legal_process_id): # type: (str) -> (str)
"""
Format an adequately formatted numbers-only Legal Process ID number,
Returns a Legal Process ID number formatted with stan... | brazilian-utils/brutils-python | brutils/legal_process.py | legal_process.py | py | 3,189 | python | en | code | 112 | github-code | 36 |
23993127692 | '''
301. Remove Invalid Parentheses
https://leetcode.com/problems/remove-invalid-parentheses/
'''
from collections import deque
from typing import List
def removeInvalidParentheses(self, s: str) -> List[str]:
# helper to check if the expression is valid
def isValid(expr):
count = 0
for ch i... | asset311/leetcode | strings/remove_invalid_parentheses.py | remove_invalid_parentheses.py | py | 1,459 | python | en | code | 0 | github-code | 36 |
32520390035 | class ContactList(list):
def search(self, name):
"""Return all contacts that contain the
search values in their name"""
matching_contacts = []
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
return matching_contacts
class Contact:
all_contacts = ContactList()
def _... | kerenskybr/python_oop_book | case_study_multiple_inheritance/mail_sender.py | mail_sender.py | py | 987 | python | en | code | 0 | github-code | 36 |
42243645300 | import os, fnmatch, sys
import dill as pickle
import scipy.interpolate as interp
import scipy.optimize as opti
import scipy.constants as constants
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import bead_util as bu
import configuration as config
import transfer_func_util as tf
... | charlesblakemore/opt_lev_analysis | scripts/weigh_beads/weigh_bead_efield.py | weigh_bead_efield.py | py | 5,194 | python | en | code | 1 | github-code | 36 |
37000889100 | T = int(input())
for tc in range(1, T+1):
N = int(input())
parti = [0] + list(map(int, input().split()))
def win(start_val, end_val):
if start_val == end_val:
return start_val
elif start_val == 1 and end_val == 3: #가위, 보
return start_val
elif start_val == 2 a... | ejuun/SWEA | swea0216_11614(CARDGAME).py | swea0216_11614(CARDGAME).py | py | 1,760 | python | en | code | 0 | github-code | 36 |
15681614045 | import logging
import os
import time
# import traceback
import csurpc
import config
__server_address = None
__get_server_address_time = 0
def get_server_address():
return __server_address
def get_server_connect():
global __server_address
global __get_server_address_time
try:
str_server_ad... | csudata/clup-agent | lib/rpc_utils.py | rpc_utils.py | py | 6,001 | python | en | code | 1 | github-code | 36 |
42914797613 | import csv
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
import sklearn
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Flatten, Dense, Activation, Dropout, Lambda, Cropping2D, Conv2D, ... | juandarr/Behavioral-cloning | model.py | model.py | py | 5,823 | python | en | code | 0 | github-code | 36 |
24807681148 | #!/usr/bin/env python
# coding: utf-8
# In[93]:
import numpy as np
import networkx as nx
import pandas as pd
import time
# # Load ca-GrQc
# In[94]:
def load_ca_grqc():
data = pd.read_csv('CA-GrQc.txt', sep="\t", skiprows=3)
records = data.to_records(index=False)
edges = list(records)
G = nx.DiGr... | wxEdward/cs599hw1 | script/problem3.py | problem3.py | py | 10,715 | python | en | code | 0 | github-code | 36 |
31694764573 | # concertTheatre.py
# write a program so that max 100 seats are sold
def getTickets():
while(True): # runs until break is reached
try: # try to get integer
num = int(input("How many in your group? "))
break # leave loop
except (ValueError, NameError):
print("Only... | namntran/2021_python_principles | workshops/4_concertTheatre.py | 4_concertTheatre.py | py | 1,016 | python | en | code | 0 | github-code | 36 |
2113931991 | class Solution:
def weekvalue(self, start: int):
total = 0
for i in range(7):
total += start + i
return total
def totalMoney(self, n: int) -> int:
weeks = n // 7
days = n % 7
curr_start = 1
total = 0
for i in range(weeks):
... | RemcoGoy/LeetCodeSolutions | daily/20231206/main.py | main.py | py | 786 | python | en | code | 0 | github-code | 36 |
11032874568 | """
Given a string, write a function to check if it a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards.
"""
def palindrome_permutation(s):
s = s.lower()
s = s.replace(" ", "")
counts = {}
for i in s:
if i in counts:
counts[i] += 1
else:
counts[i] = ... | tonydelanuez/python-ds-algos | probs/1-4-palindrome-permutation.py | 1-4-palindrome-permutation.py | py | 489 | python | en | code | 0 | github-code | 36 |
7755819569 | from funclib.resources import Resources
from funclib.stamps.stamp import TRANSPARENT, ImageStamp
from PIL import Image, ImageDraw, ImageFont
from PIL.Image import Image as PILImage
class LogoStamp(ImageStamp):
def apply(self, image: PILImage) -> PILImage:
logo = Image.open(Resources.logo_path())
... | microsoft/planetary-computer-apis | pcfuncs/funclib/stamps/branding.py | branding.py | py | 1,709 | python | en | code | 88 | github-code | 36 |
31432419627 | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | andela/wger-sparta | wger/nutrition/signals.py | signals.py | py | 1,609 | python | en | code | 1 | github-code | 36 |
35746929366 | # Python imports
import json
import logging
import sys
# Django imports
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
# Models imports
from api.models.dataset_model import Dataset
from api.models.storagehost_model import StorageHost
from api.models.computationhost_model imp... | yorgomoubayed/m2-thesis-project | dataproc/api/views/input_view.py | input_view.py | py | 10,222 | python | en | code | 0 | github-code | 36 |
15493634163 | import random
def jogar():
print('*'*50)
print('***seja bem vindo ao jogo da forca***')
print('*'*50)
arquivo = open(
"/home/joao/Área de trabalho/Curso/arquivos_programacao/projetos/forca/frutas.txt", "r")
frutas = []
for linha in arquivo:
linha.strip()
frutas.append... | JoaoGabsoares/forca | forca.py | forca.py | py | 1,250 | python | pt | code | 0 | github-code | 36 |
11874793301 | from setuptools import setup
with open('README.md') as reader:
long_description = reader.read()
setup(
author='Jaedson Silva',
author_email='imunknowuser@protonmail.com',
name='ufinder',
version='1.0.0',
description='Search URL paths with UFinder.',
long_description=long_description,
l... | jaedsonpys/ufinder | setup.py | setup.py | py | 1,161 | python | en | code | 1 | github-code | 36 |
23012310751 | import io
import os
import chess
import chess.pgn
import numpy as np
import tensorflow as tf
from absl.testing import absltest
from chess_ai import feature_converter
from chess_ai.datasets.chess_crawl import chess_crawl
_TEST_DATA_DIR = os.path.abspath(
os.path.join(os.path.dirname(__file__), "../tests/testdata"... | waterhorse1/ChessGPT | chess_ai/feature_converter_test.py | feature_converter_test.py | py | 4,229 | python | en | code | 51 | github-code | 36 |
21536350789 | import os, random, time, copy
from skimage import io, transform
import numpy as np
import os.path as path
import scipy.io as sio
import matplotlib.pyplot as plt
from PIL import Image
import sklearn.metrics
import torch
from torch.utils.data import Dataset, DataLoader
import torch.nn as nn
import torch.optim as optim
f... | ShadeAlsha/LTR-weight-balancing | utils/trainval.py | trainval.py | py | 7,324 | python | en | code | 100 | github-code | 36 |
14145252892 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 19:17:44 2020
@author: b
https://www.youtube.com/watch?v=T4nZDuakYlU&list=PLO_fdPEVlfKoHQ3Ua2NtDL4nmynQC8YiS&index=9
Selection de variable
Dnas le module sklearn.module_selection,
on retrouve les transformers et les tests de dépendances
Selecteu... | b846/Data | 4b YT Modele selection.py | 4b YT Modele selection.py | py | 3,976 | python | fr | code | 0 | github-code | 36 |
7659697862 | # It imports the OpenCV library.
import cv2
# It imports the numpy library, and it renames it to np.
import numpy as np
def stackImages(scale, imgArray):
# Getting the number of rows in the array.
rows = len(imgArray)
# Getting the number of columns in the array.
cols = len(imgArray[0])
# It c... | GurjotSinghAulakh/Python-openCV | 8. Contour - Shape Detection/chapter8.py | chapter8.py | py | 7,093 | python | en | code | 0 | github-code | 36 |
23476844064 | import asyncio
from functools import partial
import flet as ft
from loguru import logger
from elite_dangerous_rich_presence.user_controls import (
EliteDangerousOptions,
GeneralOptions,
RichPresenceOptions,
)
from elite_dangerous_rich_presence.util import UiMessages, cancelable
async def close_button(ev... | Lasa2/Elite-Dangerous-Rich-Presence | elite_dangerous_rich_presence/settings_app.py | settings_app.py | py | 3,575 | python | en | code | 25 | github-code | 36 |
4714720771 | import copy
import pathlib
import operator
import textwrap
import itertools
import functools
from termcolor import colored
from clldutils.iso_639_3 import ISO, download_tables
def sprint(text, *args, **kw):
if not isinstance(text, str):
text = '{0}'.format(text)
if args:
text = text.format(*a... | glottolog/pyglottolog | src/pyglottolog/util.py | util.py | py | 3,364 | python | en | code | 20 | github-code | 36 |
44263450633 | __all__ = ["TestCamera"]
import numpy as np
import lsst.afw.cameraGeom as cameraGeom
import lsst.geom as geom
import lsst.afw.geom as afwGeom
class TestCamera(cameraGeom.Camera):
"""A simple test Camera.
Notes
-----
The camera has one ccd with name "0".
That CCD has four amplifiers with names "... | gcmshadow/obs_test | python/lsst/obs/test/testCamera.py | testCamera.py | py | 8,173 | python | en | code | 0 | github-code | 36 |
31179207142 | from rest_framework.response import Response
from rest_framework import status
import random
import math
RESPONSE_FORBIDDEN = Response(
data={
'msg': 'Fobidden',
'status': 403
}, status=status.HTTP_403_FORBIDDEN
)
RESPONSE_NOT_FOUND = Response (
data={
'msg': 'Not Found',
'... | sudo-datluu/runfinity | backend/api/views/const.py | const.py | py | 1,180 | python | en | code | 0 | github-code | 36 |
71858745065 | #!/usr/bin/env python
import rospy
import subprocess
import time
from datetime import datetime
from std_msgs.msg import Float64, String
from time_synchronization.srv import talker1, talker2
class talker_handle(object):
def __init__(self):
# wait until both services will be available in the network
rospy.wait_fo... | zhanibekrysbek/time_synchronization | scripts/main_node.py | main_node.py | py | 987 | python | en | code | 0 | github-code | 36 |
27477035562 | from django.shortcuts import render
from django.shortcuts import render, redirect
from . forms import CreateUserForm, LoginForm, UpdateUserForm, UpdateProfileForm
from . models import Profile
from django.contrib.auth.models import auth
from django.contrib.auth import authenticate, login
from django.contrib.auth.decora... | AdirNoyman/DjangOnAWS_bootcamp2 | appy/lynx/views.py | views.py | py | 3,824 | python | en | code | 0 | github-code | 36 |
72694765545 | ## 함수 선언부
def isQueueFull():
global SIZE, queue, front, rear
if front == (rear+1) % SIZE:
return True
return False
def isQueueEmpty():
global SIZE, queue, front, rear
if front == rear:
return True
return False
def enQueue(data):
global SIZE, queue, front, rear
if isQu... | baejinsoo/algorithm_study | algorithm_study/DataStructure/09_원형큐.py | 09_원형큐.py | py | 935 | python | en | code | 0 | github-code | 36 |
29085658085 | from zone_api.alert import Alert
from zone_api.core.devices.alarm_partition import AlarmPartition
from zone_api.core.zone_event import ZoneEvent
from zone_api.core.action import action, Action
SECURITY_EVENTS = [ZoneEvent.PARTITION_ARMED_AWAY, ZoneEvent.PARTITION_ARMED_STAY,
ZoneEvent.PARTITION_DISA... | yfaway/zone-apis | src/zone_api/core/actions/security_alert_in_vacation_mode.py | security_alert_in_vacation_mode.py | py | 1,651 | python | en | code | 2 | github-code | 36 |
5140060882 | # Turimas "users" masyvas.
# Parašykite funkcijas, kurios atlikas nurodytas užduotis:
# 1. funkcija "filterDogOwers" - kaip argumentą priims masyvą ir duoto masyvo
# atveju grąžins "users", kurie turi augintinį.
# 2. funkcija "filterAdults" - kaip argumentą priims masyvą ir duoto masyvo
# atveju grąžins masyvą su "... | GrigasK/Python-Tasks | Python Tasks/Task 1/main.py | main.py | py | 1,556 | python | lt | code | 0 | github-code | 36 |
18521234605 | '''10_1 K-均值聚类支持函数
2019_11_25
'''
import numpy as np
import math
import random
import matplotlib.pyplot as plt
def loadDataSet(fileName):
dataMat = []
fr = open(fileName)
for line in fr.readlines():
curLine = line.strip().split('\t')
fltLine = list(map(float, curLine))
dataMat.appe... | DonghuiJin/Machine_Learning_In_Action | kMeans_10/kMeans.py | kMeans.py | py | 13,366 | python | zh | code | 1 | github-code | 36 |
71551411944 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/9/9 下午11:19
# @Author : Bear Chao
# @Site : http://blog.nickzy.com
# @File : ultraflightMP.py
# @Software: PyCharm
import requests
url = 'http://139.199.212.48:8080/'
def check_ufmp_status():
r = requests.get(url)
if r.status_code == 200:
... | BearChao/cheduler | tasks/ufmp.py | ufmp.py | py | 375 | python | en | code | 0 | github-code | 36 |
16738098260 | from datetime import datetime
registro = {}
print('='*30,'> Carteira de Trabalho <','='*30)
registro['nome'] = str(input('Digite seu nome:'))
nasc = int(input('Digite seu ano de nascimento: '))
registro['idade'] = datetime.now().year - nasc
registro['ctps'] = int(input('Digite o número da sua carteira de trabalho(0 pa... | TiagoFar/PythonExercises | ex092.py | ex092.py | py | 726 | python | pt | code | 0 | github-code | 36 |
18076214456 | import re
import requests
import json
from requests.exceptions import RequestException
from bs4 import BeautifulSoup
import lxml
def get_page(url):
try:
headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'}
... | sky19890315/PHP-MYSQL-JS | microsky/spider/sp3.py | sp3.py | py | 1,334 | python | en | code | 0 | github-code | 36 |
71878929703 | import requests
from bs4 import BeautifulSoup
from encrypt import *
from typing import Dict
from urllib import parse
import logging
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
"Accept": "text/html,application/... | haowang-cqu/CourseMonitor | login.py | login.py | py | 4,442 | python | en | code | 13 | github-code | 36 |
36121320813 | from typing import Dict
from forte.utils import create_import_error_msg
from forte.common.configuration import Config
from forte.models.ner.conditional_random_field import ConditionalRandomField
try:
import torch
import torch.nn.functional as F
import torch.nn.utils.rnn as rnn_utils
from torch import n... | asyml/forte | forte/models/ner/model_factory.py | model_factory.py | py | 9,176 | python | en | code | 230 | github-code | 36 |
16768433234 |
import requests
def get_goods_id(session, goodsid):
"""查询商品"""
url = "http://49.235.92.12:7005/api/v2/goods/%s"%goodsid
r = session.get(url)
print("查询结果:%s" % r.text)
return r
def add_goods(session,
goodscode="sp_111",
goodsname="商品_test",
**kwargs):
... | aliyaliang/pytest_api | api/goods.py | goods.py | py | 1,527 | python | en | code | 0 | github-code | 36 |
3829181004 |
# 用于实现微信小程序一键开锁
from socket import *
import sys
def get_host_ip():
with socket(AF_INET, SOCK_DGRAM) as s:
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
return ip
def receive():
sock = socket(AF_INET, SOCK_STREAM)
# sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind((get_... | HollowMan6/Lanck-Face-Recognition-Lock-Competition-Backend-Code | Server/Message-Receive.py | Message-Receive.py | py | 829 | python | en | code | 22 | github-code | 36 |
36432077749 | # -*- coding: utf-8 -*-
import unittest
class TestSortByWordLen(unittest.TestCase):
def test_sort(self):
words = ['a', 'bc', 'def']
expected = ['def', 'bc', 'a']
for i in range(len(words) - 1, 0, -1):
for j in range(i):
r = self.cmp_len(words[j], words[j+1])
... | ksomemo/NltkStudy | chapter4/exercises/p10.py | p10.py | py | 567 | python | en | code | 0 | github-code | 36 |
10651061256 | T = int(input())
for tc in range(1,T+1):
lst = list(input())
card = []
ans = ""
S = 13
D = 13
H = 13
C = 13
for i in range(0,len(lst)-2,3):
card.append(lst[i:i+3])
for a in range(len(card)-1):
for b in range(a+1,len(card)):
if card[a] == card[b]:
... | elenaisnanocat/Algorithm | SWEA/swea_4047_영준이의 카드 카운팅.py | swea_4047_영준이의 카드 카운팅.py | py | 786 | python | en | code | 0 | github-code | 36 |
6324925248 | # -*- coding: utf-8 -*-
from sklearn.datasets.samples_generator import make_blobs
from sklearn.cluster import KMeans
if __name__ == '__main__':
x, y = make_blobs(n_samples=200, n_features=2, centers=4, cluster_std=1, center_box=(-10.0, 10.0), shuffle=True, random_state=1)
model = KMeans(n_jobs=-1)
for i i... | GoogleLLP/SGCC-BigData-Exercise | chapter11/exercise18.py | exercise18.py | py | 418 | python | en | code | 6 | github-code | 36 |
15264960014 | from django.core.mail import EmailMessage
def send_mail():
'''Отправлячем уведомление на мою почту'''
email = EmailMessage(
subject = 'Новое сообщение',
body = F'Привет!У нас там новое сообщение',
from_email = 'info@citrom.ru',
to = ("untiwe@gmail.com",)
)
em... | untiwe/citrom_test | aboutus/package.py | package.py | py | 403 | python | ru | code | 0 | github-code | 36 |
36350064958 | # Jack McAllister Student ID #: 001155294
# C950 Data Structures and Algorithms II
# NHP2 TASK 1: WGUPS ROUTING PROGRAM
from package import Package
from truck import Truck
from myDictionary import MyDictionary
import csv
import re
from operator import attrgetter
# Takes a list and two addresses
def checkDistance(do... | JackMcAllister/C950-Data-Structures-and-Algorithms-II | main.py | main.py | py | 11,306 | python | en | code | 0 | github-code | 36 |
12675918404 | class Solution(object):
def __init__(self,list_,length):
self.max_length = length
self.list_ = list_
self.dp = {}
self.memo = {}
def cost(self,start,end):
count = 0
import sys
for i in range(start,end):
count = count +... | Mbathula007/text_editor_formatting | text_justification.py | text_justification.py | py | 1,920 | python | en | code | 0 | github-code | 36 |
15472555384 | from iotutils_neopixel import Neopixel
from colorzero import Color, Hue
import time
ledCount = 10
ledPin = 18
degreeAdjustment = 360/ledCount
neop = Neopixel(ledCount, ledPin)
firstColor = Color("red")
for ledId in range(ledCount):
degree = ledId * degreeAdjustment
neop.setColor(ledId, firstColor + Hue(deg=... | HSSBoston/smart-earring | code/rainbow-dropping.py | rainbow-dropping.py | py | 504 | python | en | code | 0 | github-code | 36 |
1693240144 | from tkinter import *
import pytesseract
import cv2
import pyscreenshot
pytesseract.pytesseract.tesseract_cmd = "D:/Program Files/Tesseract-OCR/tesseract.exe"
window = Tk()
def paint(event):
color = 'black'
x1, y1 = (event.x-1),(event.y-1)
x2, y2 = (event.x+1),(event.y+1)
Canvas1.create_oval(x1, y1, ... | Computer4062/Python-Projects | MathPad/MathPad.py | MathPad.py | py | 4,934 | python | en | code | 0 | github-code | 36 |
8534251773 | from math import*
from tkinter import*
from random import*
root = Tk()
root.title('Метод Монте Карло')
root.geometry('900x900')
label=Label(root, text='Графіки кола та квадрата', font='Arial 15')
label.pack(fill=X)
label1=Label(root, font='Arial 15')
label1.pack(fill=X)
label2=Label(root, font='Arial ... | ola14/labsPYTHON | MonteCarlo.py | MonteCarlo.py | py | 1,243 | python | en | code | 0 | github-code | 36 |
783702878 | import sqlalchemy
from sqlalchemy import MetaData, Table, String, Integer, Column, Text, DateTime, Boolean, BigInteger, ForeignKey, Date,\
SmallInteger
from datetime import datetime
from sqlalchemy import create_engine
# Подключение к серверу PostgreSQL на localhost с помощью psycopg2 DBAPI
engine = create_engine(... | PeyoteWilliams/OrganizerBot | db_create.py | db_create.py | py | 1,355 | python | en | code | 0 | github-code | 36 |
36979473911 | for _ in range(int(input())):
n=int(input())
flag=0
if n>1:
for i in range(2,n+1):
if(n%i)==0:
flag+=1
if(flag==1):
print("yes")
else:
print("no")
| shrijayan/Python | CodeChef/Primality Test.py | Primality Test.py | py | 205 | python | en | code | 0 | github-code | 36 |
4428273426 | # -*- coding: utf-8 -*-
from django.shortcuts import render,redirect
### one-time flash messages
from django.contrib import messages
from django.db.models import Count
from .models import *
def index(request):
return render(request,'login_registration_app/index.html')
def createUser(request):
if request.method != '... | rhuidean/django_review | apps/login_registration_app/views.py | views.py | py | 1,934 | python | en | code | 0 | github-code | 36 |
70447354665 | # 文件读写测试
fileName = 'D:/GitRepository/python/pythonStudy/file.txt'
# 追加写模式
f = open(fileName,'a+')
f.write('\nhello world!!!')
f.close()
f2 = open(fileName, 'r')
content = f2.read()
print(content)
f2.close()
| goaly/python-study-demo | openhome/TestFile.py | TestFile.py | py | 232 | python | en | code | 0 | github-code | 36 |
25305984887 | __author__ = 'diegopinheiro'
from initialization_strategies.initialization_strategy import InitializationStrategy
from common.attribute import Attribute
from common.attribute_converter import AttributeConverter
from common.float_converter_2 import FloatConverter2
from genetic_algorithms.individual import Individual
im... | diegompin/genetic_algorithm | initialization_strategies/data_initialization.py | data_initialization.py | py | 2,950 | python | en | code | 1 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.