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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
5255201326 | import tkinter as tk
import tkinter.ttk as ttk
import DatabaseHandler as Database
import editWindow
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
"""
Input: self - The object containing the frame being called, parent - the parent window of this frame
Output... | ReeceHoffmann/brewing-database | BrewingDB.py | BrewingDB.py | py | 7,422 | python | en | code | 0 | github-code | 50 |
31987027978 | import multiprocessing
from multiprocessing import Manager
from multiprocessing import freeze_support
import os, time, random
import numpy as np
import pandas as pd
from collections import Counter
import csv
process_num = 4
## clear_all_data
fileName_all ="movement-speeds-hourly-new-york-2020-1.csv"
node... | HarryZhao2000/Traffic-Prediction-for-New-York-GNN | Preprocessing/multi_processing.py | multi_processing.py | py | 6,353 | python | en | code | 0 | github-code | 50 |
20916537422 | import numpy as np
import pygame
import sys
import time
edge_norm = 80
pos_vec = np.array([350, 500])
point2_vec = np.array([-100, 0])
point2 = pos_vec + point2_vec
def recursive_shape_generator(RotMtx, point, vector, point2, point_array): #initial vector is the common edge
new_vec = np.matmul(RotMtx, vector) #... | tnycnsn/Recursive-Equilaterals | recursive equilaterals/recursive_equilaterals.py | recursive_equilaterals.py | py | 1,765 | python | en | code | 0 | github-code | 50 |
25275703866 | from django import forms
class AddTagForm(forms.Form):
movie_id = forms.CharField(
widget=forms.HiddenInput(),
required=False
)
tag = forms.CharField(
label='Etiqueta', required=True,
help_text='Etiqueta nueva o existente.'
)
| moz667/homodaba | homodaba/homodaba/forms.py | forms.py | py | 276 | python | en | code | 3 | github-code | 50 |
6411731853 | import demistomock as demisto
from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
from collections import OrderedDict # noqa
import json # noqa
import traceback # noqa
from typing import Dict, Any # noqa
# Disable insecure warnings
DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ" # ISO8601 forma... | demisto/content | Packs/SecneurXAnalysis/Integrations/SecneurXAnalysis/SecneurXAnalysis.py | SecneurXAnalysis.py | py | 35,608 | python | en | code | 1,023 | github-code | 50 |
28964570804 | from statistics import median
import pandas as pd
pd.options.mode.chained_assignment = None
import matplotlib.pyplot as plt
df = pd.read_csv('train.csv')
#print(df.info(verbose=True))
columnsAsNumericValues = df.select_dtypes(include=['number']).columns # this line of code is to print the columns that has numer... | rriossigma/ProyectoFinal | ProyectoFinal.py | ProyectoFinal.py | py | 3,018 | python | en | code | 0 | github-code | 50 |
30255676732 | from flask import url_for
from flask_testing import TestCase
from application import app
from application.routes import backend
import requests_mock
test_region = {
"region_id": 1,
"region_name": "Bristol",
"region_property_address": "Flat 12 A",
"region_price": "200.000",
"description": 'Best pric... | MutluToy/DfE6_Final_Project | frontend/tests/test_unit.py | test_unit.py | py | 2,508 | python | en | code | 0 | github-code | 50 |
30500759861 | from django.urls import path, include
from . import views
urlpatterns = [
path('', views.ProjectListView.as_view(), name='project-list'),
path('<int:pk>/', views.ProjectDetailView.as_view(), name='project-detail'),
path('create/', views.CreateProjectView, name='create-project'),
path('update/<int:id>',... | Yshaq/project-showcase-site | projects/urls.py | urls.py | py | 450 | python | en | code | 0 | github-code | 50 |
27953728060 | """
Custom marshmallow validators.
"""
import socket
from typing import List
from marshmallow import ValidationError
def validate_ip(ip_str: str):
"""Check if the given string is a valid IPv4 address."""
try:
socket.inet_aton(ip_str)
except socket.error:
raise ValidationError('Invalid I... | varrrro/shipyard-server | shipyard/validators.py | validators.py | py | 586 | python | en | code | 2 | github-code | 50 |
26878911655 | name_of_town = input()
holiday_package = input()
is_vip = input()
days_of_stay = int(input())
total_price = 0
price_per_day = 0
if name_of_town == 'Bansko' or name_of_town == 'Borovets':
if holiday_package == 'noEquipment':
price_per_day = 80
total_price = days_of_stay * price_per_day
if is... | ivocostov/SoftUni | Python/01. Python Basics Course/PB - Exams/Programming Basics Online Exam - 6 and 7 July 2019/03_travel_agency.py | 03_travel_agency.py | py | 1,360 | python | en | code | 2 | github-code | 50 |
25124698026 | #!/usr/bin/env python3
import torch
def gradient_penalty(d_real, y):
if not d_real.requires_grad:
return torch.tensor(0., device=d_real.device)
outputs = [d_real]
gradients = torch.autograd.grad(
outputs=outputs,
inputs=y,
grad_outputs=list(map(lambda t: torch.ones(
... | calvinpelletier/ai_old | loss/reg.py | reg.py | py | 584 | python | en | code | 0 | github-code | 50 |
41872307265 | from flask import Flask, request, redirect, render_template, flash
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://build-a-blog:locker@localhost:8889/build-a-blog'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)... | Emrichardsone/build-a-blog | main.py | main.py | py | 2,076 | python | en | code | 0 | github-code | 50 |
16691529274 | class Solution:
def reverseVowels(self, s: str):
"""
@param s: a string
@return: reverse only the vowels of a string
"""
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
ls = list(s)
l, r = 0, len(ls) - 1
while l < r:
while l < r... | AiRanthem/LintCode | Python/1282翻转字符串中的元音字母.py | 1282翻转字符串中的元音字母.py | py | 700 | python | en | code | 1 | github-code | 50 |
4150485572 | from mscn.util_common import *
def encode_samples(tables, samples, table2vec, added_tables = None):
samples_enc = []
for i, query in enumerate(tables):
samples_enc.append(list())
if added_tables == None:
new_tables = set()
else:
new_tables = set(added_tables[i]... | postechdblab/learned-cardinality-estimation | MSCN/mscn/util_mscn.py | util_mscn.py | py | 5,097 | python | en | code | 13 | github-code | 50 |
18445530243 | import random
import pandas as pd
import numpy as np
import pprint
from ObjectiveFunctions import count_nodes_objective_func
class Wildcards:
def __init__(self, phenotype, wildcard_symbol = '🌟'):
self.wildcards = []
self.wildcard_symbol = wildcard_symbol
self.fitness = -1
self.p... | JHludwolf/Optimizacion_y_MetahuristicasII | Final Project/Wildcards.py | Wildcards.py | py | 1,719 | python | en | code | 0 | github-code | 50 |
41614763940 | '''
Created on Aug 29, 2013
@author: tbowker
'''
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from registerweb import views
from registerweb import pages
urlpatterns = patterns('',
url(r'^demo/login/$', pages.LoginPage.as_view()),
url(r'^demo/landing... | mauidev/django_register | register/registerweb/urls.py | urls.py | py | 726 | python | en | code | 3 | github-code | 50 |
6274092704 | from PyQt4.QtGui import *
from re import search
from os import system,geteuid,getuid
from Core.Settings import frm_Settings
from Modules.utils import Refactor
from subprocess import Popen,PIPE
from scapy.all import *
class frm_Probe(QMainWindow):
def __init__(self, parent=None):
super(frm_Probe, self).__i... | 84KaliPleXon3/3vilTwinAttacker | Modules/ModuleProbeRequest.py | ModuleProbeRequest.py | py | 4,215 | python | en | code | 0 | github-code | 50 |
10544505400 | #!/usr/bin/env python3
""" Amazon Business & Tech | Dradabau"""
import random
wordbank= ["indentation", "spaces"]
tlgstudents= ["Aaron", "Andy", "Asif", "Brent", "Cedric",
"Chris", "Cory", "Ebrima", "Franco",
"Greg", "Hoon", "Joey", "Jordan",
"JC", "LB", "Mabel", "Shon", "Pat", "Zach"]
wordba... | DavidRadd/mycode | wordbank.py | wordbank.py | py | 696 | python | en | code | 0 | github-code | 50 |
19538014566 | import json
import time
from utils.api_helper import *
from src.endpoints.auth.auth import *
from src.endpoints.alerts.alerts import *
from utils.asserts import *
from pytest_check import check
from utils.preconditions import *
@pytest.mark.usefixtures("auth")
class TestAlertsApi:
def test_01_create_fault_n... | gerardo-aragon/upre_automation | tests/api/alerts/alerts.py | alerts.py | py | 1,913 | python | en | code | 0 | github-code | 50 |
39519162482 | # 15. Напишите программу, которая принимает на
# вход число N и выдает набор произведений чисел от 1 до N.
# Пример:
# o пусть N = 4, тогда [ 1, 2, 6, 24 ]\
# (1, 1*2, 1*2*3, 1*2*3*4)
# def factorial(num):
# numbers = int(input("Введите число "))
# list = []
# multiplication = 1
# for i in range(1... | misha1potapenko/Python | Homework_phyton/HW6/first.py | first.py | py | 835 | python | ru | code | 0 | github-code | 50 |
29089279204 | from datetime import datetime, timezone
import secrets
import string
import hashlib
import requests
from time import sleep
import logging
root = logging.getLogger()
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s -... | injuxtice/xdr-log_ingestion-health-check | health_check.py | health_check.py | py | 3,028 | python | en | code | 0 | github-code | 50 |
74658565276 | class Solution:
def maxProfit(self, prices: List[int]) -> int:
# method 1
# 因为是股票交易,有时间的因素,所以我们要保证在当前最小的波谷买入,然后在后续的波峰卖出
# 不能用min,是因为有可能整个数组的最小值之后的序列收益很小,所以应该记录当前已遍历的数组的最小值
# if not prices:
# return 0
# else:
# min_now = ... | HoweChen/leetcodeCYH | 121. Best Time to Buy and Sell Stock/main.py | main.py | py | 1,205 | python | en | code | 0 | github-code | 50 |
37152594629 | #########################################################################
# Dusi's Thesis #
# Algorithmic Discrimination and Natural Language Processing Techniques #
#########################################################################
# Reads the sentences f... | MicheleDusi/AlgorithmicDiscrimination_MasterThesis | src/parsers/winogender_templates_parser.py | winogender_templates_parser.py | py | 3,361 | python | en | code | 0 | github-code | 50 |
34454691331 | import numpy as n
ary=[]
nz=5
first=int(input("Enter first number:"))
last=int(input("Enter last number:"))
for i in range(first,last+1):
ary.append(i)
z=n.array(ary)
k=n.zeros(len(z) + (len(z)-1)*(nz))
k[::nz+1]=z
print(k) | Adityachaitu/COGNIZANCE | Task-8/que-1.py | que-1.py | py | 237 | python | en | code | 0 | github-code | 50 |
26396538096 | from DSA_python.pythonds.Graph.Graph import Graph
from english_words import english_words_lower_set as words_set
from pprint import pprint as pp
import re
def buildGraphWordLadder(word1, word2):
"""
:param word1: a from word
:param word2: a to word
:return: a word ladder, class <'graph'>
""... | steve3ussr/PyCharmProject | DSA_python/graph_learn/buildGraph_wordLadder.py | buildGraph_wordLadder.py | py | 1,531 | python | en | code | 0 | github-code | 50 |
36731106635 | #!/usr/bin/env python
import rospy
import actionlib
import math
from move_base_msgs.msg import MoveBaseAction
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist, Vector3
class Master:
"""Master Node
Processes commands from alexa and sends appropriate actions to arduino_motor
... | Transnavigators/TROSnavigator | master/master.py | master.py | py | 9,945 | python | en | code | 2 | github-code | 50 |
72883368795 | from time import sleep
from turtle import Turtle
class Score:
def __init__(self, ball):
self.ball_obj = ball
self.ball = self.ball_obj.ball
self.attempts = 3
self.ball_gone = False
self.game_over = False
def update_score(self, screen, score):
try:
... | ThozamileMad/breakout-game | scoreboard.py | scoreboard.py | py | 2,158 | python | en | code | 0 | github-code | 50 |
13825936865 | import functools
import unittest
import logging
import mox_cpr_delta_mo.__main__ as mox
mox.mora_get_all_cpr_numbers = lambda: ["0101621234", "0202621234"]
mox.mora_update_person_by_cprnumber = lambda fromdate, pnr, changes: None
mox.cpr_get_delta_udtraek = lambda sincedate: {sincedate: {"0101621234": {'fornavn': "Be... | magenta-aps/mox_cpr_delta_mo | tests/test_mox_cpr_delta_mo.py | test_mox_cpr_delta_mo.py | py | 1,054 | python | en | code | 0 | github-code | 50 |
25221893176 | from flask import Flask, render_template, request, redirect, flash
from datetime import datetime, timedelta
import os
import requests
from dotenv import load_dotenv
load_dotenv('.env')
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev123')
@app.template_filter()
def format_datetime(date... | cszhi/alert-dashboard | app.py | app.py | py | 1,828 | python | en | code | 1 | github-code | 50 |
22568536394 | # Import necessary libraries
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from tensorflow import keras
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Dense, Flatten, Reshape, Input, Lambda, Ba... | SSobol77/Perceptron-1 | ls30/ls_30_CVAE.py | ls_30_CVAE.py | py | 4,109 | python | en | code | 3 | github-code | 50 |
20236349401 | from unittest import TestCase
from domain.exceptions import ImageNameException
from domain.value_objects import ImageName
class TestImageName(TestCase):
def test_init_WHEN_valid_value_given_THEN_creates_instance_with_given_value(self) -> None:
valid_value = 'name'
image_name = ImageName(value=va... | fr-mm/blaze_mines_bot | tests/unit/domain/value_objects/test_image_name.py | test_image_name.py | py | 605 | python | en | code | 4 | github-code | 50 |
43729816712 | #!/usr/bin/python3
"""4. Text indentation
a function that prints a text with 2 new lines after
each of these characters: ., ? and :
Prototype: def text_indentation(text):
text must be a string, otherwise raise a TypeError exception with
the message text must be a string
There should be no space at the beginning or at... | Halmouus/alx-higher_level_programming | 0x07-python-test_driven_development/5-text_indentation.py | 5-text_indentation.py | py | 981 | python | en | code | 0 | github-code | 50 |
22840901551 | from .. import runtime
from ..runtime import Environment
from ..runtime.terminal import clear_screen
def _show_terminal_menu(
prompt: str,
items: list[str],
one: bool = False,
indentSize: int = 2
) -> list[int]:
print(prompt)
for index, item in enumerate(items):
print(f"{' ' * indentS... | 2trvl/dotfiles | scripts/crossgui/widgets/menu.py | menu.py | py | 2,559 | python | en | code | 0 | github-code | 50 |
27207820573 | # -*- coding:utf-8 -*-
# @Time : 2021/6/28 14: 23
# @Author : Ranshi
# @File : 面试题 02.06. 回文链表.py
from typing import Optional
class ListNode:
def __init__(self, val: int = 0, _next: Optional["ListNode"] = None):
self.val = val
self.next = _next
class Solution:
def isPalindrome(sel... | Zranshi/leetcode | interview-classic/02.06/main.py | main.py | py | 1,859 | python | en | code | 0 | github-code | 50 |
31058921525 | from dataclasses import dataclass
from pathlib import Path
from aoc2022.day6.buffer import Buffer
from aoc2022.day6.input import Input
from pytest import fixture
@dataclass
class Res:
length: int
first_marker_position: int
Sample = tuple[Buffer, Res]
class TestDay6:
@fixture
def test_input(self) ... | Luzkan/AdventOfCode2022 | aoc2022/day6/test_day6.py | test_day6.py | py | 1,026 | python | en | code | 1 | github-code | 50 |
41589364993 | import tweepy
import random
import time
import os
import datetime
import pandas as pd
from dotenv import load_dotenv
load_dotenv()
influencer_id_list = ["@takapon_jp", "@hirox246", "@ochyai"] # ホリエモン、ひろゆき、落合陽一
#ここのid変えるとフォローする対象を変更できる
NG_WORDS=['RT']
MY_SCREENNAME = 'st_st_blog'
def create_api(API_KEY, API_SECRET, ... | nyonyataro/Twitter-API | app.py | app.py | py | 5,281 | python | en | code | 0 | github-code | 50 |
25554904454 | """
Author: coman8@uw.edu
Preprocessing the PTB and MS alignments before it is sent on its merry way downstream.
This file expects the alignment which does not have weird duplicate quotation marks.
Run this first:
sed -r "/'\"+([a-z]+)\"+'/ s//'\1'/g" $INPUT > $OUTPUT
cont Match stylistic differences in ptb a... | cmansfield8/swb_errors_surprisal | src/preprocessor.py | preprocessor.py | py | 7,014 | python | en | code | 0 | github-code | 50 |
3656956651 | import wx
import main_class
import settings
import copy
import sys
import req
import orbit
import ope_voltage
import south_judge
from datetime import datetime
import time
import serial
import math
import re
import csv
import ephem
import os
def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
... | forestwaterfall/MORITATOR | moritator_main_class.py | moritator_main_class.py | py | 31,436 | python | en | code | 0 | github-code | 50 |
38751046470 | import distutils.util
import pandas
Discriminator = None
DiscriminatorWP = None
PlotSetup = None
apply_dm_cuts = True
setup_branches = [ 'chargedIsoPtSum' ]
def Initialize(eval_tools, args):
global Discriminator
global DiscriminatorWP
global PlotSetup
global apply_dm_cuts
Discriminator = eval_to... | dimaykerby/DisTauMLTools | Training/python/plot_setups/phase2_hlt.py | phase2_hlt.py | py | 2,784 | python | en | code | 0 | github-code | 50 |
72561584156 | import requests, io, datetime, time
import Module
import xml.etree.ElementTree
class Naver(Module.Module):
module_name = 'Naver'
data = []
def __init__(self):
pass
def get(self):
url = "https://datalab.naver.com/keyword/realtimeList.naver?where=main"
headers = {}
heade... | maeng-gu/SMART_MIRROR_project-in_dgsw | Main Program/Naver.py | Naver.py | py | 1,295 | python | en | code | 0 | github-code | 50 |
19275927857 | import pandas as pd
import numpy as np
from wordcloud import WordCloud
import jieba
import numpy as np
from PIL import Image
import pandas as pd
from wordcloud import STOPWORDS
import sklearn
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.... | login-invalid/MATH620152 | doc/code/Task_1.py | Task_1.py | py | 25,899 | python | en | code | 0 | github-code | 50 |
27194063994 | from numpy import *
import pandas as pd
import os
import matplotlib.pyplot as plt
pristine = pd.read_pickle('pristine.pkl')
exposure1 = pd.read_pickle('exposure1.pkl')
pristine_mono_mean = pristine['monofilament'].mean()/1000
pristine_mono_std = pristine['monofilament'].std()/1000
pristine_flouro_mean = pristine['fl... | Kent-Rush/Japan-Experiment | load_extensions/combined_plots.py | combined_plots.py | py | 1,349 | python | en | code | 0 | github-code | 50 |
34609885503 | import argparse
import os
import gzip
import numpy as np
import pandas as pd
import statistics
def read_fastq(file):
with open(file, "r") as fastq:
while True:
lines = [fastq.readline().strip() for i in range(4)]
if not lines[0]:
break
yiel... | gabor-gulyas/read.stat.from.fastq | read.stat.from.fastq.py | read.stat.from.fastq.py | py | 4,601 | python | en | code | 0 | github-code | 50 |
9340472117 | # https://pyautogui.readthedocs.io/en/latest/
import time
import pyautogui
import numpy as np
import random
from PIL import ImageGrab, ImageOps
# click function
def press(key):
pyautogui.keyDown(key)
time.sleep(0.01)
pyautogui.keyUp(key)
return
# variables
# delay for 5 seconds to navigate to game... | nirans2002/Chrome_Dino_automate_python | dino.py | dino.py | py | 1,120 | python | en | code | 0 | github-code | 50 |
3716104452 | from datetime import datetime
from typing import Union
from flask import Response, flash, jsonify, redirect, render_template, request, url_for
from flask_babel import lazy_gettext
from flask_login import current_user, login_required
from ..ext import db
from ..forms.base import DeleteForm
from ..models import Brew
fr... | zgoda/brewlog | src/brewlog/brew/views.py | views.py | py | 5,068 | python | en | code | 2 | github-code | 50 |
72137274716 | import aiohttp
import diskcache
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from sqlitedict import SqliteDict
from starlette.background import BackgroundTasks
from config.config import TELEGRAM_BOT_TOKEN, CHANNEL_ID, USER_DB_PATH
from VO.account_vo import AccountAction
from database.db im... | dryrain39/du-attend-v2-server | route/user/bug_report.py | bug_report.py | py | 1,402 | python | en | code | 4 | github-code | 50 |
74831828635 | import tensorflow as tf
from absl import app, flags, logging
from absl.flags import FLAGS
import numpy as np
import cv2
import core.utils as utils
import os
from core.config import cfg
import get_time_util
import data_stream_status_machine
# flags.DEFINE_string('weights', './checkpoint/social_yolov3_test-loss=3.3218.c... | chenpengf0223/Yolov5_tf | convert_tflite.py | convert_tflite.py | py | 10,874 | python | en | code | 0 | github-code | 50 |
29631158294 | import os
import string
try:
from OpenSSL import crypto
except ImportError:
crypto = None
from PyQt5.QtCore import QTextCodec, QRegularExpression, Qt
from PyQt5.QtGui import QTextCursor, QTextCharFormat, QBrush, QColor, QIcon
from PyQt5.QtWidgets import QWidget, QLabel, QApplication, QFileDialog, QTreeWidgetI... | takeshixx/deen | deen/gui/encoder.py | encoder.py | py | 30,002 | python | en | code | 46 | github-code | 50 |
27209146743 | # -*- coding: UTF-8 -*-
# @Time : 2021/08/30 07:54
# @Author : Ranshi
# @File : 123.py
from typing import List
import random
import bisect
class Solution:
def __init__(self, w: List[int]):
for i in range(1, len(w)):
w[i] += w[i - 1]
self.lst = w
self.len = w[-1]
... | Zranshi/leetcode | my-code/528/main.py | main.py | py | 507 | python | en | code | 0 | github-code | 50 |
20025582560 | """
Run builtin python tests with some needed changes after patch enabled,
then run it once again after patch disabled to make sure nothing breaks
"""
import sys
import unittest
from test import test_enum, test_re, test_inspect, test_dynamicclassattribute
TEST_MODULES = test_enum, test_re, test_inspect, test_dynamicc... | Bobronium/fastenum | tests/builtin_test.py | builtin_test.py | py | 6,259 | python | en | code | 15 | github-code | 50 |
10409045034 | #!/usr/bin/python3
""" some content to please the checker """
def add_attribute(obj, name, value):
""" adds a attribute if possible """
if '__dict__' in dir(obj):
obj.name = value
else:
raise TypeError("can't add new attribute")
| TS-N/holbertonschool-higher_level_programming | 0x0A-python-inheritance/101-add_attribute.py | 101-add_attribute.py | py | 259 | python | en | code | 0 | github-code | 50 |
72845417755 | """
Maelstrom Framework
High-level guiding principles:
- Classes are defined hierarchically and rely on wrapper/interface
functions to interact down the hierarchy
- Fitness evaluation is implemented as an external function and the
function itself it passed to the island
- Fitness evaluations are expected to accept name... | DeaconSeals/maelstrom-framework | maelstrom/__init__.py | __init__.py | py | 6,261 | python | en | code | 2 | github-code | 50 |
4517033117 | import numpy as np
import random as rd
INF = 10000000
class Node:
def __init__(self, total_score, ni, par):
self.t = total_score
self.n = ni
self.n_actions = rd.randrange(2, 5)
self.children = []
self.parent = par
self.isTerminal = False
def goUp(self):
return self.parent
def populate(self, curr_... | sshanuraj/MCTS | mcts.py | mcts.py | py | 2,116 | python | en | code | 0 | github-code | 50 |
17815739449 | """
Goddard Rocket Problem Example.
Comparison to Goddard example in for OpenGoddard
https://github.com/istellartech/OpenGoddard/blob/master/examples/04_Goddard_0knot.py
"""
import beluga
import logging
from math import pi, sqrt
ocp = beluga.Problem()
# Define independent variables
ocp.independent('t', '1')
# Defin... | Rapid-Design-of-Systems-Laboratory/beluga | examples/AscentVehicles/GoddardRocket/GoddardRocket.py | GoddardRocket.py | py | 3,012 | python | en | code | 24 | github-code | 50 |
12001915114 | '''
.가 먼저 계산되야하는 상태로 인해 1개씩 빼는 게 무의미
홀수개씩이나 짝수개씩도 같은 상황,
앞쪽에서 하나씩 뽑아쓰는 거면 모두 결국 뒤 그 뒤 그 뒤뒤 연산자를
살펴야하는 문제 생김,
그러면 그렇게 하면 되긴하는데, 범용성은 있는건가
범용성에 맞추면 후위표기법이랑 스택계산기, 내가 안외워서 그렇지 복잡한건 아니긴했음
한편,
모든 .의 위치를 먼저 파악한뒤 그 좌우 좌표를 따로 저장해서
미리 .만 먼저 계산하는 것도 생각했는데
간단하지만 범용성은 있나
하지만 일단 난 간단
+
간단해서 좋긴 한데, 길이는 웬만큼 긴듯, 계산기 암기할걸
++
줄일수 있... | devsacti/Algorithms | python/algorithmjobs/L8/L8_04dessert.py | L8_04dessert.py | py | 4,668 | python | ko | code | 0 | github-code | 50 |
19030269070 | from grc.models import Application
def reference_number_string(reference_number):
trimmed_reference = reference_number.replace('-', '').replace(' ', '').upper()
formatted_reference = trimmed_reference[0: 4] + '-' + trimmed_reference[4: 8]
return formatted_reference
def validate_reference_number(referenc... | cabinetoffice/grc-app | grc/utils/reference_number.py | reference_number.py | py | 655 | python | en | code | 2 | github-code | 50 |
21494435423 | import logging
import webapp2
import jinja2
import os
import json
from google.appengine.ext import ndb
from google.appengine.api import users
from xml.dom.minidom import parse
import xml.dom.minidom
USERSTORE_NAME = 'default_userstore'
SUPPLIERSTORE_NAME = 'default_supplierstore'
PRODUCTSTORE_NAME = 'default_products... | ethornbury/PythonCart | cartservice.py | cartservice.py | py | 29,695 | python | en | code | 0 | github-code | 50 |
19133322891 | import os
import sys
class colors:
cyan = '\033[96m'
green = '\033[92m'
red = '\033[91m'
normal = '\033[0m'
bold = '\033[1m'
underline = '\033[4m'
yellow = '\033[93m'
class ParensStack:
open_chars = set("[{(")
close_chars = set("}])")
def __init__(self, parens):
... | a097123/code_collab | ParensStack.py | ParensStack.py | py | 2,266 | python | en | code | 0 | github-code | 50 |
75180344475 | from bs4 import BeautifulSoup
import requests
import json
# SCRAPING PPG
url = "https://www.teamrankings.com/nba/player-stat/points"
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
lists = soup.find_all('tr')
jockDict = dict()
for list in lists:
name = list.find('td', class_="text-le... | daygodavy/nba-jock | nba-webscraper-final.py | nba-webscraper-final.py | py | 3,481 | python | en | code | 0 | github-code | 50 |
41632770724 | # -*- coding:utf-8 -*-
from functools import wraps
import time
__author__ = 'q00222219@huawei'
class RetryDecorator(object):
"""Decorator for retrying a function upon suggested exceptions.
The decorated function is retried for the given number of times, and the
sleep time between the retries is increment... | hgqislub/hybird-orchard | code/cloudmanager/decorator.py | decorator.py | py | 2,329 | python | en | code | 1 | github-code | 50 |
33411033275 | import sys
import bean as be
bdata_path = sys.argv[1]
reps = sys.argv[2].split(",")
outfile_path = sys.argv[3]
bdata = be.read_h5ad(bdata_path)
bdata_sub = bdata[:, bdata.samples.rep.isin(reps)]
bdata_sub.write(outfile_path)
| pinellolab/bean_manuscript | workflow/scripts/run_models/subset_screen.py | subset_screen.py | py | 237 | python | en | code | 0 | github-code | 50 |
18897888710 | import cv2
import numpy as np
import matplotlib.pyplot as plt
#分道计算每个通道的直方图
img = cv2.imread('/media/lc/8A986A3C986A26C3/model/data/m4.png')
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
#img_b, img_g, img_r = np.split(img)
# hist_b = cv2.calcHist([img0],[0],None,[256],[0,256])
# hist_g = cv2.calcHist([img0],[1],N... | lichuanqi/Python_Learn_Note | vision/preprocessing/gamma_bianhuan.py | gamma_bianhuan.py | py | 911 | python | en | code | 2 | github-code | 50 |
18023867441 | # -*- coding:utf-8 -*-
"""
@author: guoxiaorui
@file: 3_maximum_detonation
@time: 2021/12/12 1:31 上午
@desc:
"""
from typing import List
class Solution:
def maximumDetonation(self, bombs: List[List[int]]) -> int:
n = len(bombs)
data = [[] for _ in range(n)]
for i in range(n):
... | sun10081/leetcode_practice_xiaorui | questions/week/2021/2021_12_11/3_maximum_detonation.py | 3_maximum_detonation.py | py | 1,078 | python | en | code | 0 | github-code | 50 |
18222047806 | import pytest
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
@pytest.fixture
def driver(request):
driver = webdriver.Chrome()
request.addfinalizer(driver.quit)
... | NovikovNS/Selenium | Tasks/test_countries_admin.py | test_countries_admin.py | py | 2,479 | python | en | code | 0 | github-code | 50 |
7583912920 | import pandas as pd
import math
import numpy as np
###################################################################################
############### Make a class for matching process##################################
###################################################################################
class Mat... | BAN-JY/ridesharing | matchingprocess.py | matchingprocess.py | py | 4,040 | python | en | code | 0 | github-code | 50 |
46786286288 | import math
import os
import random
import re
import sys
# String considered valid if all characters of the string appear the same number of times
# valid if removing 1 character at 1 index in the string
# given string s, determine if it is validIfo so return YES otherwise retunr no
def isValid(s):
# Returns ex... | yettsyjk/rockinAndRolling | validatingStrings.py | validatingStrings.py | py | 1,496 | python | en | code | 0 | github-code | 50 |
17565472607 | from typing import Dict
from edges import edge_list
from builders import build_graph
graph = build_graph(edge_list)
def undirected_has_path(*, graph:Dict, source:str, destination:str, visited:dict) -> bool:
if source == destination: return True
if visited.get(source): return False
visited.update({source... | code-intensive/data_structures_and_algorithms_in_python | graphs/undirected_path.py | undirected_path.py | py | 666 | python | en | code | 0 | github-code | 50 |
552580981 | class Solution:
def kSimilarity(self, A, B):
"""
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A
exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and ... | ljia2/leetcode.py | solutions/bfs/854.K-Similar.Strings.py | 854.K-Similar.Strings.py | py | 2,199 | python | en | code | 0 | github-code | 50 |
34325490634 | import numpy as np
import pandas as pd
import random
def FindInterval(a, arr):
for i in range(len(arr)):
if arr[i] >= a:
return i
V0 = 500
p = 2
VertexList = [i for i in range(V0)]
ArcList = [[] for i in range(V0)]
# 下面每个点随机产生两条边
for i in range(V0):
randedge = random.sam... | Caohanwen0/Sybil-Detection | unsupervised/SybilSCAR/PAGenerativeNetwork.py | PAGenerativeNetwork.py | py | 2,159 | python | en | code | 0 | github-code | 50 |
22933416067 | from flask import request,Response
from datetime import datetime
from flaskr.common_method import db_setting, security,list_method,splicing_list
import requests
import json
def article_like(app):
@app.route('/article_like', methods=['post'])
def article_like(): # 文章喜欢和取消喜欢
token = request.headers['acce... | 17621445641/duitang_back_end | flaskr/model/article_like.py | article_like.py | py | 8,474 | python | en | code | 0 | github-code | 50 |
26203038438 | from io import BytesIO
from pathlib import Path
import httpx
from openai import AsyncOpenAI
from openai.types.chat import (
ChatCompletionMessageParam,
ChatCompletionMessageToolCall,
ChatCompletionSystemMessageParam,
)
from openai.types.image import Image
from typing import Any, Callable, Coroutine, Generic... | kpister/prompt-linter | data/scraping/repos/AkashiCoin~nonebot-plugin-openai/nonebot_plugin_openai~types.py | nonebot_plugin_openai~types.py | py | 3,736 | python | en | code | 0 | github-code | 50 |
31607181190 | from src import app, db
from src.models import Event, Ticket
from flask import render_template
@app.route("/", methods=["GET"])
def homepage():
events = Event.query.all()
return render_template("index.html", events=events)
@app.route("/event/<event_id>", methods=["GET"])
def event_visualizer(event_id):
ti... | Ytalow/Flask-tickets | src/routes.py | routes.py | py | 1,444 | python | en | code | 0 | github-code | 50 |
14759883343 | import logging
import time
import weatherlink_live_local as wlll
logging.basicConfig(level=logging.INFO)
def main():
devices = wlll.discover()
print(devices)
# select first device, get IP address
ip_first_device = devices[0].ip_addresses[0]
# specify units
wlll.set_units(
temperatu... | lukasberbuer/weatherlink-live-local-python | examples/basic.py | basic.py | py | 865 | python | en | code | 1 | github-code | 50 |
30847005898 | import pandas as pd
import math
import matplotlib.pyplot as plt
def benfordNumber(benfordTest):
sum = 0;
for val1,val2 in zip(benfordTest,benford):
sum += abs(val1-val2)
return sum
benford = [math.log10(1+1/value)*100 for value in range(1,10)]
digits = [value for value in range(1,10)]
data = pd.r... | mm909/BenfordsLaw | COVID/single.py | single.py | py | 1,041 | python | en | code | 0 | github-code | 50 |
1518490123 | from django.shortcuts import render_to_response, render, redirect
import requests
from bottle import request, route, run
from django.http import HttpResponse
from booker.models import Customer, Book
from booker.forms import CustomerForm, BookForm
def home(request):
return render(request, "home.html")
def new_book(... | Holl/BookStore | booker/views.py | views.py | py | 2,096 | python | en | code | 0 | github-code | 50 |
4639183369 | from io import BytesIO
from typing import Callable, Optional, Union, overload
from faker import Faker
from faker.generator import Generator
from faker.providers import BaseProvider
from faker.providers.python import Provider
from odf.opendocument import OpenDocumentText
from odf.text import P
from ..base import (
... | barseghyanartur/faker-file | src/faker_file/providers/odt_file.py | odt_file.py | py | 7,216 | python | en | code | 74 | github-code | 50 |
1185328161 | # -*- coding: utf-8 -*-
"""
utils sqlalchemy module.
"""
from sqlalchemy.sql import quoted_name
from sqlalchemy.engine import result_tuple
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy import inspect, Table, asc, desc, func, CheckConstraint
import pyrin.utils.datetime as datetime_utils
import pyri... | mononobi/pyrin | src/pyrin/utils/sqlalchemy.py | sqlalchemy.py | py | 25,102 | python | en | code | 12 | github-code | 50 |
9216030065 | import torch
class Main(torch.nn.Module):
def forward(self, x):
# The input x is a series of random numbers of size k x 2
# You should use these random numbers to compute and return pi using pytorch
# dist1 = torch.sqrt(x[:,0]**2 + x[:,1]**2)
# dist2 = torch.sqrt((x[:,0]-1)**2+x[:,1]**2)
# dist3 = torch.sqr... | xftnr/Neural-Networks | homework_01/homework/main.py | main.py | py | 1,020 | python | en | code | 0 | github-code | 50 |
16973540723 | from codecs import open
from setuptools import setup
long_description = open('README.rst', 'r', encoding='utf-8').read()
setup(
name='cloudml-hypertune',
version='0.1.0',
description='A library to report Google CloudML Engine HyperTune metrics.',
long_description=long_description,
author='Goo... | GoogleCloudPlatform/cloudml-hypertune | setup.py | setup.py | py | 1,244 | python | en | code | 32 | github-code | 50 |
22055760488 | # Read file
# Build up graph with dict
# Start path finding
# find_paths(start, end, current_path=[start])
# Iterate over all neighbouring caves: find_paths(neighbourX, end, current_path[start, neighbourX])
# ... and concatenate their resulting paths
# When adding a new cave, check if path is valid
# If end is reache... | danielmast/advent-of-code-2021 | day12/day12_1.py | day12_1.py | py | 1,688 | python | en | code | 0 | github-code | 50 |
8025266594 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 21 10:04:17 2022
@author: psen
"""
#Intialize dict and list
grocery = {}
item = []
#Get input in item and sort
while True:
try:
item.append(input("Item: ").upper())
except EOFError:
print()
break
item.sort()
#Add item in dic... | Lotus010/cs50python | Week 3 Exceptions/grocery.py | grocery.py | py | 731 | python | en | code | 0 | github-code | 50 |
71819228636 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<quali>[0-9]+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<quali>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vot... | jmboettger/HioDB | quali/urls.py | urls.py | py | 389 | python | en | code | 1 | github-code | 50 |
25587999493 | '''
Objektorientiert Programmierung
Ein bewegtes Objekt
Version 1.00, 27.02.2021
Der Hobbyelektroniker
https://community.hobbyelektroniker.ch
https://www.youtube.com/c/HobbyelektronikerCh
Der Code kann mit Quellenangabe frei verwendet werden.
'''
from tkinter import *
from kreis_klasse import KreisV... | hobbyelektroniker/Micropython-Grundlagen | 013_Klassen in Micropython/Code/Objekte3.py | Objekte3.py | py | 1,080 | python | de | code | 0 | github-code | 50 |
29269191782 | import open3d as o3d
import copy
import numpy as np
# 2
def draw_registration_result(source, target, transformation):
source_temp = copy.deepcopy(source)
target_temp = copy.deepcopy(target)
source_temp.paint_uniform_color([1, 0.706, 0])
target_temp.paint_uniform_color([0, 0.651, 0.929])
source_temp... | kev1nCh1u/Image_Processing_Project2 | src/o3d_icp.py | o3d_icp.py | py | 3,829 | python | en | code | 0 | github-code | 50 |
72335923354 | import os
import os.path as osp
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
def plot_features(features, labels, num_classes, epoch, save_dir, prefix):
"""Plot features on 2D plane.
Args:
features: (num_instances, num_features).
labels: (num_instances).
""... | chenshen03/MarginHash-pytorch | utils/visualize.py | visualize.py | py | 914 | python | en | code | 6 | github-code | 50 |
16858849958 | import pandas as pd
from sklearn.preprocessing import MinMaxScaler,StandardScaler
"""
特征工程之特征预处理:
通过一些转换函数将特征数据转换成更加适合算法模型的特征数据过程
为什么我们要进行归一化/标准化?
特征的单位或者大小相差较大,或者某特征的方差相比其他的特征要大出几个数量级,容易影响(支配)目标结果,使得一些算法无法学习到其它的特征
我们需要用到一些方法进行无量纲化,使不同规格的数据转换到同一规格
包含内容(数值型数据的无量纲化)
归一化
标准化
1,归一化
通过对原始数据进行变换把数据映射到(默认为[0,1])之间
公式:
先求出... | Mr-Owl/machine_learning | 05-k近邻算法/03-preprocessing预处理.py | 03-preprocessing预处理.py | py | 3,236 | python | zh | code | 2 | github-code | 50 |
34967066466 | #!/usr/bin/env python
# -*- coding: utf8 -*-
import logging
from urllib.parse import urljoin
from .consts import *
from .htmltools import taglist_to_dict, table_to_dict
from .urltools import get_cached_url, get_cached_post, get_from_file
from .patterns import PATTERNS
#logging.getLogger().addHandler(logging.StreamH... | ivbeg/lazyscraper | lazyscraper/scraper.py | scraper.py | py | 7,862 | python | en | code | 17 | github-code | 50 |
22136621924 | # -*- coding: utf-8 -*-
import json
import uvicorn
from starlette.applications import Starlette
from starlette.responses import JSONResponse, RedirectResponse
from starlette.routing import Route, Mount, WebSocketRoute
# from motor.motor_asyncio import AsyncIOMotorClient
# from starlette.responses import Response
# from... | Surrealistic-Creature/elsewhere | main.py | main.py | py | 5,632 | python | en | code | 0 | github-code | 50 |
2222177898 | import socket
import math
def get_hostname():
return socket.gethostname()
def get_local_ip():
try:
hostname = socket.gethostname()
local_ip = socket.getaddrinfo(hostname, None, socket.AF_INET)[0][4][0]
return local_ip
except socket.error as e:
print("An error occurred:", e)... | jinkoo2/buy-or-sell | utils.py | utils.py | py | 999 | python | en | code | 0 | github-code | 50 |
18173730026 | #! /usr/bin/python3
from evaluator import load_gold_NER, load_gold_NER_ext
import sys
from os import listdir, system
import re
from math import sqrt
from xml.dom.minidom import parse
from nltk.tokenize import word_tokenize
import evaluator
# dictionary containig information from external knowledge resources
# WARN... | guillermocreus/AHLT | lab1/baseline-NER.py | baseline-NER.py | py | 6,001 | python | en | code | 0 | github-code | 50 |
22993556400 | """
Lots of code taken from deap
"""
input_names = ['b0', 'b1', 'b2', 'b3', 'b4']
PARITY_FANIN_M = 5
PARITY_SIZE_M = 2**PARITY_FANIN_M
inputs = [None] * PARITY_SIZE_M
outputs = [None] * PARITY_SIZE_M
for i in range(PARITY_SIZE_M):
inputs[i] = [None] * PARITY_FANIN_M
value = i
dividor = PARITY_SIZE_M
... | nunolourenco/dsge | src/examples/parity_5.py | parity_5.py | py | 1,196 | python | en | code | 11 | github-code | 50 |
38281810819 | #!python3
import os
x = 0
while 1:
x += 1
os.system('./generator > input.txt')
os.system('./dmopc20c3p4 < input.txt > output.txt')
os.system('./slow < input.txt > slow.txt')
if open('slow.txt').read() != open('output.txt').read():
print("WA")
exit(0)
print("AC random test "+st... | pidddgy/competitive-programming | codeforces/fastslow.py | fastslow.py | py | 326 | python | en | code | 0 | github-code | 50 |
35879848034 | # __ TALLER 4 __
# Ejercicio 1
listaCanciones = ['La noche más linda', 'Plan', 'Monalisa', 'Maldita Traición', 'I Dont Care',
'Ella y Yo', 'Human', 'Movimiento de Cadera',
'Me Niego', 'La Descarada', 'Propuesta Indecente', 'Lento', 'Se Acabó',
'Traicionera'... | NeoEzzio/algoritmos | Talleres/Ejer2_canciones.py | Ejer2_canciones.py | py | 2,723 | python | es | code | 0 | github-code | 50 |
28890305284 |
# Importing the Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
# Data collection... | khaymanii/Big_Mart_Prediction_Model | Big Mart.py | Big Mart.py | py | 3,696 | python | en | code | 0 | github-code | 50 |
3166437961 | from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(300, 300, 720, 720)
self.setWindowTitle("PyQt5 window")
... | willdavis576/wheelDashboard | poking.py | poking.py | py | 659 | python | en | code | 0 | github-code | 50 |
10345496394 | """OpenAPI spec validator handlers requests module."""
import contextlib
from six.moves.urllib.parse import urlparse
from six.moves.urllib.request import urlopen
from openapi_spec_validator.handlers.file import FileObjectHandler
class UrllibHandler(FileObjectHandler):
"""OpenAPI spec validator URL (urllib) sche... | eugene-aiken-bytecode/bytecode-airflow-dbt | bytecode-airflow-dbt/lib/python3.9/site-packages/openapi_spec_validator/handlers/urllib.py | urllib.py | py | 781 | python | en | code | 1 | github-code | 50 |
4313034204 | # Пишем фреймворк: Задание 1 - 200 баллов
from dns import reversename, resolver
import Part_2.Lesson_16.lesson_16_task_1.full_scripts.input_text_check as in_text
import colorama
from colorama import Fore
colorama.init(autoreset=True)
def dns_reverse():
ip = in_text.input_text("Enter ip: ")
try:
rev_n... | MancunianRed/Python_Lessons | Part_2/Lesson_16/lesson_16_task_1/full_scripts/reverse_dns.py | reverse_dns.py | py | 567 | python | en | code | 0 | github-code | 50 |
22372064176 | import sys
from cx_Freeze import setup, Executable
def build(cmd = None, ver = None):
if cmd:
sys.argv.append(cmd)
#print(sys.argv)
# see http://cx-freeze.readthedocs.org/en/latest/distutils.html
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup( name = "PyMangaReader",
... | jschmer/PyMangaReader | setup.py | setup.py | py | 509 | python | en | code | 3 | github-code | 50 |
12752530025 | #The Tip Calculator
#Here, the initial price of the meal is asked from the user
price_meal = float(input("How much did your meal cost?: "))
#Next, the amount of people who will be splitting the bill is requested from the user
people = int(input("How many people will be splitting the bill?: "))
#Finally, The tip p... | itsthatbrownguy91/TipCalculator | Tip_Calculator.py | Tip_Calculator.py | py | 1,172 | python | en | code | 0 | github-code | 50 |
35018961984 | ##############################################################################
# VoiceCode, a programming-by-voice environment
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
... | jboner/emacs-config | VCode/Mediator/util.py | util.py | py | 10,501 | python | en | code | 17 | github-code | 50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.