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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
71719419537 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
df = pd.read_csv('countries.csv')
df_mex = df[df.country == "Mexico"]
df_mex.plot.scatter(x='year', y='lifeExp')
x = np.asanyarray(df_mex[['year']])
y = np.asanyarray(df_mex[['lifeExp']])
model = linear_mo... | CEOE1996/AI-Practices | Regresion Lineal Simple.py | Regresion Lineal Simple.py | py | 464 | python | en | code | 0 | github-code | 13 |
3697943037 | #
# Filename: http_server.py
# Author: Harrison Hubbell
# Date: 09/01/2014
# Description: Is responsible for serving data over HTTP
#
from socketserver import ThreadingMixIn
from multiprocessing import Process, Lock
from . import exception, handler
import logging
import http.server
import io
import ... | hhubbell/smartkeg | smartkeg/http/http.py | http.py | py | 8,112 | python | en | code | 0 | github-code | 13 |
7277561194 | import numpy as np
import mne
import matplotlib
import matplotlib.pyplot as plt
from scipy import stats
from mne.stats import fdr_correction, bonferroni_correction
def Stats_Sigs(G1, G2, numbins, name, mode):
# G1: Pre-Stim. File with all subjects
# G2: Pos-Stim. File with all subjects
# numbins: Number of windows whe... | RobertoFelipeSG/PhD | Stats_Sigs.py | Stats_Sigs.py | py | 4,527 | python | en | code | 1 | github-code | 13 |
24154314534 | from fastapi import APIRouter
from loguru import logger
from models.Users import UserIn
from repositories.users import UserRepository
user_router = APIRouter()
@user_router.post("/create/")
async def create_user(user_in: UserIn):
"""
Эндпоинт для создания юзера
:param user_in: Pydantic модель
:r... | ilnrzakirov/parts_service | endpoint/user_endpoints.py | user_endpoints.py | py | 1,269 | python | ru | code | 1 | github-code | 13 |
72216420499 | import urllib2
from beautifulsoup import listTexts
from regexp import processNames, processDates
#from pygoogle import pygoogle
def getAnswers(query):
results={}
urllist=[]
#g = pygoogle("What is your problem")
#g.pages = 1
#urllist = g.get_urls()
urllist.append("http://www.politifact.com/texas/statem... | genjinoguchi/softdev_homework_1 | search.py | search.py | py | 928 | python | en | code | 0 | github-code | 13 |
21580336835 | import os
import re
from util import *
from glob import glob
# from utilCapacity import get_capacity
LIMIT_NUM = 20
Brand_list_1 = [i.strip() for i in set(open("Labels/148_brand_list_1", encoding="utf-8").readlines())]
Brand_list_2 = [i.strip() for i in set(open("Labels/148_brand_list_2", encoding="utf-8").rea... | liuyubiao/test_2 | category/category_148.py | category_148.py | py | 32,413 | python | en | code | 0 | github-code | 13 |
1795467621 | from django.core.cache import cache as _cache
class CachedProperty(property):
"""
Decorator much like django cached_property however it also caches to a
'real' cache and exposes some additional functionality for setting/deleting
the cache value along with the ability to perform additional actions when... | greenbender/django-gravy | gravy/functional.py | functional.py | py | 2,769 | python | en | code | 2 | github-code | 13 |
23777951058 | import pandas as pd
import numpy as np
from scipy.spatial.distance import cdist
from pyproj import Transformer
# See other answer about the always_xy=True parameter
TRAN_3008_TO_4326 = Transformer.from_crs("EPSG:3008", "EPSG:4326")
def mytransform(lat, lon):
return TRAN_3008_TO_4326.transform(lat, lon)
... | VASYD-SOU/pool_detection | pool_coordinates.py | pool_coordinates.py | py | 3,720 | python | en | code | 0 | github-code | 13 |
7006543605 | from .base_page import BasePage
from .locators import BasketPageLocators
class BasketPage(BasePage):
def get_products_in_basket(self):
products = []
for product in self.browser.find_elements(*BasketPageLocators.ITEMS_IN_BASKET):
products.append(product.text)
return products | KatherineSycheva/test-project-for-stepik-course | pages/basket_page.py | basket_page.py | py | 317 | python | en | code | 0 | github-code | 13 |
17048375564 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AnttechBlockchainTwcUserinfoMatchModel(object):
def __init__(self):
self._alipay_user_id = None
self._call_no_hash = None
self._unify_no = None
self._unify_no_hash... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/AnttechBlockchainTwcUserinfoMatchModel.py | AnttechBlockchainTwcUserinfoMatchModel.py | py | 2,535 | python | en | code | 241 | github-code | 13 |
42478298444 | #! /usr/bin/env python3
from __future__ import print_function
import argparse
import glob
import os
from datetime import date
import shutil
import sys
import subprocess
import logging
import click
from .log import get_logger
from .filename import parse_filename, format_filename
from .tags import get_tags, set_tags
... | paulgessinger/document_helpers | src/document_helpers/sort.py | sort.py | py | 2,576 | python | en | code | 0 | github-code | 13 |
9018666298 | import socket
target_host = "127.0.0.1"
target_port = 8080
#ソケットオブジェクトの作成
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.bind(('127.0.0.3', 8080))
#サーバーへ接続
client.connect((target_host, target_port))
#データの送信
client.send(b"Data by TCP Client!!")
#データの受信
response = client.recv(4096)
print("success... | ryu1998/Security_Practice | base practice/tcp_client.py | tcp_client.py | py | 427 | python | ja | code | 0 | github-code | 13 |
42650474578 | # -*- coding: UTF-8 -*-
from datetime import datetime
from pprint import pprint
db = {}
with open('trd.csv', 'r') as f:
for row in f:
r = row.split(',')
t = datetime.time(datetime.strptime(r[0].split('.')[0], '%I:%M:%S'))
b = r[3].replace('\n', '')
del r[3]
del r[0]
if b in db.keys():
i... | EvgeniyUS/dataParsing | trd.py | trd.py | py | 930 | python | en | code | 0 | github-code | 13 |
32859296908 | #!/usr/bin/env python3
import re
from urllib.parse import unquote, urlparse, parse_qs
from html import unescape
from .. import Unit
from ...lib.decorators import unicoded
class urlguards(Unit):
"""
Restores the original URLs from their 'protected' versions as generated by
Outlook protection and ProofPoin... | chubbymaggie/refinery | refinery/units/pattern/urlguards.py | urlguards.py | py | 1,609 | python | en | code | null | github-code | 13 |
1362431235 | # -*-coding:Utf-8 -*
#Tests de conditions
#mon_age = 5
#if mon_age > 20:
# print("Tu as bien grandi!")
#elif mon_age >= 16:
# print("et tu est meme presque majeur")
# if mon_age == 17:
# print("Well done!!")
#else:
# print("Okayyyy")
#Test de predicat
#age = 20
#majeur = False
#if age >= 18:
# majeur... | Gilloufcr/MacGyvrer | Tests_Cours/cours.py | cours.py | py | 1,442 | python | fr | code | 0 | github-code | 13 |
17053042714 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class InsMktObjectDTO(object):
def __init__(self):
self._obj_id = None
self._type = None
@property
def obj_id(self):
return self._obj_id
@obj_id.setter
def obj... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/InsMktObjectDTO.py | InsMktObjectDTO.py | py | 1,236 | python | en | code | 241 | github-code | 13 |
28599897220 |
from numpy import *
import astropy.io.fits as pyfits
for i in range(8):
hdu=pyfits.open('non_drizzled-image-{0}.fits'.format(i+1),mode = 'update')
hdu[0].header["EXPTIME"]=1
hdu.flush()
psf=pyfits.open('non_drizzled_psf-{0}.fits'.format(i+1),mode = 'update')
psf[0].header["EXPTIME"]=1
psf.flush()
hdu=pyfits.ope... | dartoon/my_code | projects/Sim_HST_JWST/drizzle_F160W_temp/header.py | header.py | py | 411 | python | en | code | 0 | github-code | 13 |
38755701782 | # coding=utf-8
# author= YQZHU
from django.conf.urls import url, include
from . import crawler_views
urlpatterns = [
url(r'^keywords$', crawler_views.list_keywords.as_view(), name='keywords-list'),
url(r'^keywords/add$', crawler_views.keyword_add.as_view(), name='keyword-add'),
url(r'keyword/(?P<pk>[0-9... | lianhuness/django1 | crawler/crawler_urls.py | crawler_urls.py | py | 404 | python | en | code | 0 | github-code | 13 |
41419137844 | import warnings
import jax
import jax.numpy as jnp
import flax
import numpy as np
from jax.experimental import PartitionSpec as P
from jax.experimental.compilation_cache import compilation_cache as cc
from transformers import (
AutoTokenizer,
GenerationConfig
)
from . import FlaxCodeGenRLForCausalLM, CodeGenR... | xingyaoww/LeTI | leti/models/jax_inferencer.py | jax_inferencer.py | py | 8,947 | python | en | code | 58 | github-code | 13 |
7832621083 | # -.- coding:latin1 -.-
# @author : Nicolas
""" Ce code analyse les données de l'expérience maison sur le pendule et
fourni les graphiques et les résultats voulus
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def f(x, a, b):
return a * x + b
l = 1... | dslap0/Universite-Python | PHY1501/LabPendule.py | LabPendule.py | py | 4,083 | python | fr | code | 0 | github-code | 13 |
5823390151 | import azure.functions as func
from azure.identity import DefaultAzureCredential
from azure.mgmt.storage import StorageManagementClient
from azure.mgmt.storage.models import StorageAccountCreateParameters
def main(req: func.HttpRequest) -> func.HttpResponse:
nomeSito = req.params.get('nomeSito') ... | Progetto-SRS/function-app | functions/create-account-storage/__init__.py | __init__.py | py | 2,495 | python | en | code | 0 | github-code | 13 |
42040326279 |
from gtts import gTTS
import os
def t2s (text):
mytext = text
language = 'en'
myobj = gTTS(text=mytext, lang=language, slow=False)
myobj.save("welcome.mp3")
os.system("nvlc welcome.mp3")
t2s(input()) | yazidmarzuk/SchoolAR | shibu2.py | shibu2.py | py | 243 | python | en | code | 0 | github-code | 13 |
24772158924 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import dataloader.cifar10
import dataloader.dogs
import dcgan
def train_cifar10():
print('*** DCGAN trained with cifar10 ***')
data = dataloader.cifar10.load('cifar10')['img']
model = dcgan.DCGAN(data)
try:
model.train(steps=3000)
except Excep... | Linyxus/dcgan | main.py | main.py | py | 840 | python | en | code | 4 | github-code | 13 |
42514113295 | #default parameter
def area(radius,pi = 3.14):
result = pi * radius * radius
return result
def main():
rvalue = 10.5
pivalue = 3.14
#positinal argument
ans =area(rvalue,pivalue)
print("Atre of circle : ",ans) # ans=area(10.5,3.14)
#keyword argument
ans = area(ra... | Shantanu-gilbile/Python-Programs | default.py | default.py | py | 746 | python | en | code | 0 | github-code | 13 |
74815216336 |
import argparse
class TaskQueueServer:
def __init__(self, ip, port, path, timeout):
pass
def run(self):
pass
def parse_args():
parser = argparse.ArgumentParser(description='This is a simple task queue server with custom protocol')
parser.add_argument(
'-p',
action="s... | VadimPushtaev/applied-python | homeworks/task_queue/server.py | server.py | py | 1,063 | python | en | code | 86 | github-code | 13 |
31202975330 | from queue import PriorityQueue
class Edge(object):
def __init__(self, v, w):
self.dst = v
self.weight = w
# vertex in a graph
class Vertex(object):
def __init__(self, u):
self.key = u
self.adj_list = []
# vertex in dijkstra
class Vex(object):
def __init__(self, u, dist... | fanweneddie/algorithm_lab | lab5/source/Dijkstra.py | Dijkstra.py | py | 2,419 | python | en | code | 0 | github-code | 13 |
5400105284 | # %%
import numpy as np
import torch
# Input (temp, rainfall, humidity)
inputs = np.array([[73, 67, 43],
[91, 88, 64],
[87, 134, 58],
[102, 43, 37],
[69, 96, 70]], dtype='float32')
# Targets (apples, oranges)
targets = np.array([[56, 70],
... | a23956491z/deep-learning-research | python/pytorch-practice/linear_regression/linear_regression.py | linear_regression.py | py | 1,904 | python | en | code | 0 | github-code | 13 |
70268966418 | from six import iteritems
import ducky.config
import ducky.devices.terminal
import ducky.errors
import ducky.log
import ducky.machine
from .. import TestCase, mock, common_run_machine
def common_case(**kwargs):
machine_config = ducky.config.MachineConfig()
input_section = machine_config.add_device('input', 'duc... | happz/ducky-legacy | tests/devices/terminal.py | terminal.py | py | 1,655 | python | en | code | 5 | github-code | 13 |
393434243 | import sqlite3
import telebot
bot_token = '5961557186:AAFOKKlACzYLZ0PWxKCeu5KOqtIqDLMLhuw'
bot = telebot.TeleBot(bot_token)
5
@bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(message, "ادخل الاسم الاول")
@bot.message_handler(func=lambda message: True)
def search_person(m... | jobaeyyuiij/jojo | source.py | source.py | py | 1,636 | python | en | code | 0 | github-code | 13 |
11434178693 | from application_services.imdb_artists_resource import IMDBArtistResource
from application_services.UsersResource.user_service import UserResource, AddressResource
from application_services.imdb_users_resource import IMDBUserResource
from database_services.RDBService import RDBService as RDBService
from middleware impo... | YowKuan/E6156-team-project | UserService/app.py | app.py | py | 4,806 | python | en | code | 0 | github-code | 13 |
10859699605 | #https://www.acmicpc.net/problem/1874
#스택, 그리디
#스택에 원소를 삽입할 때는 단순히 특정 수에 도달할 때까지 삽입
#스택에서 원소를 연달아 빼낼 때 내림차순을 유지할 수 있는지 확인
n = int(input())
count = 1
stack = []
result = []
for _ in range(n): #원소 개수만큼 반복
num = int(input())
while count <= num: #입력받은 숫자에 도달할 때까지 삽입
stack.append(count)
count +=... | wooryung/Coding-Test | BOJ/BOJ1874(other).py | BOJ1874(other).py | py | 815 | python | ko | code | 0 | github-code | 13 |
72727934099 | #!/usr/bin/python3
'''
Plot differences for samples from uncertainty analysis.
'''
import operator
import os.path
import sys
from matplotlib import colorbar
from matplotlib import colors
from matplotlib import gridspec
from matplotlib import pyplot
from matplotlib import ticker
from matplotlib.backends import backend... | janmedlock/HIV-95-vaccine | plots/differences.py | differences.py | py | 5,922 | python | en | code | 1 | github-code | 13 |
26964761785 | # 1202 Program Alarm
from DataGetter import get_data
from Ship import IntcodeComputer
from Timer import timer
DAY = 2
data = get_data(DAY)
data = [i for i in map(int, data.strip('\n').split(','))]
def _comp(comp, noun, verb):
comp.overwrite_intr(noun, 1)
comp.overwrite_intr(verb, 2)
comp.compute()
val = comp.re... | SvbZ3r0/Advent-of-Code | 2019/day02.py | day02.py | py | 793 | python | en | code | 0 | github-code | 13 |
72089356818 | import transformers
from transformers.models.pegasus.tokenization_pegasus_fast import PegasusTokenizerFast
from qag_pegasus.min_ref_loss_model import CustomPegasusForConditionalGeneration
import unicodedata as ud
import torch
class QAGPegasus:
def __init__(self, model_name_or_path: str):
self.tokenizer = P... | XuanLoc2578/QAG | qag_pegasus/__init__.py | __init__.py | py | 1,896 | python | en | code | 0 | github-code | 13 |
23890113304 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import xrange
import pickle
import random
import tensorflow as tf
# Prepares a vocabulary and a set of training files filled with
# tf.SequenceExamples.
flags = tf.app.flags
FLAGS = flags.FLA... | sanchom/tensorflow_learning | char_rnn/create_sequence_examples_from_text.py | create_sequence_examples_from_text.py | py | 3,480 | python | en | code | 1 | github-code | 13 |
35793799269 |
class groupby(object):
# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
def __init__(self, iterable, key=None):
if key is None:
key = lambda x: x
self.keyfunc = key
self.it = iter(iterable)
... | greshem/develop_python | group_by_src.py | group_by_src.py | py | 933 | python | en | code | 1 | github-code | 13 |
25059133690 | import turtle
import pandas
screen = turtle.Screen()
screen.title("U.S. States Game")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
data = pandas.read_csv("50_states.csv")
score = 0
states_list = []
while score != 50:
user_answer = screen.textinput(title=f"{score}/50 S... | Dhyan-P-Shetty/us-states-game | main.py | main.py | py | 1,032 | python | en | code | 0 | github-code | 13 |
20337166874 | #!/usr/bin/env python
# coding: utf-8
# # The Multidimensional Knapsack Problem
# Mohammed Alagha, July 2021
#
# Glasgow, UK
# A mathematical model for the MKP problem.
# Modeled using IBM CPLEX
# In[1]:
# Importing relevant libraries
import cplex
from docplex.mp.model import Model
# In[2]:
# # Import the ... | AghaMS/Multidimensional_Knapsack_Problem_Modelling | MKP_Math_Model.py | MKP_Math_Model.py | py | 1,235 | python | en | code | 1 | github-code | 13 |
35361389754 | # Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
while ... | FeiZhan/Algo-Collection | answers/leetcode/Binary Search Tree Iterator/Binary Search Tree Iterator.py | Binary Search Tree Iterator.py | py | 856 | python | en | code | 3 | github-code | 13 |
7658707202 | class Solution:
def countAndSay(self, n: int) -> str:
if (n == 1):
return "1"
res = self.countAndSay(n-1)
newRes = ""
lastChar = res[0]
count = 1
for char in range(1, len(res)):
if (res[char] == lastChar):
count += 1
... | pamtabak/LeetCode | 38_count_and_say.py | 38_count_and_say.py | py | 510 | python | en | code | 0 | github-code | 13 |
74164706256 | # %% Imports
import os
os.chdir('../ssl_neuron/')
import json
import pickle
import numpy as np
import pandas as pd
from tqdm import tqdm
import matplotlib.pyplot as plt
import networkx as nx
from allensdk.core.cell_types_cache import CellTypesCache
from ssl_neuron.datasets import AllenDataset
from sklearn.preprocess... | felixp8/bmed7610-final-project | analysis/ephys_regression.py | ephys_regression.py | py | 17,259 | python | en | code | 0 | github-code | 13 |
9205029493 | import sys
import os
from numpy import fmax
from utils import optimizer_utils, image_utils
import torch
from torchvision.transforms import transforms
import scipy.ndimage
from datasets.ffhq import process_image
def add_batch(image: torch.Tensor):
while len(image.shape) < 4:
image = image.unsqueeze(0)
... | VioletSabers/HairEditing | src/faceparsing.py | faceparsing.py | py | 3,889 | python | en | code | 8 | github-code | 13 |
17160637242 | import sys
sys.stdin = open('input.txt')
T = int(input())
for tc in range(1, T+1):
N = int(input())
count = [0] * 201
# 시작 부터 끝점까지 각각 count를 올린다
# 그럼 겹치는 횟수가 각 복도에 나올 것이고
# 이의 최대 값이 곧 걸리는 시간이 된다.
result = 0
for _ in range(N):
start, end = map(int, input().split())
... | jiyong1/problem-solving | swea/4408/solution.py | solution.py | py | 879 | python | ko | code | 2 | github-code | 13 |
17228653899 | import torch
import random
# 二进制交叉熵损失函数的稳定版本 用来实现数值的稳定 log+sum+exp
def bce_loss(input, target):
"""
Numerically stable version of the binary cross-entropy loss function.
As per https://github.com/pytorch/pytorch/issues/751
See the TensorFlow docs for a derivation of this formula:
https://www.tensor... | ZhoubinXM/project_of_article | losses.py | losses.py | py | 5,279 | python | en | code | 0 | github-code | 13 |
19651257225 | import copy
import datetime
import json
import requests
from django.conf import settings
class WeatherDataProcessor:
"""Class to process weather data retrieval from an external API.
Manages fetching weather data based on user input and classifies it as historical or forecast data.
"""
def __init__(... | yurii-onyshchuk/WeatherApp | weather_app/services/weather_api_service.py | weather_api_service.py | py | 7,778 | python | en | code | 0 | github-code | 13 |
8866019641 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 8 12:00:24 2019
@author: james
"""
import os
import numpy as np
import pandas as pd
import time
import datetime as dt
from copy import deepcopy
import re
def list_dirs(path):
"""
list all directories in a given directory
args:
... | jamesmhbarry/PVRAD | pvcal_invert2rad/data_process_functions.py | data_process_functions.py | py | 73,297 | python | en | code | 1 | github-code | 13 |
9483909766 | #!/usr/bin/env python
# -*- encoding:utf-8 -*-
import time
import os
import argparse
from googletranslate.googletranslate import main as gtranslate
def translate_text(text, verbose=False):
class Args:
target: str = 'zh-CN'
query: str = ''
host: str = 'translate.google.com'
proxy:... | liuyug/code_example | gtranslate.py | gtranslate.py | py | 3,520 | python | en | code | 0 | github-code | 13 |
75052989456 | class Solution:
def maxPathSum(self,root):
maxpath=float("-inf")
def maxPath(node):
nonlocal maxpath
if node:
leftmax=max(maxPath(node.left),0)
rightmax=max(maxPath(node.right),0)
currMaxPath=node.val+leftmax+rightmax
maxpath=max(maxpath,currMaxPath)
return node.val+ max(leftmax,rig... | Roy263/SDE-Sheet | BTreeMaxPathSum/maxpathsum.py | maxpathsum.py | py | 500 | python | en | code | 0 | github-code | 13 |
9513085506 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import urllib
import urllib.parse
from pymongo.results import UpdateResult
import config.db
import crawler.base
class IndexCrawler(crawler.base.BaseCrawler):
"""
index
"""
def _save(self, item):
c = config.db.connect()
... | plusplus1/louischa | crawler/novels/index.py | index.py | py | 2,481 | python | en | code | 0 | github-code | 13 |
37197215224 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: anya
"""
import numpy as np
import gf
import time
import math
import matplotlib.pyplot as plt
np.set_printoptions(threshold=np.nan)
class BCH(object):
def __init__(self, n, t):
primpoly = 7
self.q = int(math.log(n + 1, 2))
file = o... | Anyabelle/Algebra | bch.py | bch.py | py | 10,197 | python | en | code | 0 | github-code | 13 |
18104948295 | import collections
import os
import numpy as np
import torch
from sklearn.model_selection import train_test_split
from torch.utils.data import DataLoader
from torchvision.transforms import transforms
from data.dataset import CustomDataset
from data.processor import process_video, process_audio
def prepare_gender():... | usef-kh/EC-523-Deep-Learning-Project | AudioVisual/data/enterface.py | enterface.py | py | 6,849 | python | en | code | 2 | github-code | 13 |
10256119996 | import numpy as np
import tensorflow as tf
from collections import namedtuple
def decode_transfer_fn(transfer_fn):
if transfer_fn == "relu": return tf.nn.relu
elif transfer_fn == "relu6": return tf.nn.relu6
elif transfer_fn == "tanh": return tf.nn.tanh
elif transfer_fn == "sig": return tf.nn.sigmoid
... | dselsam/neurocore-public | python/tfutil.py | tfutil.py | py | 3,981 | python | en | code | 35 | github-code | 13 |
28367257839 | import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.linear_model import ElasticNet, Lasso
from sklearn.feature_selection import SelectFromModel
from sklearn.svm import SVR
from sklearn.model_se... | ASzot/Kaggle_Mercedes_Benz | main.py | main.py | py | 2,707 | python | en | code | 0 | github-code | 13 |
35205533849 | from util import aoc
def parse(input):
os = []
for line in input.splitlines():
os.append([int(o) for o in line])
return len(os[0]), len(os), os
def unparse(model):
w, h, os = model
sb = []
for row in os:
sb.extend(str(o) for o in row)
sb.append("\n")
return "".joi... | barneyb/aoc-2023 | python/aoc2021/day11/dumbo_octopus_grid.py | dumbo_octopus_grid.py | py | 1,751 | python | en | code | 0 | github-code | 13 |
23649939340 | #!/usr/bin/python
# --------------------------------------------------------------------------
#
# MIT License
#
# --------------------------------------------------------------------------
# --------------------------------------------------------------------------
class CyBldConfigSettings:
def __init__(self, ... | drcdev-gh/cybld | cybld/cybld_config_settings.py | cybld_config_settings.py | py | 1,066 | python | en | code | 1 | github-code | 13 |
5764705007 | import re
import urllib
from urllib.parse import urlparse
from bs4 import BeautifulSoup
class HtmlParser(object):
def pase(self, page_url, html_content):
if html_content is None:
return
if page_url == '':
page_url = 'http://www.zhuizhuishu.com/top.html'
soup = Beau... | jiefly/NovelUpdateCraw | test/html_parser.py | html_parser.py | py | 4,382 | python | en | code | 0 | github-code | 13 |
4713974864 | import numpy as np
from bs4 import BeautifulSoup
#从页面读取数据,生成列表
def scrapePage(retX, retY, inFile, yr, numPce, origPrc):
# 打开并读取HTML文件
with open(inFile, encoding='utf-8') as f:
html = f.read()
soup = BeautifulSoup(html, 'html.parser')
i = 1
# 根据HTML页面结构进行解析
#以列表形式返回符合条件的节点
currentRo... | JiweiMma/Linear-Regression | Linear-8.py | Linear-8.py | py | 3,966 | python | zh | code | 0 | github-code | 13 |
10081184100 | from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pickle
from d... | marekratho/price_scraper | ceskereality_scraper.py | ceskereality_scraper.py | py | 5,624 | python | en | code | 0 | github-code | 13 |
25700179522 | import os
# assume check was installed into /usr/local/
env_with_err = Environment(
ENV = os.environ,
CPPPATH = ['#/src', '/usr/local/include'])
if "CC" in os.environ:
env_with_err["CC"] = os.environ["CC"]
if "CCFLAGS" not in os.environ:
env_with_err["CCFLAGS"] = '-g -std=c99 -D_GNU_SOURCE -Wall -Werror -O3'
#prin... | mindis/NECSST-data-structure | libart/SConstruct | SConstruct | 608 | python | en | code | 4 | github-code | 13 | |
19902457307 | import control
import numpy as np
class Paraemters:
def __init__(self):
self.m1, self.m2 = 1, 1
self.k1, self.k2 = 2, 3
def dynamics(m1, m2, k1, k2):
A = np.array(
[
[0, 0, 1, 0],
[0, 0, 0, 1],
[-(k1 / m1 + k2 / m1), k2 / m1, 0, 0],
[k... | kimsooyoung/robotics_python | lec15_observability/spring_mass_obsv.py | spring_mass_obsv.py | py | 1,666 | python | en | code | 18 | github-code | 13 |
1382786466 | #Triangle Area Calculator - Challenge 3
class Triangle:
def __init__(self, l1, l2, l3):
self.line1 = l1
self.line2 = l2
self.line3 = l3
print(f"The length of the lines are {l1}, {l2}, and {l3}.")
def area(self):
return self.line1 * self.line2 * self.line3
tri = Triangle(42, 42, 42)
print(tri.area())
| tomgonzo/Learning-PY | 12-Paradigms/triangle.py | triangle.py | py | 318 | python | en | code | 1 | github-code | 13 |
12145880151 | import warnings
import cupy
from cupyx.scipy.ndimage import _util
from cupyx.scipy.ndimage import filters
def choose_conv_method(in1, in2, mode='full'):
"""Find the fastest convolution/correlation method.
Args:
in1 (cupy.ndarray): first input.
in2 (cupy.ndarray): second input.
mode ... | YuehChuan/cupy | cupyx/scipy/signal/signaltools.py | signaltools.py | py | 7,354 | python | en | code | null | github-code | 13 |
37259916523 | """Module in charge of the auto-completion feature."""
from typing import (
cast,
List,
Optional,
)
from lsprotocol.types import (
CompletionContext,
CompletionItem,
CompletionItemKind,
CompletionList,
CompletionTriggerKind,
InsertTextFormat,
Position,
Range,
)
from galaxy... | galaxyproject/galaxy-language-server | server/galaxyls/services/completion.py | completion.py | py | 10,531 | python | en | code | 22 | github-code | 13 |
33362908140 | def remove_dups(arr):
anchor = 1
for i in range(len(arr)-1):
if array[i] != arr[i+1]:
arr[anchor] = arr[i+1]
anchor +=1
return arr
array = [11,11,12,20,20,25,27,66,66,87,99,99]
print("Original Array = {}".format(array))
print("New Array = {} ".format(remove_dups(array)))... | BradleyGenao/Python-DS-Algorithms | arrays/remove_dups/remove_dups.py | remove_dups.py | py | 321 | python | en | code | 0 | github-code | 13 |
73255073938 | import numpy as np
import sys
import pprint as pp
import math
##############################################################
################CONVOLUTIONAL FUNCTIONS#######################
##############################################################
def conv(img, conv_filter, bias, stride=2):
(n_filt, n_filt_ch... | IYake/EECS-738-Final-Project | cnn.py | cnn.py | py | 4,171 | python | en | code | 1 | github-code | 13 |
35499392219 | """
https://github.com/lucidrains/make-a-video-pytorch
"""
import math
import functools
from operator import mul
import torch
from torch import nn, einsum
import torch.nn.functional as F
from einops import rearrange, repeat, pack, unpack
from einops.layers.torch import Rearrange
from .modules_conv import avg_pool_n... | microsoft/i-Code | i-Code-V3/core/models/latent_diffusion/modules_video.py | modules_video.py | py | 17,387 | python | en | code | 1,451 | github-code | 13 |
27573519644 | """
Intro to python exercises shell code
"""
def is_odd(x):
if x%2==1:
return True
return False
def is_palindrome(word):
for i in range(int(len(word)/2)):
if word[i]!=word[len(word)-i-1]:
return False
return True
"""
returns whether `word` is spelled the same forwa... | genericpan/mdst_Tutorials | Tutorial1/python_exercises.py | python_exercises.py | py | 1,311 | python | en | code | 0 | github-code | 13 |
30768047868 | """
Escribir un programa que a partir de un número entero cant ingresado por el usuario permita cargar por teclado cant números enteros. La computadora debe mostrar cuál fue el mayor número y en qué posición apareció.
"""
cantidad_num = int(input("Ingrese la cantidad de numeros que va a ingresar: "))
numeros = []
f... | aadriaan98/practicas-python | 3 Flujo_de_repeticion/ejercicio46.py | ejercicio46.py | py | 683 | python | es | code | 2 | github-code | 13 |
74322280976 | import random
# global variable for the random operator used to make calls to random shorter
r = random
# get a random value of gold based on turn segment
def get_gold(x):
g = 0
if(x <= 100):
g = r.randint(0, 6)
if((x <= 200) & (x > 100)):
g = r.randint(5,16)
if((x <= 300) & (x > 200)):
g = r.randint(15,31... | BjornMelin/Freeciv_Research | TestDataGenerator.py | TestDataGenerator.py | py | 2,209 | python | en | code | 1 | github-code | 13 |
42434919606 | import sqlite3
import sys
import re
def main():
args = sys.argv
input_file = args[1]
db_file = args[2]
#dir_name = args[3]
data = read_input_file(input_file)
insert_data(data, db_file)
def read_input_file(input_file):
p1 = re.compile(r'\s+')
p2 = re.compile(r'\s+.*Version')
p3 = re... | yookuda/biocontainers_image | import_R_package_data.py | import_R_package_data.py | py | 2,841 | python | en | code | 0 | github-code | 13 |
10326302097 | '''
run-time: 60 ms, faster than 34.14%
mem-usage: 14.2 mb, less than 73.10%
'''
class Solution:
def findNumbers(self, nums: List[int]) -> int:
count = 0
for num in nums:
digits = 0
while num != 0:
num = num // 10
... | NikhilNarvekar123/Competitive-Programming | find_numbers_with_even_number_of_digits.py | find_numbers_with_even_number_of_digits.py | py | 428 | python | en | code | 0 | github-code | 13 |
29849205935 | # https://www.hackerrank.com/challenges/py-set-discard-remove-pop/problem
n = int(input())
s = set(map(int, input().split()))
N = int(input())
for _ in range(N):
c = input().split()
command = c[0]
if command == "remove":
s.remove(int(c[1]))
elif command == "discard":
s.discard(int(c[1]... | ritchereluao/HackerRankPy | Sets/5_discard_remove_pop.py | 5_discard_remove_pop.py | py | 380 | python | en | code | 0 | github-code | 13 |
36790054136 | import turtle
bob = turtle.Turtle()
size = 50
bob.speed("fastest")
bob.penup()
bob.goto(-200,-200)
def draw_square():
bob.pendown()
bob.begin_fill()
for x in range(4):
bob.forward(size)
bob.left(90)
bob.end_fill()
bob.penup()
for c in range(8):
for r in range(8):
if ... | kmurphy/coderdojo | 04-Some_More_Turtle_Graphics/code/chess_2.py | chess_2.py | py | 421 | python | en | code | 1 | github-code | 13 |
6661427455 | # Data Structure ...
# User-Defined ...
# Linked List ...
# Singly Linked List (Adding data @ Ending) ...
class creatingnode():
def __init__(self,data):
self.data = data
self.linkto = None
class S_linkedlist():
def __init__(self,object_name):
self.name = object_name
self.head =... | RithickDharmaRaj-darkCoder/Linked_List | singlyLL.py | singlyLL.py | py | 4,090 | python | en | code | 0 | github-code | 13 |
17825551340 | import cv2
from matplotlib import pyplot
import numpy
img=cv2.imread('smarties.png',cv2.IMREAD_GRAYSCALE)
_, mask=cv2.threshold(img,220,255,cv2.THRESH_BINARY_INV)
kernel=numpy.ones((5,5),numpy.uint8)
dilation=cv2.dilate(mask,kernel,iterations=3)
erosion=cv2.erode(mask,kernel,iterations=3)
opening=cv2.morpho... | kanavbhasin22/Image_Processing | Morphological.py | Morphological.py | py | 819 | python | en | code | 0 | github-code | 13 |
8343772196 | arr = [[] for _ in range(5)]
dy = [-1, 0, 1, 0]
dx = [0, -1, 0, 1]
visited = [[0 for _ in range(5)] for _ in range(5)]
total = 0
for i in range(5):
st = input()
arr[i] = list(st)
# DFS로 7번 상하좌우 보면서 s 4개있는지 확인
def BFS():
cnt = 0
q = [(a, b)]
visited[a][b] = 1
for _ in range(7):
x, y ... | rohujin97/Algorithm_Study | baekjoon/1941.py | 1941.py | py | 781 | python | en | code | 0 | github-code | 13 |
40054587023 | # 4. Verifique se há dois nomes repetidos.
dic1 = {'user1':{'nome': 'Mioshi', 'sobrenome': 'Kanashiro', 'apelido': 'Japa'},
'user2':{'nome': 'Sergei', 'sobrenome': 'Ivanov', 'apelido': 'Russo'},
'user3':{'nome': 'Alfredo', 'sobrenome': 'Constâncio', 'apelido': 'Portuga'}}
nomes = []
for a, b in dic1.i... | robinson-1985/python-zero-dnc | 33.operacoes_com_dicionarios/11.exercicio4.py | 11.exercicio4.py | py | 470 | python | pt | code | 0 | github-code | 13 |
37563778835 | import os
import csv
from bs4 import BeautifulSoup
from Article import Article
from SearchResultParser import SearchResultParser
import Project
class SearchResultConverter:
def __init__(self):
self.topic = None
self.page = None
self.response = None
self.searchresults = [] #contains li... | PrusakSebastian/PaprScrapr | src/python/SearchResultConverter.py | SearchResultConverter.py | py | 5,268 | python | en | code | 0 | github-code | 13 |
12777787967 | #!/usr/bin/env python
import os
import sys
import datetime
from dateutil import parser
from pprint import pprint as pp
import click
from tvoverlord.config import Config
from tvoverlord.db import DB
from tvoverlord.consoletable import ConsoleTable
from tvoverlord.downloadmanager import DownloadManager
from tvoverlord.... | shrx/tv-overlord | tvoverlord/history.py | history.py | py | 6,469 | python | en | code | null | github-code | 13 |
31943604960 | from random import randrange
from typing import List
# @lc code=start
class Solution:
def __init__(self, n: int, blacklist: List[int]):
m = len(blacklist)
self.bound = w = n - m
black = {b for b in blacklist if b >= w}
self.b2w = {}
for b in blacklist:
if b < s... | wylu/leetcodecn | src/python/p700to799/710.黑名单中的随机数.py | 710.黑名单中的随机数.py | py | 678 | python | en | code | 3 | github-code | 13 |
26790057040 | from typing import Any, Dict, Sequence, Tuple, Union
import hydra
import omegaconf
import pytorch_lightning as pl
import torch
import torchmetrics
from torch.optim import Optimizer
from transformers import AutoModelForSequenceClassification
import wandb
from src.common.constants import GenericConstants as gc
from src... | ktl014/eval-student-writing | src/pl_modules/model.py | model.py | py | 6,995 | python | en | code | 0 | github-code | 13 |
72915384978 | import os
import os.path
import sys
import glob
import shutil
import fnmatch
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir,
os.pardir))
from scripts import utils
recursive_lint = ('__pycache__', '*.pyc')
lint = ('build', 'dist', 'pkg/pkg', 'pkg/qutebrowser-*.pk... | qutebrowser/qutebrowser | scripts/dev/cleanup.py | cleanup.py | py | 1,281 | python | en | code | 9,084 | github-code | 13 |
71536209939 | import logging
from fastapi import APIRouter, Depends, HTTPException
from starlette import status
from tortoise.transactions import in_transaction
from core.auth import auth_current_user
from core.helpers import get_amount, get_refund_amount
from core.roles import get_roles_client
from core.stripe import get_stripe
f... | Ivan-Terex91/graduate_work | billing_api/api/v1/billing.py | billing.py | py | 9,066 | python | en | code | 0 | github-code | 13 |
32053534315 | """Provides the 4heat DataUpdateCoordinator."""
from __future__ import annotations
from collections.abc import Coroutine
from dataclasses import dataclass
from datetime import timedelta
from typing import Any, cast
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, call... | anastas78/homeassistant-fourheat | custom_components/fourheat/coordinator.py | coordinator.py | py | 7,438 | python | en | code | 0 | github-code | 13 |
72013214419 | from flask import Flask, request, jsonify
from load_model_and_recommend import recommend_for_book
app = Flask(__name__)
app.config["DEBUG"] = True
@app.route('/')
def hello():
return 'Hello World!'
@app.route('/recommend_book',methods=['GET'])
def sen_recommend():
if 'book_name' in request.args:
book... | Akshith-github/Books_Recommendation_system | implementation_1_knn/flask_ml_api.py | flask_ml_api.py | py | 2,325 | python | en | code | 1 | github-code | 13 |
71253508819 | import matplotlib.pyplot as plt
x = [2, 6, 9, 1]
y = [8, 3, 7, 1]
plt.plot(x,y)
plt.title('line')
plt.xlabel('x')
plt.ylabel('y')
plt.grid(axis='both')
plt.show() | debdutgoswami/python-semester-practical | Question 21 - 30/Q28.py | Q28.py | py | 164 | python | en | code | 0 | github-code | 13 |
28920375748 | """
Exercício - Salvando a classe em json
Salve os dados da sua classe em JSON
e depois crie novamente as instâncias
da classe com os dados salvos
Faça em arquivos separados.
"""
import json
import os
BASE_DIR = os.path.dirname(__file__)
SAVE_TO = os.path.join(BASE_DIR, 'ex24.json')
class Estadio:
def __init__(s... | devSantZ/python_course | secao_3/exercicios/ex24_a.py | ex24_a.py | py | 1,374 | python | pt | code | 0 | github-code | 13 |
27636075683 | import pygame
from main.networking import Networking
from main.display import Display
from main.entity_manager import EntityManager
from main.character import Character
from main.controls import Controls
class Client():
def __init__(self):
self.tps=60
self.clock = pygame.time.Clock()
self.i... | ouriquegustavo/PyNamite | client/main/client.py | client.py | py | 2,090 | python | en | code | 1 | github-code | 13 |
16138189851 | import tweepy
from textblob import TextBlob
Consumer_Key= "your consumer key"
Consumer_Secret="your consumer secret"
Access_Token ="your access token"
AccessToken_Secret= "your access token secret"
authen=tweepy.OAuthHandler(Consumer_Key,Consumer_Secret)
authen.set_access_token(Access_Token,AccessToken_Secret)
api=t... | chajaykrishna/TwitterSentimentAnalysis | tweets.py | tweets.py | py | 464 | python | en | code | 0 | github-code | 13 |
14230982357 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('role', '0004_auto_20200916_2012'),
]
operations = [
migrations.AlterUniqueTogether(
name='rolerelatedobject',
unique_together={('role_id', 'object_type', 'object_id'... | TencentBlueKing/bk-iam-saas | saas/backend/apps/role/migrations/0005_auto_20201029_2028.py | 0005_auto_20201029_2028.py | py | 1,962 | python | en | code | 24 | github-code | 13 |
4568515908 | class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack.append(x)
def pop(self):
"""
:rtype: void
"""
... | Weikoi/OJ_Python | leetcode/easy/easy 1-200/155_最小值栈.py | 155_最小值栈.py | py | 994 | python | en | code | 0 | github-code | 13 |
10840022252 | import logging
import numpy as np
import tensorflow as tf
from tensorflow.python.estimator.estimator import Estimator
from tensorflow.python.estimator.run_config import RunConfig
from tensorflow.python.estimator.model_fn import EstimatorSpec
from tensorflow.keras.utils import Progbar
from .text_preprocessing import ... | gaphex/bert_experimental | bert_experimental/feature_extraction/bert_feature_extractor.py | bert_feature_extractor.py | py | 4,951 | python | en | code | 77 | github-code | 13 |
26312019932 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 28 14:15:49 2022
@author: nathan
"""
import pandas as pd
import geopandas as gpd
import os
from shapely.geometry import Polygon
import folium
# Degree spacing between grid cells
latDeg = 0.5
lonDeg = 0.625
crs_list = ["EPSG:4326", "EPSG:6933", "EP... | NathanDeMatos/UVic-ESD | LandUse/GridArea.py | GridArea.py | py | 1,264 | python | en | code | 0 | github-code | 13 |
30121127086 | import turtle
t= turtle.Turtle()
t.shape("turtle")
def house():
t.forward(100)
t.left(90)
t.forward(100)
t.left(90)
t.forward(100)
t.left(90)
t.forward(100)
t.left(90)
t.forward(100)
t.left(90)
t.forward(100)
t.right(90)
t.forward(20)
t.left(135)
... | Sasha2011a/- | рисовалка.py | рисовалка.py | py | 2,023 | python | en | code | 0 | github-code | 13 |
73845810257 | import os
import shutil
from pathlib import Path
from typing import List, Optional, Union
class DisplayablePath:
display_filename_prefix_middle = "├──"
display_filename_prefix_last = "└──"
display_parent_prefix_middle = " "
display_parent_prefix_last = "│ "
def __init__(self, path, parent_pa... | Kel0/django-parrallel-sessions | dps/utils.py | utils.py | py | 3,824 | python | en | code | 0 | github-code | 13 |
27188707073 | N = int(input())
triangle = [list(map(int, input().split())) for _ in range(N)]
dp = []
for i in range(1, N + 1):
dp.append([0] * i)
for x in range(0, N):
if x == 0:
dp[x][0] = triangle[x][0]
elif x == 1:
dp[x][0] = dp[x - 1][0] + triangle[x][0]
dp[x][-1] = dp[x - 1][... | Nam4o/Algorithm | 백준/Silver/1932. 정수 삼각형/정수 삼각형.py | 정수 삼각형.py | py | 618 | python | en | code | 1 | github-code | 13 |
5294441894 | import pickle
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
import csv
import datetime
# test_modelos_pickle = {'l_modelo' : l_modelo,
# 'l_total_reward': l_rewards,
# 'l_info': l_info}
# Salvo resultados
raiz = ... | falamo1969/AgenteInversionTFM | resumen_last_portfolio_full_invested.py | resumen_last_portfolio_full_invested.py | py | 1,875 | python | en | code | 0 | github-code | 13 |
1363875863 | from flask import Flask, render_template, request
from recipe_scrapers import scrape_me
import sqlite3
app = Flask(__name__) # create app instance
@app.route("/")
def index(): # Home page of the KitchenCompanion app
return render_template('index.html', title = 'Home')
@app.route("/view") # Connects... | WinSpartan/KitchenCompanion | kitchen_app/app.py | app.py | py | 4,931 | python | en | code | 0 | github-code | 13 |
22215437854 | class LinearValueFunction:
def __init__(self, step_size):
self.step_size = step_size
# Use a tile coding with only a single tiling (i.e. state aggregation):
# a grid of square tiles
self.tile_size = 16
self.w = np.zeros(((BOUNDARY_SOUTH - BOUNDARY_NORTH + self.tile_size) // ... | ottomattas/INFOMAML | Assignments/linearvf.py | linearvf.py | py | 1,661 | python | en | code | 0 | github-code | 13 |
34537534108 | import socket
import json
import numpy as np
import matplotlib.pyplot as plot
class RingBuffer:
def __init__(self,size_max):
self.max = size_max
self.data = []
class __Full:
def append(self, x):
self.data[self.cur] = x
self.cur = (self.cur+1) % self.max
... | Howard-149/mbed-HW2 | server.py | server.py | py | 2,720 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.