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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
9547326563 | import os
from sld.configs import Config
import numpy as np
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
from tensorflow.keras.callbacks import TensorBoard
from tensorflow.keras.utils import to_c... | hyeonslove/SignLanguageDetection | utils/training.py | training.py | py | 1,604 | python | en | code | 1 | github-code | 1 |
37775266673 | # 숫자와 문자를 구별하는 법이 궁금하다
def solution():
data = input()
result = []
value = 0
# 문자를 하나씩 확인하며
for x in data:
# 알파벳인 경우 결과 리스트에 삽입
if x.isalpha():
result.append(x)
# 숫자는 따로 더하기
else:
value += int(x)
# 알파벳을 오름차순으로 정렬
result.sort()
... | sangeon-ahn/thisiscodingtest | 구현/문자열 재정렬/문자열 재정렬.py | 문자열 재정렬.py | py | 987 | python | ko | code | 0 | github-code | 1 |
39087752641 | class Solution(object):
def twoSum(self, nums, target):
numsMap = {}
for i, num in enumerate(nums):
complement = target - num
if complement in numsMap:
return [i, numsMap[complement]]
numsMap[num] = i
if __name__ == "__main__":
solution = ... | BastienLaby/leetcodeSolutions | problems/two-sum.py | two-sum.py | py | 377 | python | en | code | 0 | github-code | 1 |
22919970401 | import torch
import numpy as np
import torch.nn as nn
import os, gc
os.environ["CUDA_VISIBLE_DEVICES"] = '0'
import warnings
warnings.filterwarnings(action='ignore', category=DeprecationWarning)
warnings.simplefilter("ignore", UserWarning)
from VAD_module import VAD, Scheduler, add_loss
from utils import Speec... | Yifei-ZHAO96/STAM-pytorch | train_STAM.py | train_STAM.py | py | 9,476 | python | en | code | 7 | github-code | 1 |
4403027049 | #!/usr/bin/python
# INSERTION-SORT(A)
# for j = 2 to A.length
# key = A[j]
# // Insert A[j] into the sorted sequence A[1..j - 1].
# i = j - 1
# while i > 0 and A[i] > key
# A[i+1] = A[i]
# i = i - 1
# A[i + 1] = key
def insert_sort_asce(array):
for j in range(1, len(array), 1):
... | myisjon/study-algorithms | base/python/sort/insert_sort.py | insert_sort.py | py | 1,025 | python | en | code | 0 | github-code | 1 |
20539075614 | """
Curve Fit example
@luis.fernandes
#Nov 20 2019
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def lorentzian(x, amplitude, x0, sigma, background):
# A lorentzian peak with:
# Constant Background : background
# Proportional t... | OSHI7/Learning1 | LM/fit.py | fit.py | py | 2,118 | python | en | code | 0 | github-code | 1 |
74583620193 | # -*- coding : utf-8 -*-
from dateutil.relativedelta import relativedelta
from datetime import datetime, timedelta
from odoo import fields, models, api, tools, _
from odoo.exceptions import Warning, UserError, ValidationError
class custom_partner(models.Model):
_inherit = "res.partner"
@api.multi
def _dr... | lawrence24/e_order | models/custom_partner.py | custom_partner.py | py | 11,031 | python | en | code | 0 | github-code | 1 |
39510695868 | # input 문자열
info = input()
# 문자를 담을 리스트
stack = []
# 갯수 체크
cnt = 0
# enumerate 로 index와 value 값을 가져옴
for i,v in enumerate(info):
# 여는 괄호일 경우
if v == "(":
# 스택에 index 값 추가
stack.append(i)
# 레이저인지 막대인지 모르지만 갯수 추가
cnt += 1
# 닫는 괄호가 나왔을 경우
else:
# check 라는 변수에 stack의 ... | choikeunyoung/algorithm | 백준/Silver 2/10799.py | 10799.py | py | 831 | python | ko | code | 1 | github-code | 1 |
43513488678 | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
'''
方法:贪心算法
分析:
if 总油量>=总消耗量,则表示 该车可以跑完全程
if 当前 加油站的油量gas[i] > 耗油量 cost[i]
说明他可以作为 初始加油站 继续往下跑
else 该加油站非 初始加油站,只能选择下一个
''... | km1994/leetcode | topic17_greedy/T134_canCompleteCircuit/interview.py | interview.py | py | 1,045 | python | zh | code | 24 | github-code | 1 |
24245139725 | #!/usr/bin/env python
"""Truncation beautifier function
This simple function attempts to intelligently truncate a given string
"""
__author__ = 'Kelvin Wong <www.kelvinwong.ca>'
__date__ = '2007-06-22'
__version__ = '0.10'
__license__ = 'LGPL v.2.1 http://www.gnu.org/licenses/lgpl.html'
def trunc(s,min_pos=0,max_pos=7... | UO-OACISS/tau2 | tools/src/perfexplorer/examples/MicroLoadImbalance/trunc.py | trunc.py | py | 3,386 | python | en | code | 34 | github-code | 1 |
17341410745 | from flask import Flask,request
from flask.helpers import make_response
from flask.json import jsonify
import qrcode
import json
from PIL import Image
app = Flask(__name__)
app.config.from_pyfile("settings.py")
baseUrl = "http://10.0.2.2:5000"
@app.route("/home")
def home():
list = []
list.append(createPrevie... | cnatom/MeiTuanAndroidAppServer | app.py | app.py | py | 3,976 | python | en | code | 6 | github-code | 1 |
12539332954 | from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from . import models, forms
def show_all_posts(request):
"""
This view will show all of the posts
"""
my_posts = models.Post.objects.all()
return render(
request=request,
contex... | javadkhd/JavadKhadem_HWs_M50 | message/blog/views.py | views.py | py | 884 | python | en | code | 0 | github-code | 1 |
22919346325 | ######################################################
# 8,330: Machine Learning (MiQEF)
# Assignment 3: kNN Algorithm
# Niklas Leander Kampe | 16-611-618
######################################################
# Utility Libraries
import math
import warnings
import numpy as np
import pandas as pd
from sklearn.model_sel... | nikampe/Machine_Learning | Assignment 3/kNN Algorithm - Niklas Kampe.py | kNN Algorithm - Niklas Kampe.py | py | 4,660 | python | en | code | 2 | github-code | 1 |
10107790749 | # coding=utf-8
# Author:fan hongtao
# Date:2020-11-22
import codecs
import time
import segment_dic
import segment_hmm
import pos_tag
class eval:
def __init__(self):
# 加载分词器和词性标注模型
self.Segment_dic = segment_dic.segment()
self.Segment_hmm = segment_hmm.segment()
self.Pos_tag = po... | HavEWinTao/BIT-CS | 自然语言理解初步/big1/Source/evaluate.py | evaluate.py | py | 3,606 | python | en | code | 1 | github-code | 1 |
1076817932 | # -*- coding: utf-8 -*-
from __future__ import print_function
import os
from formation import AtomicTemplate, Template
OUTPUT_FILE = os.path.join(
os.path.dirname(os.path.dirname(__file__)),
"output",
"004_vpc_in_template.yaml"
)
def main():
template = Template()
vpc = AtomicTemplate("VPC", "... | jamesroutley/formation | test/fixtures/example/004_vpc_in_template.py | 004_vpc_in_template.py | py | 432 | python | en | code | 0 | github-code | 1 |
71992212513 | """Support functions to write and read data."""
import os
from enum import Enum
from pathlib import Path
import yaml
from scm.plams import Molecule as PlamsMolecule
from scm.plams.interfaces.adfsuite.ams import AMSResults
from osp.core.cuds import Cuds
from osp.core.namespaces import crystallography, emmo
# from osp.... | simphony/reaxpro-wrappers | osp/tools/io_functions.py | io_functions.py | py | 27,357 | python | en | code | 0 | github-code | 1 |
21905826955 | # -*- coding: utf-8 -*-
import re
import os
import traceback
from core.utils import sectionToMap, readlines
def match(filename):
filename = os.path.basename(filename)
return filename == 'zabbix_server.conf' or filename == 'zabbix_proxy.conf'
def run(filename):
tmp = {'DBHost': 'localhost', 'DBPort': 3306}
res... | CaledoniaProject/src-scan | modules/config_parser/zabbix.py | zabbix.py | py | 625 | python | en | code | 1 | github-code | 1 |
43406778979 | from tkinter import *
from PIL import ImageTk,Image
root = Tk()
root.title("Learn to code")
root.iconbitmap(r'C:\Users\tomry\GraphicUserInterface\wifi.ico')
# Odkaz: https://www.youtube.com/watch?v=YXPyB4XeYLA&list=PLWKjhJtqVAbnqBxcdjVGgT3uVR10bzTEB&index=2
def open():
global my_img
top = Toplevel()
to... | BlackRou/GraphicUserInterface | base.py | base.py | py | 684 | python | en | code | 0 | github-code | 1 |
19545085642 | import math
from functools import reduce
f = [x.rstrip('\n').split(',') for x in open('buses.txt').readlines()]
times = []
positions = []
total = 0
for y, x in enumerate(f[1]):
if x != 'x':
times.append(int(x))
positions.append(y)
current = 0
for pos in range(1, len(times)):
done = False
whi... | Patchkat/Advent-Of-Code-2020 | Day 13/AoC13B.py | AoC13B.py | py | 664 | python | en | code | 0 | github-code | 1 |
72797707875 | # Import heapq
from heapq import *
# Function to return the merged sorted array
def mergeKSortedArrays(kArrays):
# List to store merged elements
merged = []
# Initialize minheap
minheap = []
# Traverse over arrays
for i, array in enumerate(kArrays):
# Check for empty arrays
i... | DataRohit/Data-Structures-and-Algorithms | 22_heaps/12_merge_sorted_arrays.py | 12_merge_sorted_arrays.py | py | 1,262 | python | en | code | 1 | github-code | 1 |
15226306609 | import numpy
def parse(filename):
image = []
part = []
file = open(filename,"r")
lines = file.readlines()
for line in lines:
coord = line.rstrip("\n").split(",")
if(len(coord) == 1):
if(len(part) != 0):
image.append(part)
part = []
... | chandraseta/grafika-opengl | Task-2/src/svgparser.py | svgparser.py | py | 1,016 | python | en | code | 0 | github-code | 1 |
12036768402 | from django.shortcuts import render, redirect
from . import models
from . import forms
from django.contrib.auth.decorators import permission_required
# Create your views here.
def Product(request, _product_id):
category_parents = models.Category_parent.objects.order_by("order")
product = models.Product.object... | AndresGroselj/Ultrahardware | Ultrahardware/products/views.py | views.py | py | 4,306 | python | en | code | 0 | github-code | 1 |
30211290727 | from __future__ import annotations
import logging
from ._apik import validate_api_key
from ._kafka import KafkaProducer
try:
KAFKA_PRODUCER = KafkaProducer()
except Exception as exc:
logging.exception(exc)
KAFKA_PRODUCER = None # type: ignore
def add_query_ingest_impl(api_key: str, body: bytes) -> boo... | bloomberg/datalake-query-ingester | src/bloomberg/datalake/datalakequeryingester/_request_handler.py | _request_handler.py | py | 493 | python | en | code | 7 | github-code | 1 |
13354811915 | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
graph = defaultdict(list)
in_degree = defaultdict(int)
for edge in prerequisites:
graph[edge[1]].append(edge[0])
in_degree[edge[0]] += 1
... | Biruk-Tassew/Competitive_programming | 210-course-schedule-ii/210-course-schedule-ii.py | 210-course-schedule-ii.py | py | 819 | python | en | code | 0 | github-code | 1 |
30051399636 | from django.test import TestCase
from datasets.models import RADataEntry
from datasets.serializers import RADataEntrySerializer
class RADataRecordSerializerTestCase(TestCase):
fixtures = ['set.json', 'record.json', 'entry.json', 'member.json']
serializer_class = RADataEntrySerializer
@classmethod
de... | quanttide/django-quanttide-data | example/datasets/tests/test_serializers_entry.py | test_serializers_entry.py | py | 989 | python | en | code | 0 | github-code | 1 |
74618324832 | """This submodule handles the cli-like utilities such as the parser
"""
import argparse
class RadolanParser(argparse.ArgumentParser):
def __init__(self):
super().__init__(
description="Training U-Net model for segmentation of RADOLAN precipitation images"
)
self.add_arguments... | Campostrini/dwd_dl | dwd_dl/cli.py | cli.py | py | 4,660 | python | en | code | 2 | github-code | 1 |
38861082488 | from loaders.dataloader_mnist import load_mnist
from models.model_vae import VariationalInference, VariationalAutoencoder
from models.distributions import ReparameterizedDiagonalGaussian
import torch
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
sns.set_style("whitegrid")
### TEST DISTRIBU... | nikolasborrel/dlmusic | misc/tests_vae.py | tests_vae.py | py | 2,588 | python | en | code | 0 | github-code | 1 |
11520253260 | import xml.etree.ElementTree
import xml_share as xshare
import os
class xml_share_repository:
"""
Stores the information read from xml for easy access.
"""
xml_shares = []
def built_up_repository(self, share_file=os.path.dirname(__file__) + '/shares.xml'):
"""
Fill the reposit... | postmanisonline/pyShares | xml_share_repository.py | xml_share_repository.py | py | 2,807 | python | en | code | 0 | github-code | 1 |
46356953091 | from flask import Flask, render_template, request, redirect
from mysqlconnection import connectToMySQL
app = Flask(__name__)
mysql = connectToMySQL('friendsdb')
@app.route('/')
def index():
result = mysql.query_db("select * from players")
return render_template("index.html", entry = result)
if __name__=="__ma... | RamS2k/Python | Players and Slams/server.py | server.py | py | 350 | python | en | code | 0 | github-code | 1 |
6167365766 | # Se crea un diccionario vacío llamado 'calificaciones'.
calificaciones = {}
# Se actualiza el diccionario 'calificaciones' con dos pares clave-valor.
calificaciones.update({"Laura": 3.7, "Sebastian": 4.5})
# Se crea un nuevo diccionario 'calificaciones' con un par clave-valor.
calificaciones = {
'nombre': 'Marlo... | marlon172004/python | dicFun/Diccionarios/ejercicio3.py | ejercicio3.py | py | 1,189 | python | es | code | 0 | github-code | 1 |
37621288464 | def app():
import pandas as pd
from operator import itemgetter
import glob
import streamlit as st
pd.options.mode.chained_assignment = None
st.header('Master List of LPI')
files = glob.glob('*.xlsx')
appended_data = []
leagueList = []
for file in files:
leagueName = fil... | LouieR3/FantasyFootballApp | pages/10_LPI_Master_List.py | 10_LPI_Master_List.py | py | 1,670 | python | en | code | 2 | github-code | 1 |
73688763873 | import numpy as np
import h5py
import pickle
def get_emb(word, h):
if word in h:
return h[word]
else:
return h['__UNK__']
path = 'data/semeval16/laptop/text_vocab.vocab'
with open(path, 'r') as f:
with open('data/semeval16/laptop/text_vector.pkl', 'rb') as pkl_file:
h = pickle.lo... | gangeshwark/Attention_Based_LSTM_AspectBased_SA | create_word_emb_matrix.py | create_word_emb_matrix.py | py | 635 | python | en | code | 28 | github-code | 1 |
7961996580 | import math
import numpy as np
import pandas as pd
import random
import itertools as itr
import os
from pathlib import PurePath
from scipy.sparse import coo_matrix
from scipy.spatial import distance_matrix
import scipy.stats as sts
from sklearn.preprocessing import normalize
import time
import functools
import operat... | jb-chaudron/Neural-Gas-MCMC | fonction.py | fonction.py | py | 11,525 | python | en | code | 0 | github-code | 1 |
72362825953 | load(
"//rules:utils.bzl",
"ANDROID_TOOLCHAIN_TYPE",
)
load("@bazel_skylib//lib:paths.bzl", "paths")
load(":common.bzl", _common = "common")
load(":java.bzl", _java = "java")
_density_mapping = {
"ldpi": 120,
"mdpi": 160,
"hdpi": 240,
"xhdpi": 320,
"xxhdpi": 480,
"xxxhdpi": 640,
"tv... | bazelbuild/rules_android | rules/bundletool.bzl | bundletool.bzl | bzl | 10,103 | python | en | code | 165 | github-code | 1 |
12803267686 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 13 00:14:35 2018
@author: liuchuang
"""
import numpy as np
a = np.arange(10)
### 1 通过下标范围产生数组 和原数组共享数据空间
b=a[::-1] ## 步长为负数 倒序
c=a[3:7] ### 左开右闭
### 2 通过整数序列 元素选取 每个元素作为下标 获得新数组 不共享空间
d=a[[1,2,3,5]]
a[[1,2,3]]=4,5,6
print(a,b,c,d)
#... | LiuChuang0059/python_practise | python_lib/Numpy/numpy_save_use.py | numpy_save_use.py | py | 529 | python | zh | code | 43 | github-code | 1 |
41013348872 | filename = "Inputs/" + __file__.strip("py") + "txt"
with open(filename, "r") as file:
data = [line.strip() for line in file.readlines()]
def Part1():
numVisible = len(data) * 2 + len(data[0]) * 2 - 4
for i in range(1, len(data) - 1):
for j in range(1, len(data[i]) - 1):
tree = int(data... | ThomasCulotta/Advent2022 | Day08.py | Day08.py | py | 1,708 | python | en | code | 0 | github-code | 1 |
12782304510 | # Definition for a binary tree node.
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def add_left_child(self, value):
self.left = TreeNode(value)
def add_right_child(self, value):
self.right = TreeNode(value)... | tranphibaochau/LeetCodeProgramming | Medium/binary_tree_vertical_traversal.py | binary_tree_vertical_traversal.py | py | 948 | python | en | code | 0 | github-code | 1 |
9391112971 | '''
Created on Feb 13, 2014
@author: theo
'''
import os
from django.core.management.base import BaseCommand, CommandError
from acacia.data.models import Project, ProjectLocatie, MeetLocatie, Datasource, Parameter, Series
from django.conf import settings
class Command(BaseCommand):
args = ''
help = 'Deletes un... | tkleinen/acaciadata | acacia/acacia/management/commands/cleanup.py | cleanup.py | py | 1,613 | python | en | code | 0 | github-code | 1 |
8716232323 | from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^login/$', views.authentication, name="authentication"),
url(r'^logout$', auth_views.logout, {'next_page': '/'}, name="logout", ),
url(... | chrisar12/Tesis_App | SituacionSalud/urls.py | urls.py | py | 1,458 | python | en | code | 0 | github-code | 1 |
23028915325 | class SolapamientoLaberinto:
def __init__(self, tablero):
self.tablero = tablero
def verificar(self, posiblePos):
caminoB = False
virusB = False
metaB = False
dict = self.tablero.dictCuadros
for piso in dict['camino']:
(pisoX, pisoY) = (piso.posicion... | alejandro-llanganate/Proyecto_2020A_Modelamiento | src/laberinto/solapamientoLaberinto.py | solapamientoLaberinto.py | py | 1,310 | python | es | code | 0 | github-code | 1 |
33847984940 | def IRRIGADOR(ONOFF: str):
if ONOFF == "ON":
pins.digital_write_pin(DigitalPin.P0, 1)
else:
pins.digital_write_pin(DigitalPin.P0, 0)
def on_bluetooth_connected():
basic.show_string("C")
bluetooth.on_bluetooth_connected(on_bluetooth_connected)
def on_bluetooth_disconnected():
basic.show... | Turma-Robotica/Projeto-Horta | Garden_Microbit.py | Garden_Microbit.py | py | 2,005 | python | en | code | 0 | github-code | 1 |
22022271593 | def solution(s):
answer = []
s_li = s.split(" ")
for i in s_li:
tmp_li = []
for j in range(0,len(i)):
if j % 2 == 0 :
tmp_li.append(i[j].upper())
else :
tmp_li.append(i[j].lower())
tmp_li="".jo... | sunyeongan/TIL | 프로그래머스/lv1/12930. 이상한 문자 만들기/이상한 문자 만들기.py | 이상한 문자 만들기.py | py | 412 | python | en | code | 2 | github-code | 1 |
44533595681 | from grt.core import Constants
constants = Constants()
class Intake:
"""
Intake mechanism, with roller motor, two independent angle
change motors and 4 (left front/rear, right front/rear) limits
"""
motor_power = 1
def __init__(self, roller, achange_left, achange_right,
acha... | grt192/2014aerial-assist | py/grt/mechanism/__init__.py | __init__.py | py | 5,007 | python | en | code | 0 | github-code | 1 |
2121705474 | import os
from datetime import date
import dateutil
from src.examples.program.traccar.config.config import Config
from src.examples.program.traccar.config.keys import Keys
class MediaManager:
_LOGGER = "LoggerFactory.getLogger(MediaManager.class)"
def __init__(self, config):
self._path = None
... | sofialucca/thesisResearch | src/examples/program/traccar/database/mediaManager.py | mediaManager.py | py | 1,536 | python | en | code | 0 | github-code | 1 |
10992674316 | # Programa simples para testar os sensores
# Importa as bibliotecas
import time
import board
import adafruit_dht
# from board import D18
# Inicialização do dispositivo no pino:
dht_device = adafruit_dht.DHT11(board.D18)
#Para ler do DHT22
#dht_device = adafruit_dht.DHT22(<pin>)
while True:
try:
# Para l... | Miyake-Diogo/rpi-sensors-to-cloud | only-sensors/dht11_standard.py | dht11_standard.py | py | 647 | python | pt | code | 1 | github-code | 1 |
23671007568 | import numpy as np
import matplotlib.pyplot as plt
def test_polyreg_univariate():
'''
Test polynomial regression
'''
# load the data
filepath = "./test.txt"
df = pd.read_csv(filepath, header=None)
X = df[df.columns[:-1]]
y = df[df.columns[-1]]
# regression with degree = d
... | spapazov/regression | test/test_poly_reg.py | test_poly_reg.py | py | 1,163 | python | en | code | 0 | github-code | 1 |
41402696786 | from datetime import date
from typing import List, Optional
from pydantic import BaseModel
class UserBase(BaseModel):
email: str
username: str
tanggal_lahir: date
alamat: str
status: Optional[str]
no_telp: str
class UserUpdate(BaseModel):
email: Optional[str]
username: Optional[str]... | vaniaalya14/rpl | sql_app/schemas.py | schemas.py | py | 1,046 | python | en | code | 0 | github-code | 1 |
17575244199 | import requests
from bs4 import BeautifulSoup
import pandas as pd
import pathlib
import datetime
def fetch(which):
url = 'https://isin.twse.com.tw/isin/C_public.jsp'
param = dict(
exchange={'strMode':'2'},
otc={'strMode':'4'})
response = requests.get(url, param[which])
assert response.s... | you-ming-hu/Stock_Trend_Analysis | Stocky/Database/agent/overview/core.py | core.py | py | 4,298 | python | en | code | 0 | github-code | 1 |
44933547743 | from gensim.models import KeyedVectors
import image_read as image_read
import pandas as pd
import re
import numpy as np
from ast import literal_eval
'''
This class receives the image,
performs the similarity and recommends the quotes
'''
class QuoteFinder:
def __init__(self, path):
self.path = path
... | pran4ajith/quote-learning | quote_finder.py | quote_finder.py | py | 1,663 | python | en | code | 0 | github-code | 1 |
5580413154 | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.http import HttpResponseRedirect
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'tsune.views.home', name='home'),
# url(r'^tsune/'... | DummyDivision/Tsune | tsune/urls.py | urls.py | py | 1,281 | python | en | code | 3 | github-code | 1 |
4768490540 | """
Leetcode 144
Given a binary tree, return the preorder traversal of its nodes' values.
Recursive solution is trivial, could you do it iteratively?
"""
class Node:
def __init__(self, v):
self.val = v
self.left = None
self.right = None
def preorder_iterative(root):
stack, res = [], []... | btjd/coding-exercises | binary_tree/preorder_traversal.py | preorder_traversal.py | py | 1,217 | python | en | code | 0 | github-code | 1 |
25462663318 | #!/usr/bin/python3
"""
Module 3-say_my_name.py with the function say_my_name
"""
def say_my_name(first_name, last_name=""):
"""Functions that prints a complete name in a sentence"""
if type(first_name) is not str:
raise TypeError('first_name must be a string')
elif type(last_name) is not str:
... | dalejohgi/holbertonschool-higher_level_programming | 0x07-python-test_driven_development/3-say_my_name.py | 3-say_my_name.py | py | 434 | python | en | code | 0 | github-code | 1 |
11510286902 | # Released under the MIT License. See LICENSE for details.
#
"""Functionality related to managing cloud based assets."""
from __future__ import annotations
from typing import TYPE_CHECKING, Annotated
from dataclasses import dataclass, field
from pathlib import Path
import threading
import urllib.request
import loggin... | efroemling/ballistica | src/assets/ba_data/python/babase/_assetmanager.py | _assetmanager.py | py | 7,331 | python | en | code | 468 | github-code | 1 |
71188285794 | from pyspark import SparkContext
from pyspark.sql import SparkSession
class SparkSpawner:
@classmethod
def get_spark(self) -> SparkSession:
spark_builder = SparkSession.builder.appName('BigDW')\
.enableHiveSupport() \
.config("spark.jars.packages","io.delta:delta-core_2.11:0.5.... | FP-DataSolutions/DeltaWarehouse | src/utils/spark_spawner.py | spark_spawner.py | py | 689 | python | en | code | 5 | github-code | 1 |
37083046284 | import scapy.all as sp
import datetime as dt
class TCPDumpHelper:
def __init__(self, p):
self.path = p
# with Jan 1 1970 as reference, the exp_day is the no of seconds till experiment day
self.exp_day = 1539388800
self.ist_hour = 5
self.ist_mins = 30
self.Mac_IP_Ma... | samvram/wmn_track3_helper | TCPDumpHelper.py | TCPDumpHelper.py | py | 6,699 | python | en | code | 0 | github-code | 1 |
2775757377 | """
https://leetcode.com/problems/sort-array-by-parity/
"""
from typing import List
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
write_p = 0
for i in range(len(A)):
if A[i] % 2 == 0:
A[i], A[write_p] = A[write_p], A[i]
write_... | alexparunov/leetcode_solutions | src/900-1000/_905_sort-array-by-parity.py | _905_sort-array-by-parity.py | py | 345 | python | en | code | 1 | github-code | 1 |
26535774253 | from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QObject, pyqtSlot, QThread, pyqtSignal, QRectF, QRect, QPointF, QLocale
import sys
from collections import OrderedDict
import pyqtgraph as pg
import numpy as np
from easydict import EasyDict as edict
class Viewer2DBasic(QObject):
sig_double_click... | Attolab/FAB1_LIZARD | 220317_backup/pymodaq/daq_utils/plotting/viewer2D/viewer2d_basic.py | viewer2d_basic.py | py | 9,024 | python | en | code | 0 | github-code | 1 |
33094392198 | import solution
from sortedcontainers import SortedList
import bisect
class Solution(solution.Solution):
def solve(self, test_input=None):
nums, k, t = test_input
return self.containsNearbyAlmostDuplicate(list(nums), k, t)
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""
... | QuBenhao/LeetCode | problems/220/solution.py | solution.py | py | 1,941 | python | en | code | 8 | github-code | 1 |
21615992825 | from django.test import TestCase
from core.models import User, ActivityPeriod
from core.views import get_user_data_by_id, get_all_user_data, get_user_activity_details
class UserTestCase(TestCase):
def test_user(self):
with self.assertRaises(User.DoesNotExist):
user_1 = User.objects.get(id="W... | Mangy007/full-throttle-labs-api | core/tests.py | tests.py | py | 1,030 | python | en | code | 0 | github-code | 1 |
25258516529 | from __future__ import absolute_import
from flask import current_app
from .builder import JenkinsBuilder
class JenkinsGenericBuilder(JenkinsBuilder):
def __init__(self, master_urls=None, *args, **kwargs):
self.script = kwargs.pop('script')
self.cluster = kwargs.pop('cluster')
self.path =... | harrisonfeng/changes | changes/backends/jenkins/generic_builder.py | generic_builder.py | py | 1,685 | python | en | code | null | github-code | 1 |
665845198 | from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
# print report
coffee_machine = CoffeeMaker()
money_machine = MoneyMachine()
menu_items = Menu()
machine_is_on = True
while machine_is_on:
order = menu_items.get_items()
# prompt user to make an order
... | paulmureithi/Python-Bootcamp | coffee_machine_oop/main.py | main.py | py | 1,010 | python | en | code | 0 | github-code | 1 |
70195295073 | import matplotlib.pyplot as plt
import numpy as np
from fluids.fittings import entrance_rounded, entrance_rounded_methods
rcs = np.linspace(0,0.4, 1000)
for method in entrance_rounded_methods:
Ks = [entrance_rounded(Di=1.0, rc=rc, method=method) for rc in rcs]
plt.plot(rcs, Ks, label=method)
plt.legend()
plt.... | CalebBell/fluids | docs/plots/entrance_rounded_plot.py | entrance_rounded_plot.py | py | 446 | python | en | code | 306 | github-code | 1 |
30322019110 | import cv2
import os
for root, dirs, files in os.walk('pai/1/'):
# print(root)
# print(dirs)
# print(files)
if (files):
for item in files:
img = cv2.imread(os.path.join('pai/1', item))
rows, cols = img.shape[:2]
M = cv2.getRotationMatrix2D((cols / 2, rows / ... | huilizhou/Deeplearning_Python_DEMO | image_preprocess/pre_img_warp_20181017.py | pre_img_warp_20181017.py | py | 449 | python | en | code | 0 | github-code | 1 |
31663210078 | import gym
import numpy as np
from stable_baselines3.common.env_checker import check_env
from stable_baselines3.common.callbacks import BaseCallback
from stable_baselines3 import DQN
env = gym.make('navi_env:navi-env-v0')
train = True
new_train = True
model_name = "distance_matters"
steps = 10000
class ... | engelmannakos/onlab | dqn.py | dqn.py | py | 1,661 | python | en | code | 0 | github-code | 1 |
30355678992 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error,mean_squared_error
from keras.models import Model,Sequential
from keras.layers import Dense,Activation
df = pd.read_excel('AL_WIND_07_12.... | Jabor047/Deep-Learning-and-Machine-Learning-Competitions | Zindi Africa/Wind Power predictions/lineareg.py | lineareg.py | py | 1,220 | python | en | code | 0 | github-code | 1 |
31914585274 | from __future__ import absolute_import
import datetime
import json
import os
import requests
import simpy
from celery.utils.log import get_task_logger
from DLP.celery import app
from DLP.settings import BASE_DIR
from dlp.apis.api_weather import can_fly, ALLOW
from dlp.file_manager.file_manager import get_site_url, \... | xavics/DLP | dlp/tasks.py | tasks.py | py | 5,131 | python | en | code | 2 | github-code | 1 |
955910411 | # coding: utf-8
"""
SnapTrade
Connect brokerage accounts to your app for live positions and trading
The version of the OpenAPI document: 1.0.0
Contact: api@snaptrade.com
Created by: https://snaptrade.com/
"""
from datetime import date, datetime # noqa: F401
import decimal # noqa: F401
import f... | passiv/snaptrade-sdks | sdks/python/snaptrade_client/model/status.py | status.py | py | 3,639 | python | en | code | 3 | github-code | 1 |
42739885025 | import argparse
from ccc_client.dcs.DcsRunner import DcsRunner
from ccc_client.utils import print_API_response
def run(args):
runner = DcsRunner(args.host, args.port, args.authToken)
for i in args.cccId:
r = runner.create_link(args.setId, i)
print_API_response(r)
parser = argparse.ArgumentP... | ohsu-comp-bio/ccc_client | ccc_client/dcs/cli/create_link.py | create_link.py | py | 659 | python | en | code | 0 | github-code | 1 |
22475012122 | class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) == 1: return True
if nums[0] == 0: return False
target = len(nums) - 1
state = [0] * target
state[0] = nums[0]
for i in range(1, le... | Brady31027/leetcode | 55_Jump_Game/jump_game.py | jump_game.py | py | 444 | python | en | code | 1 | github-code | 1 |
30294953 | from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import speech
import imaplib
fromadd = "mmanibalan2@gmail.com"
def send():
speech.voice("To whom")
a = speech.speech()
print("done")
speech.voice("mail")
body = speech.speech()
p... | manibalanM/manibalan-chan | mail.py | mail.py | py | 1,702 | python | en | code | 1 | github-code | 1 |
70342956194 | import logging
import os
import termcolor
# Success log level
SUCCESS = 25
def configure_logging(level=logging.INFO, use_color=True):
"""
Configure te global logging settings.
"""
override_level = os.environ.get('S2EENV_LOG_LEVEL', None)
if override_level:
level = logging.getLevelName(o... | S2E/s2e-env | s2e_env/utils/log.py | log.py | py | 2,179 | python | en | code | 89 | github-code | 1 |
3662992089 | import requests
#设置代理
proxy = {
'http':'218.65.254.114',
'https':'175.148.72.52:1133'
}
url = 'https://httpbin.org/get'
response = requests.get(url,proxies=proxy)
print(response.status_code)
print(response.text)
#使用私密代理
# proxy = {
# 'http':''
# } | 1615961606/-test | 备份/1804爬虫/第一周/第四天/request_proxy.py | request_proxy.py | py | 279 | python | en | code | 0 | github-code | 1 |
13211031237 | from SIZR import *
from scitools.std import PiecewiseConstant # using this to shorten
# implementation of E, alpha and beta
problem = ProblemSIZR(S0=60,I0=0,Z0=1,R0=0,
E = PiecewiseConstant(domain=[0,33],
data=[(0, 20), (... | simehaa/University | inf1100/Night_of_the_Living_Dead.py | Night_of_the_Living_Dead.py | py | 993 | python | en | code | 0 | github-code | 1 |
5891336974 | a = int(input())
a =[int(i) for i in input().split()]
a =[0, 0]
for i in range(l - 2, - 1, - 1):
if(a[i]== 0):
a.append(a[i])
else :
a.append(a[i])
ans = 0
for i in range(len(a)):
if(a[i]== 0):
count = count + 1
else :
j = a[i]
print(ans)
| ds4an/CoDas4CG | GeneratedPrograms/CoasetoFine/pre/39.py | 39.py | py | 251 | python | en | code | 13 | github-code | 1 |
72933274915 | def pc(num, total):
if num == 0: return '0%'
if num == total: return '100%'
s = "%.1f%%" % (100.0 * num / total)
if s == '0.0%':
return '<0.1%'
elif s == '100.0%':
return '99.9%'
else:
return s
def fc(num):
return "{:,}".format(int(num))
def int2str(num):
sbl = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
base = len(... | iitis/mutrics | common.py | common.py | py | 456 | python | en | code | 5 | github-code | 1 |
4607144250 | import tkinter as tk
import os
import tkinter.ttk as ttk
from board import MainBoard, SettingBoard, open_setting
import tkinter.font as tkFont
import webbrowser
from logic import get_map_path, get_setting
from constants import *
MAP_PATH = get_map_path()
size, cr = get_setting(JSON_NAME)
win = tk.Tk()
win.title("ra... | BigShuang/ra3-map-browser | gui.py | gui.py | py | 1,826 | python | en | code | 0 | github-code | 1 |
6021296254 | from typing import Set, List
import argparse
import itertools
import numpy as np
import cv2
import os
ALLOWED_EXT = [".jpg", ".JPG", ".png", ".PNG", ".jpeg", ".JPEG"]
AVAILABLE_ALGORITHMS = ["dhash", "humming"]
def read_args():
parser = argparse.ArgumentParser()
parser.add_argument("folder", help="Path to a... | EvgeniiTitov/detectors | scripts/duplicates_detector.py | duplicates_detector.py | py | 6,038 | python | en | code | 1 | github-code | 1 |
38120283463 | import numpy as np
import cv2
#calling and storing the file for face recognition
face_cascade=cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml')
cap=cv2.VideoCapture(0)
while True:
ret,frame=cap.read()
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)#cascade works on gray
#fa... | Jindalkaran/OpenCv | e_face_detection.py | e_face_detection.py | py | 1,181 | python | en | code | 1 | github-code | 1 |
32964384592 | from ConfigSpace import Constant, UniformFloatHyperparameter, UniformIntegerHyperparameter, CategoricalHyperparameter, \
EqualsCondition
from skorch.callbacks import LRScheduler
from torch import nn
from torch.optim import AdamW, Adam
from .skorch_base import SkorchBaseModel
class MLP(nn.Module):
def __init... | automl/AutomlCup2023 | models/base_models/mlp_model.py | mlp_model.py | py | 4,522 | python | en | code | 2 | github-code | 1 |
33751812156 | import sys
from os.path import dirname, abspath
sys.path.append(dirname(dirname(dirname(abspath(__file__)))))
import unittest
import thread
import beanstalkc
import simplejson
from scavengers.scavenger import Scavenger
from scavengers.scavenger_utils import OK_CODE, NOT_FOUND_ERROR_CODE
from scavengers.google_plus_sca... | andreisoare/droopy | scavengers/test/google_plus_test.py | google_plus_test.py | py | 1,751 | python | en | code | 0 | github-code | 1 |
13392283616 | import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=12, ncols=3, figsize=(30, 100))
def getAvg(df):
res = pd.Series(np.zeros(128))
for x in df:
res += df[x]
res /= (len(list(dfH)) - 1)
return res
subject_nums = [
'04', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15'... | ezhang7423/CS192 | vis.py | vis.py | py | 1,463 | python | en | code | 0 | github-code | 1 |
2905485311 | #백준 1978 소수 찾기
n = int(input()) #입력받을 숫자의 개수
data = list(map(int, input().split())) #소수 판별 숫자 입력
count = 0 #결과값 변수
for x in data: #data 값 전체 조회
for i in range(2, x+1): # 최소 소수 2부터 최대값까지 조회
if x % i == 0: #소수 인 경우
if x == i:
count += 1
break
print(count) | excel42/Python_practice | 1978.py | 1978.py | py | 412 | python | ko | code | 0 | github-code | 1 |
18973686604 | import os
import sys
from datetime import datetime
import logging
import shutil
from spotcam_utils.config_helper import ConfigHelper
class DirectoryHelper():
def __init__(self, CAMERA_NAME, DATE = datetime.now()):
self.CAMERA_NAME = CAMERA_NAME
self.DATE = DATE
self.HOME = os.environ['HOME... | andrewchiull/get-camera-video_POM | spotcam_utils/directory_helper.py | directory_helper.py | py | 1,625 | python | en | code | 2 | github-code | 1 |
74730464352 | def tringle_type(l1, l2, l3):
type = ""
if l1 + l2 <= l3 or l2 + l3 <= l1 or l1 + l3 <= l2 or l1 < 0 or l2 < 0 or l3 < 0:
print("i lati del triangolo non sono validi")
else:
type = "isocele"
if l1 != l2 and l1 != l3:
type = "scaleno"
elif l1 == l2 and l1 =... | CristianCerutti/Compiti_Vacanze_Sistemi | triangle.py | triangle.py | py | 472 | python | en | code | 0 | github-code | 1 |
24099043056 | import requests
import json
url = 'https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5'
response = requests.get(url)
json_data = json.loads(response.text)
string_out = ''
for data in json_data:
buy = data['buy']
sale = data['sale']
string_out +=f'Покупка: {buy} - Продажа: {sale}\n'
print(string_out... | mikh-maksi/python-autocourse | pasing/parse_pb.py | parse_pb.py | py | 335 | python | en | code | 0 | github-code | 1 |
8530202683 | import torch
import os
def save_tuple(state, next_state, action, reward, is_terminal, path, t):
s_prime_aux = state
s_prime_aux = s_prime_aux.detach().cpu().type(torch.uint8)
s_aux = next_state
s_aux = s_aux.detach().cpu().type(torch.uint8)
action_aux = action
action_aux = action_aux.... | riordan45/rl-edge-of-stability | utils/save_tuple.py | save_tuple.py | py | 854 | python | en | code | 0 | github-code | 1 |
18978794914 | #!/usr/bin/env python
from webapps.util import documents, formatters
from webapps.sml.lib import common, datalayer
from webapps.sml.resources import func
import pprint
def processGet(dl, data, baseurl, encoding, user):
fmt = data['format'].lower() if 'format' in data else None
questions = {}
answers ... | andrewchoi5/Angular-Project | resources/products.py | products.py | py | 5,286 | python | en | code | 0 | github-code | 1 |
32525669806 | import requests
from lxml import html
# 创建 session 对象。这个对象会保存所有的登录会话请求。
session_requests = requests.session()
# 提取在登录时所使用的 csrf 标记
login_url = "http://www.chechebijia.com/api/user/login/"
payload = {
"phone": "13811848104",
"password": "cnt82562288",
"operateType": 0
}
# 执行登录
result = session_requests.post(
log... | anjiayin/test | login.py | login.py | py | 880 | python | en | code | 0 | github-code | 1 |
6913184410 | from profile import Profile
from os import unlink
from io import StringIO
import pstats
def calibrate(n):
"""
https://docs.python.org/3/library/profile.html#calibration
"""
if n > 0:
pr = Profile()
magics = []
for i in range(n):
magics.append(pr.calibrate(10000))
... | vstinner/python-ptrace | ptrace/profiler.py | profiler.py | py | 1,232 | python | en | code | 172 | github-code | 1 |
11735270517 | import tensorflow.compat.v1 as tf
import posenet
import cv2
import keyboard
class Tracker():
def capture_pose_gen(self):
model = posenet.load_model_keras(101, model_dir='./converted_models/saved_model')
cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)
cv2.namedWin... | ImpulseFitnessCode/ExcerciseTracker | tracker.py | tracker.py | py | 1,449 | python | en | code | 0 | github-code | 1 |
1149391347 | def chkdic(cDict,val):
a=0
for x in cDict.keys():
if val == cDict[x]:
a=x
break
return a
def uniqueValues(aDict):
'''
aDict: a dictionary
returns: a sorted list of keys that map to unique aDict values, empty list if none
'''
# Your code here
... | ChienSien1990/Python_collection | Dictionary/Dictionary_unique_value.py | Dictionary_unique_value.py | py | 783 | python | en | code | 0 | github-code | 1 |
72070561954 | states = {"Andhra Pradesh": "AP", "Arunachal Pradesh": "AR", "Assam": "AS", "Bihar": "BR", "Chattisgarh": "CT",
"Chhattisgarh": "CT", "Goa": "GA", "Gujarat": "GJ", "Haryana": "HR", "Himachal Pradesh": "HP",
"Jharkhand": "JH", "Jharkhand#": "JH", "Karnataka": "KA", "Kerala": "KL", "Madhya Pradesh": "... | harshasridhar/covid-cases-prediction | constants.py | constants.py | py | 2,015 | python | en | code | 0 | github-code | 1 |
41489675162 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 9 09:54:35 2020
Calculating number of pixels for hull convex area
@author: Rafael Yassue
"""
import cv2
import numpy as np
import os as os
from skimage.morphology import convex_hull_image
import pandas as pd
import matplotlib.pyplot as plt
os.chdir("G:\\My Drive... | RafaelYassue/Root-phenotyping | python/HULL.py | HULL.py | py | 1,098 | python | en | code | 2 | github-code | 1 |
2017416865 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 5 08:58:15 2021
@author: apa
"""
# prime number
for num in range(2,10):
#print("Testing", num)
prime=True
for div in range(num-1,1,-1):
if num%div==0:
prime=False
break
if prime==True:
print("Prime: ", num)
else:
... | asselapathirana/pythonbootcamp | archives/2021/day2/prime_dev1.py | prime_dev1.py | py | 357 | python | en | code | 0 | github-code | 1 |
1444812705 |
class ActionSegmentSamplingTracker:
def __init__(self, lecture_name, segment_length):
self.segments = []
self.counts_per_class = {}
self.frame_start = None
self.lecture_name = lecture_name
self.segment_length = segment_length
def add_frame(self, frame_idx, label):
... | adaniefei/AccessMath_Pose | AccessMath/speaker/util/action_segment_sampling.py | action_segment_sampling.py | py | 6,875 | python | en | code | 1 | github-code | 1 |
21585286375 | #!/usr/local/bin/python3
import numpy as np
import pandas as pd
import psycopg2 as pg
import sys, os, re
from collections import defaultdict
from matplotlib import pyplot as plt
import os, sys, datetime, argparse, pytz, glob, logging, re, csv, operator, math, logging.handlers
from dy8_signals import *
class Stats:
d... | chenxu0602/ChinaFutures | dy8_stats.py | dy8_stats.py | py | 3,455 | python | en | code | 2 | github-code | 1 |
16144823426 | import unittest
import pygame
import database
from ui.renderer import Renderer
from sprites.ball import Ball
from sprites.paddle import Paddle
from eventhandler import EventHandler
from gameloop import GameLoop
class TestGameloop(unittest.TestCase):
def setUp(self):
DISPLAY_WIDTH = 800
DISPLAY_HEIG... | katajak/ot-harjoitustyo | src/tests/gameloop_test.py | gameloop_test.py | py | 2,393 | python | en | code | 0 | github-code | 1 |
42689748720 | import numpy as np
from scipy.spatial.distance import cdist
from collections import defaultdict
from sace.sace import SACE
class CaseBasedSACE(SACE):
def __init__(self, variable_features, weights=None, metric='euclidean', feature_names=None,
continuous_features=None, categorical_features_lists... | riccotti/Scamander | sace/casebased_sace.py | casebased_sace.py | py | 9,044 | python | en | code | 5 | github-code | 1 |
75201389472 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
# Created by Jianguo on 2017/10/23
__author__ = "Jianguo Jin (jinjianguosky@hotmail.com)"
"""
Description:
Person
字段
属性
方法
"""
from datetime import date, datetime
class Person:
def __init__(self, name, age, birthdate,... | skyaiolos/SeleniumWithPython | OOP/employee.py | employee.py | py | 1,134 | python | en | code | 1 | github-code | 1 |
71975823393 | # mongodb supported languages
mongodb_supported_languages = (
'da','nl','en','fi','fr','de','hu','it',
'nb','pt','ro','ru','es','sv','tr'
)
# key:language abbreviation
# value:language name equivalent supported by nltk SnowballStemmer
language_long_name = {
'da': 'danish',
'nl': 'dutch',
'en': 'engl... | esdairiM/stats_project_youtube_comments | src/datastore/languagesAbreviationMapping.py | languagesAbreviationMapping.py | py | 739 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.