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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
24481282090 | import logging
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Logger(object):
__metaclass__ = Singleton
def __in... | shalseban/wikiepedia-top-pageviews | src/main/python/logger.py | logger.py | py | 809 | python | en | code | 0 | github-code | 36 |
32137328654 | import datetime
import json
import os
from datetime import timezone
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from sklearn.decomposition import PCA
from sklearn.model_selection import KFold, ParameterGrid, train_test_split
from prism_kondo.experiment_utils import (
add_random_n... | lurue101/Ruecker_MA | prism_kondo/noise_experiments.py | noise_experiments.py | py | 13,013 | python | en | code | 0 | github-code | 36 |
42893635287 | # _*_ coding: utf-8 _*_
"""
Created by Allen7D on 2020/4/13.
"""
from app import create_app
from tests.utils import get_authorization
__author__ = 'Allen7D'
app = create_app()
def test_create_auth_list():
with app.test_client() as client:
rv = client.post('/cms/auth/append', headers={
'Aut... | Allen7D/mini-shop-server | tests/test_cms_auth.py | test_cms_auth.py | py | 874 | python | en | code | 663 | github-code | 36 |
73974471145 | import logging
from datetime import datetime
from time import sleep
from typing import Union, Optional, Tuple, List, Sequence
import mariadb
from mariadb import Cursor, Connection
from accounting_bot import utils
from accounting_bot.exceptions import DatabaseException
logger = logging.getLogger("ext.accounting.db")
... | Blaumeise03/AccountingBot | accounting_bot/ext/accounting_db.py | accounting_db.py | py | 11,837 | python | en | code | 6 | github-code | 36 |
13231395273 | class Creation(object):
"""The creation module for inheritance.
Functions:
create:
assign a chain.
_creation:
creation a chain.
_create_text:
creation a text.
"""
def create(self):
"""Assign a chain to the self._chain... | Amaimersion/markov-chain | chain/creation.py | creation.py | py | 2,793 | python | en | code | 6 | github-code | 36 |
38687624011 | import random
def setWinningNumber():
winningNumber = random.randint(0,37)
"""
if winningNumber == 37:
winningNumber = str("Double Zero")
print("Double Zero: " + str(winningNumber))
else:
winningNumber = str(winningNumber)
"""
winningNumber = str(winningNumb... | DanielMeeker/RouletteSimulator | rouletteStrats.py | rouletteStrats.py | py | 5,466 | python | en | code | 0 | github-code | 36 |
4898894473 | import os
import sys
from PyQt5 import QtGui, QtWidgets
"""
from datetime import datetime,timedelta
from threading import Timer
"""
print('poggo')
class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
def __init__(self,icon,parent=None):
QtWidgets.QSystemTrayIcon.__init__(self,icon,parent)
s... | verentino/PU_PDT_TimeUp | tray_old.py | tray_old.py | py | 1,936 | python | en | code | 0 | github-code | 36 |
25852170492 | """Returns probes where each 'N' base is replaced by real bases.
The 'N' base in a probe indicates an unknown -- i.e., the base
can either 'A', 'T', 'C', or 'G'.
This acts as a filter on the probes by returning, for each probe p:
- if p does not contain an 'N' base, then p itself.
- if p does contain one or more 'N... | broadinstitute/catch | catch/filter/n_expansion_filter.py | n_expansion_filter.py | py | 4,410 | python | en | code | 63 | github-code | 36 |
42982956826 | import redis
#import hazelcast
import logging
import random
import azlog
log = azlog.getLogger(__name__)
def SetupCacheConn(type,ip,port,key,ssl):
if (type=="redis"):
if (ssl=="yes"):
r=SetupRedisSSLConn(ip,port,key)
else:
r=SetupRedisConn(ip,port,key)
else:
... | Azure/HPC-Accelerator | scenarios/batch/code/src/utils.py | utils.py | py | 2,295 | python | en | code | 9 | github-code | 36 |
29673229409 | #!/usr/bin/env python
import rospy
import tf2_ros
import gazebo_msgs.msg
import geometry_msgs.msg
import time
import pdb
IS_SIM = True
if IS_SIM:
ORIGIN_FRAME = 'odom'
else:
ORIGIN_FRAME = 'origin'
if __name__ == '__main__':
rospy.init_node('gazebo_tf_broadcaster')
broadcaster = tf2_ros.StaticTrans... | apacheck/stretch_skill_repair | nodes/gazebo_tf_publisher.py | gazebo_tf_publisher.py | py | 1,914 | python | en | code | 1 | github-code | 36 |
72136189865 | import os
from flask import jsonify, current_app
from flask_mail import Message
from werkzeug.utils import secure_filename
from PIL import Image
from api import mail
QUESTIONS_PER_PAGE = 5
def paginator(request, data):
page = request.args.get("page", 1, type=int)
start = (page - 1) * QUESTIONS_PER_PAGE
... | dennisappiah/pong-game-api | api/utils.py | utils.py | py | 1,591 | python | en | code | 4 | github-code | 36 |
16239891433 | def read_data(filename):
try:
with open(filename, 'r', encoding='utf-8') as file:
data = []
for line in file:
line = line.strip().split(' ')
if len(line) == 2:
surname, birth_year = line
data.append((surname, int... | Merlin0108/rep2 | lab10/3.py | 3.py | py | 824 | python | en | code | 0 | github-code | 36 |
11916959214 | from django import forms
from .models import Comment ,Blog,Category
class BlogForm(forms.ModelForm):
category = forms.ModelChoiceField(
queryset=Category.objects.all().order_by('name'))
class Meta:
model = Blog
fields = ['title', 'featured_image', 'content','category']
... | minarefaat1002/blog_website | blogs project/blog/forms.py | forms.py | py | 804 | python | en | code | 0 | github-code | 36 |
17978578215 | # 导入操作系统库
import os
# 更改工作目录
os.chdir(r"D:\softwares\applied statistics\pythoncodelearning\chap3\sourcecode")
# 导入绘图库
import matplotlib.pyplot as plt
# 导入支持向量机模型
from sklearn import svm
# 导入决策边界可视化工具
from sklearn.inspection import DecisionBoundaryDisplay
# 导入数据集生成工具
from sklearn.datasets import make_blobs
# 导入绘图库中的字体管理... | AndyLiu-art/MLPythonCode | chap3/sourcecode/Python4.py | Python4.py | py | 1,925 | python | zh | code | 0 | github-code | 36 |
9190017437 | # imports
# scipy/anaconda imports
import pandas
from scipy import stats
import numpy
# python standard library imports
import math
import statistics
import copy
import collections
import time
nan = float("nan")
def fit_line(x_data, y_data):
"""
performs a linear fit to the data and return the slope, y-intercept, R... | Kramer-Lab-Team-Algae/vO2-per-LEF-scripts | Data Analysis/MathHelper.py | MathHelper.py | py | 6,671 | python | en | code | 0 | github-code | 36 |
20638189382 | from tkinter import *
root=Tk()
h,w=root.winfo_screenheight(),root.winfo_screenwidth()
root.geometry('%dx%d+0+0'%(w,h))
def seat():
root.destroy()
import journey_details
def check():
root.destroy()
import checkbooking
def add():
root.destroy()
import addbus
img=PhotoImage(file=".\... | aviraljain19/Python-Bus-Booking-Project | home.py | home.py | py | 1,006 | python | en | code | 0 | github-code | 36 |
1158088849 | import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from utils import INPUT_SHAPE, batch_generator
from keras.models import Sequential
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
from keras.layers import Lambda, Conv2D, Dropout, Dense, Flatten... | thomashiemstra/self_driving_car_simulation | train.py | train.py | py | 2,585 | python | en | code | 1 | github-code | 36 |
7004225568 | # *args
def func(*args):
print(args) # it print tuple
print(type(args))
func(1,2,3,4,5,6,4)
def add_all(*args):
total = 0
for i in args:
total += i
return total
print(add_all(1,2,3,4,6,8,11,23)) | salmansaifi04/python | chapter9(functions)--(args_and_kwargs)/01_args_intro.py | 01_args_intro.py | py | 229 | python | en | code | 0 | github-code | 36 |
28713561153 | import sys
# print(sys.argv)
old_str = sys.argv[1]
new_str = sys.argv[2]
filename = sys.argv[3]
# 1 读取文件至内存中
f = open(filename, "r+")
data = f.read()
new_data = data.replace(old_str, new_str)
old_count = data.count(old_str)
# 2清空文件
f.seek(0)
f.truncate()
# 3写入文件
f.write(new_data)
print(new_data)
f.close()
print(f"... | codefreshstudent/day8 | day4/file_replace.py | file_replace.py | py | 412 | python | en | code | 0 | github-code | 36 |
24267348983 | import pandas as pd
import geocoder
import math
from RR import *
class TreeOp:
def __init__(self, path=None):
# The path is the path of the csv file. Call this function to create the R-Trees
# Will Create R-Entries and then those entries will be search
# X is the longitude, Y is the Latit... | munawwar22HU/Ehsas | Source/RTreeOperations.py | RTreeOperations.py | py | 3,426 | python | en | code | 1 | github-code | 36 |
17585730612 | from __future__ import annotations
from collections import defaultdict
from starwhale import Job, handler, evaluation
from starwhale.utils.debug import console
PROJECT_URI = "https://cloud.starwhale.cn/project/349"
JOB_URI_TEMPLATE = "%s/job/{job_id}" % PROJECT_URI
JOB_IDS = [
"845",
"844",
"843",
"8... | star-whale/starwhale | example/llm-leaderboard/src/analysis.py | analysis.py | py | 3,516 | python | en | code | 171 | github-code | 36 |
28518778247 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE
from opus_core.variables.variable import Variable
from variable_functions import my_attribute_label
class percent_development_type_DDD_within_walki... | psrc/urbansim | randstad/gridcell/percent_development_type_DDD_within_walking_distance.py | percent_development_type_DDD_within_walking_distance.py | py | 3,241 | python | en | code | 4 | github-code | 36 |
25947442218 | import os
import sqlite3
from datetime import datetime, timedelta
import telebot
bot = telebot.TeleBot(os.getenv("BOT_TOKEN"))
memes_chat_id = int(os.getenv("MEMES_CHAT_ID"))
flood_thread_id = int(os.getenv("FLOOD_THREAD_ID", 1))
memes_thread_id = int(os.getenv("MEMES_THREAD_ID", 1))
conn = sqlite3.connect("memes.db... | dzaytsev91/tachanbot | cron_job_message_count.py | cron_job_message_count.py | py | 1,258 | python | en | code | 2 | github-code | 36 |
38326596416 | import pandas as pd
from matplotlib import pyplot as plt
from oemof.tools import logger
import logging
import q100opt.plots as plots
from q100opt.buildings import BuildingInvestModel, SolarThermalCollector
from q100opt.scenario_tools import ParetoFront
from q100opt.setup_model import load_csv_data
logger.define_loggi... | quarree100/q100opt | examples/single_building/example_house_with_solarthermal.py | example_house_with_solarthermal.py | py | 3,764 | python | en | code | 1 | github-code | 36 |
5302886583 | import natasha
from external_analizer.morph_dictionaries.pymorphy_morph_dictionary import PymorphyMorphDictionary
from external_analizer.syntax_analizer.syntax_analyzer import SyntaxAnalizer
class NLPAnalyzer():
# создаем классы для анализа текста предложения для всего проекта
segmenter = natasha.Segmenter()... | NenausnikovKV/NLP_library | source/external_analizer/nlp_analizer.py | nlp_analizer.py | py | 2,131 | python | en | code | 0 | github-code | 36 |
34182723957 | # coding=utf-8
from __future__ import print_function
"""负责从主网址中爬取出需要的网址"""
import datetime
import logging
import bs4
import requests
import re
import tools.newspublish
from bs4 import BeautifulSoup
from models import *
from .tools.bloomfilter import BloomFilter
from Spider.autonews.tools.svmutil import *
from .objec... | zqkarl/Spider | Spider/autonews/url_spider.py | url_spider.py | py | 26,835 | python | en | code | 0 | github-code | 36 |
26944213809 | # -*- coding: utf-8 -*-
'''
@author: davandev
'''
import logging
import os
import traceback
import sys
import davan.config.config_creator as configuration
import davan.util.constants as constants
from davan.util import cmd_executor as cmd_executor
from davan.http.service.base_service import BaseService... | davandev/davanserver | davan/http/service/picture/PictureService.py | PictureService.py | py | 4,701 | python | en | code | 0 | github-code | 36 |
2262298883 | import tensorflow as tf
#how to see tensorflow operation
def seeTF():
# one 3x3 image with 2 channels
input = tf.Variable(tf.random_normal([1,3,3,2]))
# one 3x3 filter with 2 channels
filter = tf.Variable(tf.random_normal([3,3,2,1]))
op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='... | thbeucher/DQN | help/tuto_tf.py | tuto_tf.py | py | 3,957 | python | en | code | 1 | github-code | 36 |
12006624886 | #! /usr/bin/env python3
import sys
sys.path.insert(0, '/home/pi/soco') # Add soco location to system path
import time
from soco import SoCo
from soco.snapshot import Snapshot
print("Starting Doorbell Player...")
### Setup
# Define doorbell MP3 file as bellsound and set doorbell volume
bellsound = "http... | ronschaeffer/sonosdoorbell | SonosDoorbellPlayer.py | SonosDoorbellPlayer.py | py | 5,389 | python | en | code | 2 | github-code | 36 |
34636922480 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
#Program to find minimum flips to convert message P to message Q
def flipped_bits(num1, num2):
# initially flips is equal to 0
flips = 0
# & each bits of num1 && num2 with 1
# if t1 != t2 then we will flip that bit
while(num1 > 0 or num2 > 0):
... | atta1987/HSBC | Bits flip.py | Bits flip.py | py | 796 | python | en | code | 0 | github-code | 36 |
37849815349 | #!/usr/bin/env python3
from bicon import data_preprocessing
from bicon import BiCoN
from bicon import results_analysis
import sys
path_expr = sys.argv[1]
path_net = sys.argv[2]
path_out = sys.argv[3]
GE, G, labels, _ = data_preprocessing(path_expr, path_net)
L_g_min = int(sys.argv[4])
L_g_max = int(sys.argv[5])
mo... | repotrial/NeDRex-Web | web/backend/scripts/run_bicon.py | run_bicon.py | py | 596 | python | en | code | 2 | github-code | 36 |
71249270184 | """
Core client functionality, common across requests.
"""
import collections
import random
import requests
import time
from datetime import datetime
from datetime import timedelta
RETRIABLE_STATUSES = {500, 503, 504}
class AbstractRestClient:
"""Performs requests to APIs services."""
def __init__(self, b... | ifreddyrondon/address-resolver | addressresolver/core/client.py | client.py | py | 5,786 | python | en | code | 0 | github-code | 36 |
74541806822 | #!/usr/bin/env python
# -*- encoding:utf-8 -*-
import logging
import time
import gzip
import random
from six.moves.urllib.error import URLError
from six.moves.urllib.request import Request, build_opener, HTTPCookieProcessor
from six.moves.urllib.parse import urlencode
from six.moves.http_cookiejar import CookieJar
fr... | liuyug/utils | network.py | network.py | py | 3,623 | python | en | code | 0 | github-code | 36 |
19738801169 | from vigilo.models.session import DBSession, MigrationDDL
from vigilo.models.tables import HighLevelService
def upgrade(migrate_engine, actions):
"""
Migre le modèle.
@param migrate_engine: Connexion à la base de données,
pouvant être utilisée durant la migration.
@type migrate_engine: C{Engin... | vigilo/models | src/vigilo/models/migration/028_Different_HLS_priorities.py | 028_Different_HLS_priorities.py | py | 1,101 | python | fr | code | 4 | github-code | 36 |
25141616 | from sys import stdin
input = stdin.readline
n = int(input())
table = []
for i in range(n):
table.append(list(map(int, input().split())))
ans = [0]*n
for i in range(n):
rank = 1
for j in range(n):
if i == j :
continue
if (table[i][0] >= table[j][0] and table[i][1] < table[j][1])... | kmgyu/baekJoonPractice | bruteForce/덩치.py | 덩치.py | py | 523 | python | en | code | 0 | github-code | 36 |
28721865338 | # usage: python dropprofiles.py
# looks through mongo argo:argo and lists ids
from pymongo import MongoClient
client = MongoClient('mongodb://database/argo')
db = client.argo
mongoprofiles = open("mongoprofiles", "w")
mongoids = [x['_id'] for x in list(db.argo.find({}, {'_id':1}))]
for x in mongoids:
mongoprofil... | argovis/ifremer-sync | audit/mongoids.py | mongoids.py | py | 363 | python | en | code | 0 | github-code | 36 |
16393471442 | #This is just an expansion on what the Matrix class was having a hard time fitting in
#It mainly deals with getting larger inverses, but also could have allowed
#transposing and determinants
def transposeMatrix(m):
t = []
for r in range(len(m)):
tRow = []
for c in range(len(m[r])):
... | MrShutCo/Matrix-Solver | matrix_inverse_helper.py | matrix_inverse_helper.py | py | 1,571 | python | en | code | 0 | github-code | 36 |
40264770849 | budget = float(input())
season = input()
type_holiday = ""
destination = ""
total = 0
if budget <= 100:
destination = "Bulgaria"
if season == "summer":
type_holiday = "Camp"
total = budget * 0.3
elif season == "winter":
type_holiday = "Hotel"
total = budget * 0.7
elif budget... | ivoivanov0830006/1.1.Python_BASIC | 3.Nested_conditional_statements/*05.Journey.py | *05.Journey.py | py | 709 | python | en | code | 1 | github-code | 36 |
15062774171 | import socket
import tkinter as tk
HOST = '127.0.0.1'
PORT = 12345
def run_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen()
print(f"Server started at {HOST}:{PORT}")
while True:
print("Waiting for a connect... | damianslavenburg/leren-programmeren | python/module 4/deel 2/chatbot/server.py | server.py | py | 1,186 | python | en | code | 0 | github-code | 36 |
32578660748 | import cv2 as cv
import numpy as np
image = cv.imread('img.jpg')
imageGray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
imageGrayCanny = cv.Canny(image,100,150)
cv.imshow('canny',imageGrayCanny)
contours, hierarchy = cv.findContours(imageGrayCanny,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_NONE)
contours_poly = [None] *... | mycatdoitbetter/projects-opencv2-python | t31 - t45/t-32/t-32.py | t-32.py | py | 1,040 | python | en | code | 1 | github-code | 36 |
10084447821 | s = input().rstrip()
result = []
# 한글자씩 떼서 리스트에 저장
for i in range(len(s)):
a = s[i:]
result.append(a)
# 정렬
result.sort()
# 출력
for j in result:
print(j) | papillonthor/Cool_Hot_ALGO | tsLim/boj/s4_11656_접미사배열.py | s4_11656_접미사배열.py | py | 196 | python | ko | code | 2 | github-code | 36 |
21107263411 | """Utility functions for building models."""
from __future__ import print_function
import collections
import time
import os
import numpy as np
import tensorflow as tf
from .utils import iterator_utils
from .utils import misc_utils as utils
from .utils import data_utils
__all__ = [
"get_initializer", "get_device... | panchgonzalez/nmor | nmor/model_helper.py | model_helper.py | py | 7,400 | python | en | code | 22 | github-code | 36 |
27513406893 | dict_a = {
'kr': '한국',
'au': '호주',
'jp': '일본',
'us': '미국'
}
tuple_list = sorted(dict_a.items(), key = lambda item: item[1])
keys = []
values = []
for key, value in tuple_list:
keys.append(key)
values.append(value) | yewon-kim/practice-python | locale_practice.py | locale_practice.py | py | 253 | python | en | code | 0 | github-code | 36 |
17904371974 | import pandas as pd
import tensorflow as tf
import psycopg2
import configparser as cf
import numpy as np
import key_driver_analysis as kda
SQL_COLUMN_NAMES = ['nct_id',
'start_date',
'study_type',
'enrollment_type',
'phase',
... | nastacio/clinical-bi | src/main/py/ct_data.py | ct_data.py | py | 8,474 | python | en | code | 0 | github-code | 36 |
2124363907 | import torch
import torch.nn as nn
class RNN_Classifier(torch.nn.Module):
def __init__(self, input_size, hidden_size, output_size, num_layers = 1, batch_first = True, use_gpu = True):
super(RNN_Classifier, self).__init__()
self.hidden_size = hidden_size
self.input_size = input_size
... | nhatleminh1997/ASL_detection | RNN_classifer.py | RNN_classifer.py | py | 1,041 | python | en | code | 0 | github-code | 36 |
3238085621 | from pandas import DataFrame
import csv
import xlwt
import pandas as pd
import numpy as np
data = pd.read_csv("D:\\experiment\\第三次豆瓣\\测试3\\train\\实验数据_clear.csv")
#print(data)
#二维矩阵存每个用户观看不同类别的数量
namedic={"其他": 0, "剧情": 1,"喜剧": 2,"动作": 3,"爱情": 4,"科幻": 5,"动画": 6,"悬疑": 7,"惊悚": 8,"恐怖": 9,"犯罪": 10,"传记": 11,"历史": 12,"战争"... | JiaoZixun/Recommend_By_Canopy-K-means | recommend——豆瓣/step1——统计各用户各类型数量.py | step1——统计各用户各类型数量.py | py | 1,523 | python | en | code | 18 | github-code | 36 |
14537963306 | # 주식 비교 및 분석
# 1. 주식 비교
# 야후 파인낸스 사용
# 필요 라이브러리는 yfinance, pandas-datareader
# 주식 시세 구하는 함수는 get_data_yahoo()
# get_data_yahoo(조회할 주식 종목 [, start=조회 기간의 시작일] [, end=조회 기간의 종료일])
from pandas_datareader import data as pdr
import yfinance as yf
yf.pdr_override()
sec = pdr.get_data_yahoo('063160.KS', start='2020-08-17')
... | drafighter/dra_investar | stock_basic.py | stock_basic.py | py | 655 | python | ko | code | 0 | github-code | 36 |
30835513911 | from voxy.wordcount.wordcount import count_words
def test_word_count():
test_text = """This is a text with some punctuations. And some new lines
and plenty of spaces."""
expected_count = 15
actual_count = count_words(test_text)
assert actual_count == expected_count
| itissid/vxy_coding_challenge | voxy/test/test_word_count.py | test_word_count.py | py | 305 | python | en | code | 0 | github-code | 36 |
18074097517 | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
#
urlpatterns = patterns('',
url(r'^index$', 'Users.views.start'),
url(r'... | ggarri/photoDiary | Users/urls.py | urls.py | py | 512 | python | en | code | 0 | github-code | 36 |
40895132002 | from flask import Flask, render_template, request, Response, url_for,jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_weasyprint import HTML, render_pdf
import ast
import json
import dicttoxml
from datetime import datetime
from model import Reports
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_UR... | webbyfox/suade | app.py | app.py | py | 1,494 | python | en | code | 0 | github-code | 36 |
9376474634 | import numpy as np
import cv2
import sys
from math import sqrt
sys.setrecursionlimit(10000)
class MandelbrotSet:
def __init__(self, size, numColors):
self.size = size
self.c = 0
self.img = np.zeros((size,size,3), dtype='uint8')
self.pallet = []
self.generatePallet(numColors)... | cleiston/Fractals | MandelbrotSet.py | MandelbrotSet.py | py | 1,684 | python | en | code | 0 | github-code | 36 |
73894898984 | __author__ = "Sebastian Heinlein <devel@glatzor.de>"
import datetime
import glob
import gzip
import locale
import logging
import os
import re
import subprocess
import tempfile
import time
import traceback
import uuid
import apt
import apt_pkg
from defer import inline_callbacks, return_value
from defer.utils import d... | thnguyn2/ECE_527_MP | mp4/SD_card/partition1/usr/share/pyshared/aptdaemon/pkcompat.py | pkcompat.py | py | 126,545 | python | en | code | 0 | github-code | 36 |
38197374041 | import matplotlib.pylab as plt
import matplotlib.patches as mpatch
import numpy as np
import pandas as pd
# Get alcohol consumption level and GSP
YEAR = 2009
df = pd.read_csv("cache/niaaa-report.csv")
df = df[df.Year == YEAR]
df2 = pd.read_csv("cache/usgs_state_2009.csv", dtype={"Gross State Product": np.float64},
... | hmly/data-science | demo-analysis/demo-analysis.py | demo-analysis.py | py | 1,586 | python | en | code | 0 | github-code | 36 |
30466359767 | class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
def pathSum(self, root, total):
if not root:
return []
res = []
path = []
self.dfs(root, total, path, res)
return res
def dfs(self,... | dundunmao/LeetCode2019 | 113. binary tree path sum.py | 113. binary tree path sum.py | py | 2,279 | python | en | code | 0 | github-code | 36 |
73974487785 | import random
import unittest
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from accounting_bot.ext.checklist import CheckList, Task, RepeatDelay
class ChecklistTest(unittest.TestCase):
def test_expire(self):
# noinspection PyTypeChecker
checklist = C... | Blaumeise03/AccountingBot | tests/test_checklist.py | test_checklist.py | py | 3,556 | python | en | code | 6 | github-code | 36 |
6771193553 | # 10026
# 적록 색약은 빨강 === 초록으로 인식, 적록 색약인 사람과 아닌 사람이 보는 구역의 수를 출력
import sys
input = sys.stdin.readline
# 로직에 문제 없는데도 계속 뜨는 RecursionError
# 알고보니 파이썬 자체에서 최대 재귀 한도가 적용되어 무한 루프를 발생하지 않도록 막아뒀기 때문에, 재귀 제한이 있다.
# 아래 셋팅을 추가하여 제한을 푼다.
sys.setrecursionlimit(100000)
n = int(input())
matrix = [list(map(str, input())) for _ in ... | chajuhui123/algorithm-solving | BOJ/그래프/230104_적록색약.py | 230104_적록색약.py | py | 2,255 | python | ko | code | 0 | github-code | 36 |
6319889570 | import json
import socket as s
import selectors
import threading
import types
import logging
logger = logging.getLogger("Main." + __name__)
class SocketHandler:
socket = None
sel = selectors.DefaultSelector()
selector_timeout = 4
doShutdown = threading.Event()
connected_sockets = []
handl... | Nickiel12/Church-Programs | Android/android_server/Classes/SocketHandler.py | SocketHandler.py | py | 5,396 | python | en | code | 0 | github-code | 36 |
2848517125 | #############################################################################################################################################
__filename__ = "main.py"
__description__ = """Represents main program.
"""
__author__ = "Anand Iyer"
__copyright__ = "Copyright 2016-17, Anand Iyer"
__credits__ = ["Ana... | ananddotiyer/DDE-Lite | ExcelWriter/main.py | main.py | py | 9,200 | python | en | code | 1 | github-code | 36 |
6543226908 | def find_lis(x): # Sequence[Tuple]) -> List[Tuple]:
"""Find the longest increasing subsequence.
Description of the algorithm and pseudo-code at the link:
https://en.wikipedia.org/wiki/Longest_increasing_subsequence#Efficient_algorithms"""
n = len(x)
p = [0] * n
m = [0] * (n + 1)
# m[0] = -1
l ... | applepie-heidi/biomut-finder | mapper.py | mapper.py | py | 6,475 | python | en | code | 0 | github-code | 36 |
20672750408 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from graph_tool.all import *
import numpy as np
from pathos.multiprocessing import ProcessingPool as Pool
import tqdm
import pickle
def swir(n, z, rho0, kappa, mu, eta, num_ensamble):
pER = z/n
ss = 1 - mu - kappa
ww = 1 - eta
np.random.seed(num_ensamble)... | VolodyaCO/erSWIR | implementation.py | implementation.py | py | 7,234 | python | es | code | 1 | github-code | 36 |
27705271301 | import yfinance as yf
import requests
from datetime import datetime
def calculate_dma(ticker, days):
data = yf.download(ticker, period='1mo')
data['DMA'] = data['Close'].rolling(window=days).mean()
return data
def generate_signal(live_price, dma):
if live_price > dma:
return "buy"
else:
... | vajjhala/dma-btc | dma-btc.py | dma-btc.py | py | 946 | python | en | code | 0 | github-code | 36 |
19258098333 | import time
import Adafruit_ADS1x15
import csv
adc1 = Adafruit_ADS1x15.ADS1115(address=0x48, busnum=1)
adc2 = Adafruit_ADS1x15.ADS1115(address=0x49, busnum=1)
GAIN = 1
sensors = ['MQ135', 'MQ3', 'MQ4', 'MQ2', 'MQ4', 'MQ6', 'MQ7', 'MQ8']
print('Reading ADS1x15 values, press Ctrl-C to quit...')
print("Train... | macoycorpuz/pca-knn-rpi-azotemia | ot/gather.py | gather.py | py | 1,157 | python | en | code | 0 | github-code | 36 |
29595058013 | from fontTools.ttLib import TTFont
import random, copy, os, time, base64
# Measure creation time
start = time.time()
# Read original TTF/OTF font file
f = TTFont('font.ttf')
# Find font's longest CMAP table
cmap = f['cmap']
longestCMAPtable = None
for t in cmap.tables:
if not longestCMAPtable or len(t.cmap) > len(l... | yanone/geheimsprache | geheimsprache.py | geheimsprache.py | py | 1,928 | python | en | code | 12 | github-code | 36 |
26699383365 | # https://www.codewars.com/kata/5254ca2719453dcc0b00027d/train/python
s1 = 'ab'
s2 = 'aabb'
def permutations(string):
s = list(string)
for i, letra in enumerate(s):
s[i] = [s+i]
return s
print(permutations(s2))
| nicorl/codewars | sin terminar/permutations.py | permutations.py | py | 235 | python | en | code | 0 | github-code | 36 |
27338086141 | # inspired from: https://codehandbook.org/how-to-read-email-from-gmail-using-python/
# https://github.com/jay3dec/pythonReadEmail
# Python 3.8^ standard libraries
from traceback import print_exc
from imaplib import IMAP4_SSL
from email import message_from_bytes
from base64 import b64decode
from uuid import uuid4
from ... | PAR-iTY/on-the-spot | python/on-the-spot-mail.py | on-the-spot-mail.py | py | 13,406 | python | en | code | 0 | github-code | 36 |
73139030824 | import numpy as np
from scipy.ndimage import maximum_filter
from operator import itemgetter
# implementation with pure functional procedure
# it could be refactored as object-oriented way....
def find_spot(mesh, N):
""" find view spots in a landscape """
try:
validate_mesh_grid(mesh)
grid = scale_to_grid(... | easz/view_spot_finder | view_spot_finder/finder.py | finder.py | py | 4,367 | python | en | code | 0 | github-code | 36 |
6672720656 | import torch
import torch.nn as nn
from torch.autograd import Variable
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import torch.nn.function... | PRCinguhou/domain-adaptation | train.py | train.py | py | 9,439 | python | en | code | 2 | github-code | 36 |
42236411796 | from pick import pick
import re
import sys
result = ""
selected = []
all_feature = []
def loadDB(filename):
# 加载产生式数据库
dictionary = {}
all = []
global all_feature
with open(filename, 'r') as f:
for line in f.readlines():
# 按行加载
if line[0] == "#":
con... | littlebear0729/Production-system | identify_system.py | identify_system.py | py | 2,137 | python | en | code | 0 | github-code | 36 |
73137151144 | import pytest
from registry_schemas import validate
# Properties can be anything, using show* for testing.
REGISTRATIONS_TABLE = {
'showColumn1': True,
'showColumn2': False,
'showColumn3': True,
'showColumn4': False
}
# Properties can be anything, using misc* for testing.
MISC_PREFERENCES = {
'pr... | bcgov/registry-schemas | tests/unit/common/test_user_profile.py | test_user_profile.py | py | 2,351 | python | en | code | 0 | github-code | 36 |
14128044898 | #!/usr/local/bin/ python3
# -*- coding:utf-8 -*-
# __author__ = "zenmeder"
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNod... | zenmeder/leetcode | 160.py | 160.py | py | 619 | python | en | code | 0 | github-code | 36 |
6911896789 | import json
from pydantic import BaseModel
from pdf_token_type_labels.TokenType import TokenType
from pdf_features.Rectangle import Rectangle
SCALE_RATIO = 0.75
class SegmentBox(BaseModel):
left: float
top: float
width: float
height: float
page_number: int
segment_type: TokenType = TokenType... | huridocs/pdf_metadata_extraction | src/data/SegmentBox.py | SegmentBox.py | py | 1,091 | python | en | code | 2 | github-code | 36 |
8649507511 | """
============================
Author:柠檬班-木森
Time:2020/5/12 20:40
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
import time
import unittest
from selenium import webdriver
from ddt import ddt, data
from web_08day.page.page_login import LoginPage
from web_08day.page.page_index import ... | huchaoyang1991/py27_web | web_08day(web自动化用例编写和PO模式)/testcase/test_login_02.py | test_login_02.py | py | 1,630 | python | en | code | 0 | github-code | 36 |
37558477516 | from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.hashers import make_password, check_password
from superadmin.models import User, UserGroup, Account, AccountChangeLog
from .forms import RawLoginForm
# Create your views here.
def user_login(request):
if request.session.get('us... | lymen/localusermanager | user/views.py | views.py | py | 2,564 | python | en | code | 0 | github-code | 36 |
3224619644 | import random
from os import path
from world_map import *
from game_data import *
from output import *
from shop import Shop
from entity import Entity
from color import Color
class Var():
def __init__(self):
self.running = True
self.ai_turn = True
self.data_slot = 0
self.data_fil... | ihave13digits/PythonTextRPG | var.py | var.py | py | 12,139 | python | en | code | 4 | github-code | 36 |
8546055493 | import random
import pygame as pg
from creature import Creature
def draw_creatures(list):
i= 0
for i in range(len(list)):
list[i].draw()
def replication(creatures, display, border_rect, start_speed,\
start_sense, start_energy, speed_mutation, sense_mutation, nutrition, color):
for creature in ... | lkh-767572/natural-selection-of-traits | methods.py | methods.py | py | 2,031 | python | en | code | 0 | github-code | 36 |
25050666323 | import numpy as np
from teilab.utils import dict2str, subplots_create
from teilab.plot.plotly import boxplot
n_samples, n_features = (4, 1000)
data = np.random.RandomState(0).normal(loc=np.expand_dims(np.arange(n_samples), axis=1), size=(n_samples, n_features))
kwargses = [{"vert":True},{"vert":False}]
title = ", ".joi... | iwasakishuto/TeiLab-BasicLaboratoryWork-in-LifeScienceExperiments | docs/teilab-plot-plotly-2.py | teilab-plot-plotly-2.py | py | 584 | python | en | code | 0 | github-code | 36 |
6270963777 | import unittest
import os
import pandas as pd
from src.chant import Chant
from src.chant import get_chant_by_id
# Load demo chants
CUR_DIR = os.path.dirname(__file__)
ROOT_DIR = os.path.abspath(os.path.join(CUR_DIR, os.path.pardir))
_demo_chants_fn = os.path.join(ROOT_DIR, 'cantus-data', 'chants-demo.csv')
CHANTS = pd... | bacor/ISMIR2020 | tests/test_chant.py | test_chant.py | py | 828 | python | en | code | 4 | github-code | 36 |
43661627525 |
def ordenar(stack):
return len(stack)== 0
def double(x):
y=x*2
return y
a=[5, 6, 9, 8, 7]
for i in range(0, len(a)):
print(a[i])
#bubble
for i in range (0, len(a)+1 -2):
for j in range (0, len(a)+1 - i-2):
x= a[j]
y= a[j+1]
if x > y:
a[j] = y
a[j+1] ... | up210612/UP210612_DSA | Unit 1/section5.py | section5.py | py | 589 | python | en | code | 0 | github-code | 36 |
9661100905 | from __future__ import print_function
import sys
import time
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
from useFunc.detectAndTrack import *
from useFunc.utils import *
from useFunc.featMatch import *
if __name__ == '__main__':
# Params
intv_EM = 4 # interval to implement
# - foc... | dexter2406/MonoVision_MotionEstimation | MoVis_EM.py | MoVis_EM.py | py | 2,416 | python | en | code | 0 | github-code | 36 |
33629829422 | import os, re
root_dir = os.getcwd() + '\\homeworks'
all_dir = os.listdir(root_dir)
with open("file_lists.csv", "a") as file_list:
file_list.write('学生,检索报告,综述论文,Endnote截图,Endnote压缩库,其他\n')
for stu_dir in all_dir:
stu = os.listdir("{0}\\{1}".format(root_dir, stu_dir))
with open("file_lists.csv", "a") as file... | tianyaxin/compare_docx | get_all_file_lists.py | get_all_file_lists.py | py | 1,269 | python | en | code | 0 | github-code | 36 |
29719010517 | from functools import reduce
def flip_data(arr, curr, l):
"""flip the data accounting for wrapping"""
# base case
if l == 1:
return
# get the subset
subset = []
for i in range(l):
n = (curr + i) % len(arr)
subset.append(arr[n])
# reverse
subset = subset[::-1]
... | yknot/adventOfCode | 2017/10_02.py | 10_02.py | py | 2,192 | python | en | code | 0 | github-code | 36 |
16245179877 | # allows for use of bash scripts
import subprocess
#protects password imputs so they are not palin text
import getpass
# import os module
import os
gitHub_address = 'https://github.com/alexboyd92/TestLabScripts.git'
localFileLocation = '/etc/default/isc-dhcp-server'
localGit = '/home'
replacefile = '/home/testlab... | alexboyd92/TestLabScripts | python_scripts/host_install.py | host_install.py | py | 3,612 | python | en | code | 1 | github-code | 36 |
27668133159 | import os
from PIL import Image
def resize_image(path, new_path, width, height, crop_center=True):
'''Image resizing and saving to new path'''
original_image = Image.open(path)
image = original_image if not crop_center else crop_center_image(
original_image)
new_image = image.resize((width, he... | jonathanrodriguezs/image-resizer | image_resizer.py | image_resizer.py | py | 1,177 | python | en | code | 0 | github-code | 36 |
7690070657 | class Node:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
self.hd = 0
def topview(root):
if root == None:
return
q = []
m = dict()
hd = 0
root.hd = hd
q.append(root)
while len(q):
root = q[0]
hd = ... | thisisshub/DSA | O_binary_search_tree/problems/I_top_view_of_binary_tree.py | I_top_view_of_binary_tree.py | py | 964 | python | en | code | 71 | github-code | 36 |
28466775330 | n1=int ( input ( "primera nota:" ) )
n2=int ( input ( "segunda nota:" ) )
n3=int ( input ( "tercera nota:" ) )
n4=int ( input ( "cuarta nota:" ) )
n5=int ( input ( "quinta nota:" ) )
nma=0
nme=0
if n1>n2 and n1>n3 and n1>n4 and n1>n5: nma=n1
elif n2>n1 and n2>n3 and n2>n4 and n2>n5: nma=n2
elif n3>n1 and n... | PBMGC/EJERCICIOS-CONDICIONALES-PYTHON | 10.py | 10.py | py | 744 | python | en | code | 1 | github-code | 36 |
25168937459 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Find the least value of n for which p(n) is divisible by one million.
from __future__ import print_function
import timeit
import sys
try:
range = xrange
except NameError:
pass
start = timeit.default_timer()
sys.setrecursionlimit(25000)
def pent(n):
retu... | tijko/Project-Euler | py_solutions_71-80/Euler_78.py | Euler_78.py | py | 990 | python | en | code | 0 | github-code | 36 |
30988421589 | import json
import os
from flask import Flask, request, jsonify
app = Flask(__name__)
here = os.path.dirname(__file__)
state_path = os.path.join(here, "state.json")
@app.route("/")
def home():
with open(state_path) as f:
return jsonify(json.load(f))
@app.route("/<page>", methods=["GET", "POST"])
def ... | tartopum/atelier | fake_arduino/server.py | server.py | py | 1,307 | python | en | code | 2 | github-code | 36 |
35548614493 | def solution(code):
answer = ''
mode = False
for i in range(len(code)):
if code[i] == '1':
mode = not mode
else :
if mode and i % 2 :
answer += code[i]
if not mode and i % 2 == 0 :
answer += code[i]
if answer == '':
... | ckswls56/BaejoonHub | 프로그래머스/unrated/181932. 코드 처리하기/코드 처리하기.py | 코드 처리하기.py | py | 358 | python | en | code | 0 | github-code | 36 |
20052535936 | from __future__ import print_function
import matplotlib.pylab as plt
import Layer1.NLSVC as svm
import Layer1.learnerV2a as l
import Layer1.RLLSVM as rlvm
#import Layer1.SVMLearner as svm
#import Layer1.RecurrentSVM as rsvm
#import Layer1.Poly_Learner as pl
#import Layer1.MLP_Learner as mlp
import numpy as np
from Laye... | MLRichter/AutoBuffett | layer1_testScript.py | layer1_testScript.py | py | 3,264 | python | en | code | 8 | github-code | 36 |
11486559115 | import tkinter as tk
janela = tk.Tk()
janela.title("Formulário")
janela.geometry("500x400")
def press():
print("Press")
#Nome
Nome = tk.Label(text="Nome:", font=("arial", 16))
Nome.grid(column=0, row=0)
#Input nome
input_nome = tk.Entry()
input_nome.grid(column=0, row=1)
#Idade
idade = tk.Label(text="Idade:",... | LeynilsonThe1st/python | scratches/my_app.py | my_app.py | py | 1,297 | python | pt | code | 0 | github-code | 36 |
36028935609 | import jwt
from .models.models import *
# get_permissions
def get_permissions(user_id):
# check role
user = User.query.get(user_id)
role = user.role
# If role is true then user is admin
if role:
# get all user created lists
user_owned_lists_query = List.query.filter(List.creator_i... | mfragab5890/Irithim-python-flask | src/auth.py | auth.py | py | 7,106 | python | en | code | 0 | github-code | 36 |
74649265384 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import unittest
from BeautifulReport import BeautifulReport
from utils.my_logger import logger
from utils.get_path import *
from scp import SCPClient
import paramiko
import os
import time
def make_report(name):
base_dir = os.path.split(os.path.split(os.path.abspath(__f... | iospeng/python | pycharm_demo/pythonProject2/utils/report.py | report.py | py | 1,550 | python | en | code | 0 | github-code | 36 |
17884436215 | # -*- encoding: utf-8 -*-
"""
说明:由于之前帮助按钮模式做的效果不是很理想,目前计划是做一个新的模块作为临时结局方案
"""
import webbrowser
class helpLinkEngine(object):
def __init__(self):
self.url_dict = {
"dataio_sample_showhelp":'导入其他数据分析软件的工作表?sort_id=3265627'
}
def openHelp(self, tag = ""):
if tag in self.u... | pyminer/pyminer | pyminer/packages/pm_helpLinkEngine/helpLinkEngine.py | helpLinkEngine.py | py | 754 | python | zh | code | 77 | github-code | 36 |
10863350609 | def quicksort(collection: list) -> list:
if len(collection) < 2:
return collection
pivot = collection.pop() #use last item as pivot
greater: list[int] = [] #all elements > than pivot
lesser: list[int] = [] #all elements <= pivot
for element in collection:
(greater if element > pivot ... | TotallyNotTito/ForFun | quicksort.py | quicksort.py | py | 650 | python | en | code | 0 | github-code | 36 |
27338793613 | from math import sqrt
def prime(n):
sq=int(sqrt(n))
for p in range(2,sq+1):
if n%p==0:
return False
if n==2*p+1:
return True
for i in range(2,sq+1):
if n%i==0:
return False
return True
n=int(input())
print(prime(n))
| GeethaBhavani28/python-programming | safe prime.py | safe prime.py | py | 319 | python | en | code | 0 | github-code | 36 |
581853 | # edad = int(input("Escribe tu edad: "))
# if edad >= 18:
# print("Eres apto para entrar")
# else:
# print("No eres apto para entrar")
# numero = int(input("Escribe un numero: "))
# if numero > 100:
# print("Es mayor a 100")
# elif numero == 100:
# print("Es igual a 100")
# else:
# print("Es menor ... | eliecerangel/practicas | CONDICIONALES.py | CONDICIONALES.py | py | 854 | python | es | code | 0 | github-code | 36 |
7289309011 | import networkx as nx
import json
import matplotlib.pyplot as plt
import sys
from collections import defaultdict
from networkx.algorithms import bipartite
import numpy as np
import mmsbm
import time
import pickle
def parse_reviews(review_file, business_ids):
user_ids = []
reviews = defaultdict(list)
stars = {}
i =... | jonnymags/Networks-project | yelp.py | yelp.py | py | 5,362 | python | en | code | 0 | github-code | 36 |
42534845706 | # c_units.py
# V0.5.0 LDO 19/10/2022: initial version
# V0.5.1 LDO 12/11/2022: refactor modules
'''
grafanacode: Grafana unit formats.
See `categories.ts <https://github.com/grafana/grafana/blob/main/packages/grafana-data/src/valueFormats/categories.ts>`_
Use::
import c_units as UNITS
unit... | DOSprojects/grafanacode | grafanacode/c_units.py | c_units.py | py | 11,206 | python | en | code | 0 | github-code | 36 |
27635586847 | from codenames.data.codenames_pb2 import ActionOutcome
from codenames.data.codenames_pb2 import Role
from codenames.data.codenames_pb2 import SharedAction
from codenames.data.codenames_pb2 import SharedClue
from codenames.data.types import Codename
from codenames.data.types import EndTurn
from codenames.data.types impo... | ealt/Codenames | codenames/game/game.py | game.py | py | 3,650 | python | en | code | 0 | github-code | 36 |
17520933988 | # coding:utf-8
import unittest
import ddt
import os
import requests
from common import base_api
from common import readexcel
from common import writeexcel
from common.readexcel import ExcelUtil
curpath = os.path.dirname(os.path.realpath(__file__))
textxlsx = os.path.join(curpath,"demo_api.xlsx")
report_path = os.path... | fangjiantan/PostTest | Testcase/test_api.py | test_api.py | py | 1,065 | python | en | code | 0 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.