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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
1420651127 | """
2D Plasma Electron Energy Module.
EERGY2D contains:
Electron energy equation
d(3/2nekTe)/dt = -dQ/dx + Power_in(ext.) - Power_loss(react)
Input: ne, Te from Plasma1d, E_ext from field solver
Output: Te
"""
import numpy as np
from copy import deepcopy
from packages.Constants import KB_EV
class EE... | buckees/Langmuir | packages/Model/Reactor2D/Reactor2D_eergy.py | Reactor2D_eergy.py | py | 3,136 | python | en | code | 0 | github-code | 1 |
75058950113 | '''
A set of functions to help with feature creation
'''
import numpy as np
import matplotlib.pyplot as plt
from skimage.feature import hog
from image_processing import convert_to_gray
from sklearn.base import BaseEstimator, TransformerMixin
class CreateFeatures(BaseEstimator, TransformerMixin):
def __init__(sel... | erees1/faces-segmentation | src/feature_processing.py | feature_processing.py | py | 5,459 | python | en | code | 3 | github-code | 1 |
31223212153 | """______________________ ______________________ ______________________ ______________________
______________________ ______________________ ______________________ ______________________"""
teste = []
teste.append('Francis')
teste.append((34))
galera = list()
galera.append(teste[:])
teste[0] = 'Paul'
teste[1] = 35
g... | FrancisPaull/CursoemvideoPython | aulas/aula018 - Listas pt2.py | aula018 - Listas pt2.py | py | 1,279 | python | pt | code | 0 | github-code | 1 |
35074829379 | from keras.callbacks import Callback
import keras.backend as K
import json
class Logger(Callback):
def __init__(self, filepath, hyperparams, period=1):
super(Logger, self).__init__()
self.filepath = filepath #Save filepath for logging
self.period = period #Logging period
self.epochs_since_last_save = 0
s... | SwapnilPande/GazeTracking | iTracker/utils/customCallbacks.py | customCallbacks.py | py | 1,285 | python | en | code | 0 | github-code | 1 |
1951380057 | import numpy as np
class CategoricalNB:
def __init__(self):
pass
def fit(self, X, y):
self.y_keys = self._get_percent_unique(y)
self.__options = {}
for key in self.y_keys[0]:
self.__options[key] = self._get_probs(X, y, key)
... | xpcosmos/from_scratch | from_scratch/naive_bayes/_naivebayes.py | _naivebayes.py | py | 2,877 | python | en | code | 0 | github-code | 1 |
14448218907 | """
ChordNova v3.0 [Build: 2021.1.14]
(c) 2020 Wenge Chen, Ji-woon Sim.
Port to Python by osbertngok
"""
import typing
import enum
import music21
from .cnchordfeature import CNChordFeature, CNChordBigramFeature
from ..i18n import Statement, Language, _
from ..functions import different_name
class OverflowState(enum... | osbertngok/chordnovapy | python/chordnovacore/models/cnchord.py | cnchord.py | py | 9,690 | python | en | code | 1 | github-code | 1 |
73034175393 | # -*- coding: utf-8 -*-
# Import Python libs
import os
import sys
import shutil
import tempfile
import textwrap
import copy
from cStringIO import StringIO
# Import Salt Testing libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../')
# Import Salt libs
import ... | shineforever/ops | salt/tests/unit/pydsl_test.py | pydsl_test.py | py | 18,739 | python | en | code | 9 | github-code | 1 |
3060757577 | """
model.py: bert ner 模型
by: qliu
update date: 2021-12-17
"""
import os, torch
import torch.nn as nn
from transformers import BertForTokenClassification
class BertNer(nn.Module):
def __init__(self, common_config, model_config):
self.common_config = common_config
self.model_config = model_config
... | Jugglecomemid/NER_FRAME | ner/bert/model.py | model.py | py | 1,446 | python | en | code | 0 | github-code | 1 |
38924348496 | from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import time
import json
import datetime
import requests
# endpoint
data_all = requests.get('https://corona.lmao.ninja/all')
data_by_country = requests.get('https://corona.lmao.ninja/countries/')
def main_api(request):
fucking_list = ['upd... | lisianthuss116/d-covid | corona/services.py | services.py | py | 1,287 | python | en | code | 0 | github-code | 1 |
36337289418 | #!C:\Python34
import re
def main():
fd = open( "C:\\1.Class\\PracticeInClass\\Class28\\audio.conf")
data = fd.read()
#ob = re.compile( r"\bt\w+e\b", re.IGNORECASE)
ob = re.compile( r"\b\w+e\b", re.IGNORECASE)
for match in ob.finditer(data):
print ( match)
if __name__ == "__main__":
main()
| reshmaladi/Python | 1.Class/PracticeInClass/Class28/T_find.py | T_find.py | py | 306 | python | en | code | 0 | github-code | 1 |
72338065313 | import sys # sys нужен для передачи argv в QApplication
from PyQt5 import QtWidgets
import design
import requests
import time
import re
url_get_info = 'https://callapi.gravitel.ru/api/v1/getdialoutstat'
url_list = 'https://callapi.gravitel.ru/api/v1/listdialouts'
headers = {'Content-Type': 'application/json'}
def c... | danilfg/call_api_gravitel | main.py | main.py | py | 6,315 | python | ru | code | 0 | github-code | 1 |
31002478902 | import math
import lasap.containers.observable as observable
from lasap.utils import io
class Parallelizer:
def __init__(self, dirname, jobid, numjobs):
self.dirname = dirname
self.jobid = jobid
self.numjobs = numjobs
path = io.data_dir() + dirname
io.check_dir(path)
... | Hugo-loio/lasap | lasap/pproc/parallelizer.py | parallelizer.py | py | 891 | python | en | code | 0 | github-code | 1 |
71697009954 | import functools
def cache(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
cache_key = args + tuple(kwargs.values())
if cache_key not in wrapper.internal_cache:
wrapper.internal_cache[cache_key] = func(*args, **kwargs)
return wrapper.internal_cache[cache_key]
... | dimDamyanov/PythonOOP | 09. Decorators/LAB/demo_cache.py | demo_cache.py | py | 775 | python | en | code | 0 | github-code | 1 |
45872045621 | import sys
# basic libraries
import pandas as pd
#SQL library
from sqlalchemy import create_engine
# NLP
import re
import nltk
from nltk.tokenize import word_tokenize
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.stem.porter import PorterStemmer
nltk.download(['punkt', 'wordnet'])
# Machine Learning
from sk... | iosnewbie2016/Data-Science-Nanodegree | Disaster Pipeline App/models/train_classifier.py | train_classifier.py | py | 4,923 | python | en | code | 0 | github-code | 1 |
9388336891 |
from monosat import *
import functools
import math
import os
import random
import random
import sys
print("begin encode");
seed = random.randint(1,100000)
random.seed(seed)
print("RandomSeed=" + str(seed))
filename="/tmp/test_bv"
filename = filename + ".gnf"
Monosat().init("-decide-graph-bv -no-decide-theo... | tklenze/monosat-ctl | examples/python/test_maxflow_pb.py | test_maxflow_pb.py | py | 1,013 | python | en | code | 9 | github-code | 1 |
35887330524 | def descending_order(num):
num_list = [int(x) for x in str(num)]
num_list.sort(reverse=True)
str_list = [str(x) for x in num_list]
return int(''.join(str_list))
if __name__ == '__main__':
number = 15
print(descending_order(number))
| artempenteskul/tasks | codewars/python/easy/descending_order.py | descending_order.py | py | 258 | python | en | code | 0 | github-code | 1 |
13388033335 | #!/usr/bin/python
import sys
import time
import boto.ec2
#if len(sys.argv) < 3:
# print('Given the region and id that an AMI images is currently in, this script will copy it to other regions.')
# exit('Usage: {0} region image_id'.format(sys.argv[0]))
#REGION = sys.argv[1]
#IMAGE_ID = sys.argv[2]
new_images = {... | SunSparc/aws | update_asg_with_new_image/copy_image_to_all_regions.py | copy_image_to_all_regions.py | py | 1,692 | python | en | code | 4 | github-code | 1 |
40932463266 | from pyspark import SparkContext
import re
import random
import numpy as np
import hashlib
import time
import sys
from datetime import datetime
'''
Receive a document and return a set of shingles
'''
def shingling(doc, k=6):
shingles = []
for i in range(len(doc[1]) - k + 1):
shingles.append(doc[1]... | joaocarvalho19/Assign1-MDLE | ex2.py | ex2.py | py | 7,249 | python | en | code | 0 | github-code | 1 |
5053762256 | from application.Models.models import User
from application import db
from application.Team.Utils import commit_changes_to_db, save_to_db
class Team:
def get_team_account(self):
team = User.query.filter_by(is_team=1, is_admin=1)
if not team.count() > 0:
team = User.query.filter_by(is_a... | theirfanirfi/flask-book-exchange-apis | application/Team/Team.py | Team.py | py | 868 | python | en | code | 0 | github-code | 1 |
21391391184 | # 15-112: Principles of Programming and Computer Science
# HW07 Programming: Term Project (Tetris)
# Name : Umaymah Imran
# AndrewID : uimran
# File Created:
# Modification History:
# Start End
# 2/11 11:46pm 3/11 3:14am
# 3/11 12:01pm 3/11 4:11pm
# 3/1... | uimran/15-112-Term-Project | Tetris_Project.py | Tetris_Project.py | py | 39,683 | python | en | code | 0 | github-code | 1 |
31529457971 | from module import HandDetector
import cv2
import math
import time
import pygame
import serial
Arduino = serial.Serial(port='COM3 ', baudrate=9600)
class Timer:
def _init_(self, time_between=5):
self.start_time = time.time()
self.time_between = time_between
def can_send(self):
if tim... | Majethia/AR-CONTROLLED-CAR | wired_project.py | wired_project.py | py | 3,244 | python | en | code | 0 | github-code | 1 |
29790491256 | from .helpers import build_dataset
import nussl
import gin
import torch
import os
import logging
from torch import multiprocessing
from ignite.contrib.handlers import ProgressBar
from .handlers import add_train_handlers
from datetime import datetime
@gin.configurable
def build_model_optimizer_scheduler(model_config, o... | pseeth/bootstrapping-computer-audition | src/train.py | train.py | py | 5,298 | python | en | code | 7 | github-code | 1 |
6335751792 | from bs4 import BeautifulSoup
import requests
from models import Listing
import pandas as pd
from serializer import Serializer
import re
import os
class PreviewScraper:
def __init__(self, search_query, url="", soup=None):
self.search_query = search_query
self.url = url
self.soup... | tomgauth/apartment-scraper | scraper.py | scraper.py | py | 6,116 | python | en | code | 1 | github-code | 1 |
26510703374 | # show the learned policy
import gym
import pickle
import numpy as np
from copy import deepcopy
path_q_table = 'q_table.pickle'
with open(path_q_table, 'rb') as f:
q_table = pickle.load(f)
NUM_OBS = q_table.shape[0]
env = gym.make('MountainCar-v0', render_mode='human')
start = env.reset()
obs, _ = start
don... | Oliver-Busemann/Reinforcement_Learning | 2_MountainCar_TabularQLearning/play_greedy_mountaincar.py | play_greedy_mountaincar.py | py | 1,384 | python | en | code | 0 | github-code | 1 |
6690968888 | import torch
import torch.nn as nn
from torch import Tensor
from nugi_rl.model.components.Transformer import EncoderLayer, DecoderLayer
class GlobalExtractor(nn.Module):
def __init__(self, dim: int, num_layers = 2) -> None:
super().__init__()
object_queries = torch.ones(1, 1, dim)
self.re... | wisnunugroho21/nugi_rl | nugi_rl/model/ppo/Sumo.py | Sumo.py | py | 3,198 | python | en | code | 2 | github-code | 1 |
19818432604 | # -*- coding: utf-8 -*-
from django import forms
from django.core.exceptions import ImproperlyConfigured
from django.forms.models import ModelForm
from django.utils.encoding import smart_text
from django.utils.translation import ugettext as _
from cms.api import create_page
from cms.constants import TEMPLATE_INHERITA... | farhan711/DjangoCMS | cms/tests/test_wizards.py | test_wizards.py | py | 6,247 | python | en | code | 7 | github-code | 1 |
34469673620 | # 10개 정수입력받아 500미만의 수 중 가장 큰수와 500초과 수중 가장 작은 수
arr = list(map(int, input().split()))
max1 = -1
max2 = 1001
for i in arr:
if i > max1 and i < 500:
max1 = i
elif i < max2 and i > 500:
max2 = i
print(max1, max2) | yeafla530/algorithms | 코드트리/NL/500근처의수.py | 500근처의수.py | py | 292 | python | ko | code | 0 | github-code | 1 |
17440157782 |
def solve(data):
binary = get_bin_data(data)
return decode_package(binary)[0]
def decode_package(binary):
if len(binary) <= 7:
return 0, ""
version = int(binary[:3], 2)
type_ = binary[3:6]
if type_ == "100":
package_data = ""
for i in range(6, ((len(binary)) // 5) * 5,... | Florik3ks/AOC2021 | 16/16-2.py | 16-2.py | py | 2,200 | python | en | code | 1 | github-code | 1 |
14310366994 | import c4d
import random
def main():
if not op:
c4d.gui.MessageDialog('Please select Polygons')
return
if not isinstance(op, c4d.PolygonObject):
c4d.gui.MessageDialog('Please select Polygons!')
return
bs = op.GetPolygonS()
selda = bs.GetAll(op.GetPolyg... | ilayshp/c4d_scripting_py | Ornatrix_helpers/Ornatrix_selection_for_mod.py | Ornatrix_selection_for_mod.py | py | 1,176 | python | en | code | 1 | github-code | 1 |
11811085397 | import logging
import magic
import os
from cms.medias.utils import get_file_type_size
from django.conf import settings
from django.core.files.uploadedfile import InMemoryUploadedFile
from . import settings as app_settings
from . utils import to_webp
logger = logging.getLogger(__name__)
FILETYPE_IMAGE = getattr(sett... | UniversitaDellaCalabria/uniCMS | src/cms/medias/hooks.py | hooks.py | py | 2,228 | python | en | code | 5 | github-code | 1 |
25498246635 | import copy
import json
import logging
import optparse
import os
import random
import sys
import threading
import customtabs_benchmark
_SRC_PATH = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..', '..', '..', '..'))
sys.path.append(os.path.join(_SRC_PATH, 'third_party', 'catapult', 'devil'))
from de... | hanpfei/chromium-net | tools/android/customtabs_benchmark/scripts/run_benchmark.py | run_benchmark.py | py | 4,287 | python | en | code | 289 | github-code | 1 |
20406603699 | defterolepta = int(input('Δώσε τον αριθμό των δευτερολέπτων: '))
if defterolepta < 60:
print('Δευτερόλεπτα: ', float(defterolepta), sep='')
elif defterolepta >= 60 and defterolepta < 3600:
lepta = (defterolepta // 60) % 60
defterolepta = defterolepta % 60
print('Λεπτά: ', float(lepta), '\nΔευτερόλ... | bilakos26/Python-Test-Projects | ypologismos_xronou.py | ypologismos_xronou.py | py | 1,816 | python | el | code | 0 | github-code | 1 |
39606616067 | import os
from flask import Flask
from flask import render_template
app = Flask(__name__, template_folder='./templates')
@app.route('/')
def hello_world():
name = os.environ.get("MAIN_TEXT")
color = os.environ.get("COLOR")
print(color)
print(name)
return render_template('index.html', name=name, color=color) | WesleyDMartin/ATTPresentation | index.py | index.py | py | 314 | python | en | code | 0 | github-code | 1 |
22575631577 | import sys
input =sys.stdin.readline
count = 1
E, S, M = map(int,input().split())
while True:
if E%15==count%15 and S%28==count%28 and M%19==count%19:
break
count+=1
print(count) | dydwkd486/coding_test | baekjoon/python/baekjoon1476.py | baekjoon1476.py | py | 197 | python | en | code | 0 | github-code | 1 |
39906494492 | # -*- coding: utf-8 -*-
from processr.processr import (
rename_keys,
project_dict,
transform_values,
transform_dict,
transform_values_strict)
import pytest
##############################################################
# rename_keys #
##############... | entropiae/processr | tests/test_stages.py | test_stages.py | py | 3,531 | python | en | code | 0 | github-code | 1 |
26490993748 | from pygame import*
from time import time as tim
from random import randint
def Fliby_bird_game():
init()
mixer.init()
window = display.set_mode((1100, 600))
display.set_caption("Fliby Bird")
clock = time.Clock()
background = transform.scale(
image.load("fliby bird/background.jpg... | Bohdan-Balanuk/Fliby-Bird | fliby_bird.py | fliby_bird.py | py | 5,368 | python | en | code | 0 | github-code | 1 |
12079028125 | # Digits in Words
# The program must accept an integer N as the input. The program must print the corresponding words separated by space(s) for each digit in N as the output. The words must be printed as given below,
# 0 - zero
# 1 - one
# 2 - two
# 3 - three
# 4 - four
# 5 - five
# 6 - six
# 7 - seven
# 8 - eight
# 9... | Logesh08/Programming-Daily-Tests | Digits in Words.py | Digits in Words.py | py | 800 | python | en | code | 0 | github-code | 1 |
32874425692 | """
Link: https://codeforces.com/problemset/problem/468/B
Time complexity: O(N * Log(N))
Space complexity: O(N)
Author: Nguyen Duc Hieu
"""
class Union_Find:
def __init__(self, N):
self.parent = [i for i in range(N)]
self.rank = [0] * N
self.component = N
def find(self, u):
if... | hieuducnguyen/BigOCourse | 16_disjoint_set_union/8_Two_Sets.py | 8_Two_Sets.py | py | 3,132 | python | en | code | 2 | github-code | 1 |
22892185392 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from itertools import chain, combinations, product
from pprint import pprint
import pickle
import csv
########################
# Simple hierarchies #
########################
number_hrcs = {'sp': {('s', 'p')},
'ps': {('p', 's')}}
person_hrcs = {'123':... | CompLab-StonyBrook/msc | syncalc.py | syncalc.py | py | 9,143 | python | en | code | 1 | github-code | 1 |
35633348698 | from interface import *
def fileExist(name):
try:
a = open(name, 'rt')
a.close()
except FileNotFoundError:
return False
else:
return True
def criarFile(name):
try:
a = open(name, 'wt+')
a.close()
except:
print('Theres was an... | ehliexplore/curso-em-video-python-exercicios | REMAKE 115/packs/arquivo/__init__.py | __init__.py | py | 1,206 | python | en | code | 0 | github-code | 1 |
25403760205 | from algorithm.conll import *
from algorithm.scorer import *
if __name__ == "__main__":
if len(sys.argv) == 3:
key_dir = sys.argv[1]
response_dir = sys.argv[2]
#key_dir = "./data/gold.conll"
#response_dir = "./data/pred.conll"
key = extract_cluster_conll(key_dir)
res = extract_clu... | fairy-of-9/Coreference-Scorer | conll_scorer.py | conll_scorer.py | py | 977 | python | en | code | 0 | github-code | 1 |
35076666654 | """
Device Specific Classes which use AVR32Protocol implementation
"""
from pyedbglib.protocols.avr32protocol import Avr32Protocol
class Avr32Device(object):
"""
Generic AVR32 device wrapper (maps to avr32 protocol)
"""
def __init__(self, transport, reset_domains=5):
"""
:param transpor... | SpenceKonde/megaTinyCore | megaavr/tools/libs/pymcuprog/avr32target.py | avr32target.py | py | 1,801 | python | en | code | 471 | github-code | 1 |
6667165172 | import numpy as np
import time
def sigmoid(arg: int) -> float:
return np.divide(1., 1. + np.exp(-arg))
def tanh(arg: int) -> float:
arg1 = np.exp(arg)
arg2 = np.exp(-arg)
return np.divide(arg1 - arg2, arg1 + arg2)
if __name__ == "__main__":
np.random.seed(2019)
length = 1000000
random... | kislerdm/benchmark-math | code/py/numpy/bench_numpy.py | bench_numpy.py | py | 1,094 | python | en | code | 0 | github-code | 1 |
3862571173 | from django import forms
topic_choices = (
('general', 'General enquiry'),
('bug' 'Report a bug'),
('suggestion', 'Suggestion'),
)
class ContactForm(forms.Form):
topic = forms.ChoiceField(choices=topic_choices)
message = forms.CharField(widget=forms.Textarea())
sender = forms.EmailField(requir... | Pragades-Rajagopal/django-ex1 | mysite/books/forms.py | forms.py | py | 572 | python | en | code | 0 | github-code | 1 |
15807083162 | def main():
celcius = int(input("Enter the temperature in Celsius: "))
fahrenheit = ((9/5) * celcius) + 32
print(f"The temperature in Fahrenheit is:\t", format(fahrenheit, '.2f'))
"""
########################################
# Do not delete the return statement
######################... | DVC-COMSC/assignment-2-2-gshriivanth | main.py | main.py | py | 418 | python | de | code | 0 | github-code | 1 |
70319714273 | # -*- coding: utf-8 -*-
from jowent.bannerviewlet import MessageFactory as _
from zope import schema
from zope.interface import Interface
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
class IBannerViewletInstalled(Interface):
""" A layer specific for this add-on product.
This interface is r... | jowent/jowent.bannerviewlet | jowent/bannerviewlet/interfaces.py | interfaces.py | py | 2,720 | python | en | code | 0 | github-code | 1 |
34142690678 | '# -*- coding: utf-8 -*-'
'''
This module includes routines that are shared by the NLPShakespeareWorks project
'''
__author__ = 'Dr Avner OTTENSOOSER <avner.ottensooser@gmail.com>'
__version__ = '$Revision: 0.01 $'
def Arab2Roman(AO_iArab):
'''
Convert Arab numeral to Roman Numeral.
Based on snipp... | DrOttensooser/BiblicalNLPworks | SkyDrive/NLP/ShakespeareNLPworks/Source Code/AO_mShakespeareWorksCommon.py | AO_mShakespeareWorksCommon.py | py | 3,166 | python | en | code | 8 | github-code | 1 |
43725083994 | import os
import time
import DAQUtils
from StatMonUtils import Log, SecondsToTime, fileAgeWarnTime
from StatusChecker import StatusDatum, StatusChecker
###################
# BeamDAQ
###################
class BeamDAQ(StatusChecker):
"""Check that the BeamDAQ is alive and updating"""
def __init__(self):
StatusCh... | E1039-Collaboration/e1039-slowcontrols | status_monitor/BeamDAQ.py | BeamDAQ.py | py | 3,483 | python | en | code | 0 | github-code | 1 |
26109465573 | from django.shortcuts import render
from django.http import Http404
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from core.models import Spaceship, Location
from .serializers import SpaceshipSerializer, LocationSerializer
class SpaceshipListC... | mayankaga94/stomble-spaceship | api/views.py | views.py | py | 5,268 | python | en | code | 0 | github-code | 1 |
15145456064 | from operator import itemgetter
from datetime import datetime, timedelta
import sys
from txkoji import Connection
from txkoji import task_states
from txkoji.estimates import average_build_duration
from txkoji.estimates import average_build_durations
from twisted.internet import defer
from twisted.internet.task import r... | ktdreyer/txkoji | examples/estimate-container.py | estimate-container.py | py | 5,389 | python | en | code | 6 | github-code | 1 |
31490813260 | import cv2
cap = cv2.VideoCapture("D:\ciic-iitm\image processing\FullSizeRender.MOV")
frame_no = 0
while(cap.isOpened()):
frame_exists, curr_frame = cap.read()
if frame_exists:
print("for frame : " + str(frame_no) + " timestamp is: ", str(frame_no/cap.get(cv2.CAP_PROP_FPS)))
frame_no+=1
... | siddiq3004/computer-vision | IITM_HACKATHON_PROJECT/Round_2/stamp.py | stamp.py | py | 374 | python | en | code | 0 | github-code | 1 |
25462641798 | #!/usr/bin/python3
"""Empty class"""
class Square:
"""Square class wit a private attribute"""
def __init__(self, size=0, position=(0, 0)):
"""Initializes with a attributes size and position"""
if type(size) is not int:
raise TypeError('size must be an integer')
if type(posi... | dalejohgi/holbertonschool-higher_level_programming | 0x06-python-classes/6-square.py | 6-square.py | py | 2,305 | python | en | code | 0 | github-code | 1 |
17562778915 | from curses import window
import matplotlib
import numpy as np
import pandas as pd
from collections import namedtuple
from matplotlib import pyplot as plt
EpisodeStats = namedtuple("Stats",["episode_lengths", "episode_rewards", "step_reward_avg"])
def plot_value_function(V, title="Value Function"):
"""
Plots... | Sam-Fatehmanesh/FSRIresearch | plotting.py | plotting.py | py | 2,518 | python | en | code | 0 | github-code | 1 |
11518286872 | ############# Memoization ##############
class Solution:
def canJump(self, nums: List[int]) -> bool:
n = len(nums)
dp = [-1] * n
def solve(idx):
if(idx ==n-1):
return True
if(dp[idx] != -1):
return dp[idx]
... | Hamza2Malik/DSA-Leetcode | Python/Array/55_Jump Game (Google Microsoft).py | 55_Jump Game (Google Microsoft).py | py | 1,659 | python | en | code | 0 | github-code | 1 |
24678993685 | import xml.etree.ElementTree as et
import re
def records(xml):
root = et.fromstring(xml)
return root.findall('result/content')
def organisation(record):
org = {
'pure_uuid': record.attrib['uuid'],
'parent_pure_uuid': None,
'parent_pure_id': None,
'type': record.find("./typeClassification/term/lo... | UMNLibraries/experts | experts/pureapi.old/xmlparser.py | xmlparser.py | py | 11,883 | python | en | code | 0 | github-code | 1 |
14930508832 | from bs4 import *
import requests as rq
import os
import shutil
#to take all data from given website
r2=rq.get("https://www.indiaglitz.com/aamir-khan-photos-hindi-actor-2738542-7950")
soup=BeautifulSoup(r2.text,"html.parser")
link=[]
#To select images whoes source link starts with the given src
#here t... | DILIP-RAMGOPAL/Internship | photo.py | photo.py | py | 907 | python | en | code | 0 | github-code | 1 |
72663776034 |
from operator import itemgetter
import nest_py.core.jobs.file_utils as file_utils
import nest_py.omix.jobs.fst_input_etl as fst_input_etl
def load_fst_results_from_csv(comparison_key, data_dir):
fn = filename_of_fst_results(comparison_key, data_dir)
#corresponds to the tornado_observation_key, which is just ... | KnowEnG/platform | nest_py/omix/jobs/fst_output_etl.py | fst_output_etl.py | py | 2,762 | python | en | code | 2 | github-code | 1 |
33862207059 | import streamlit as st
import requests
from streamlit_folium import folium_static
import folium
import pandas as pd
from geopy.geocoders import Nominatim
from os import system, name
st.markdown("<h1 style='text-align: center; color: black;'>NY Taxi</h1>",
unsafe_allow_html=True)
st.subheader('Please provi... | HamzaBenki/TaxiFareWebsite | app.py | app.py | py | 1,722 | python | en | code | 0 | github-code | 1 |
43791231089 | #!/usr/bin/env python
import os
import re
import omero
from omero.gateway import BlitzGateway
from omero.rtypes import (
rdouble,
rint,
rstring
)
DATASET_ID = 13801
DELETE_ROIS = True
DRYRUN = False
W = 256
H = 256
# Generated with:
# /uod/idr/filesets/idr0109-zaritsky-melanoma/20210408-ftp/ROI>
# find *... | IDR/idr0109-zaritsky-melanoma | scripts/rois.py | rois.py | py | 4,415 | python | en | code | 0 | github-code | 1 |
19455279998 | import os
import shutil
from datetime import datetime
from PIL import Image, ExifTags
import tkinter as tk
from tkinter import filedialog, messagebox
def choose_directory():
global media_path
media_path = filedialog.askdirectory()
if media_path:
folder_entry.delete(0, tk.END)
folder_entry.... | aquamammal/photosvideoorganizer | Photo Folder Creation With Video Updated With Gui.py | Photo Folder Creation With Video Updated With Gui.py | py | 3,273 | python | en | code | 0 | github-code | 1 |
17727361108 | from flask_sqlalchemy import SQLAlchemy
from app import db, Ticket
import os
os.system("rm tickets.db")
validcode_file = "test.txt"
db.create_all()
with open(validcode_file) as f:
content = f.read().splitlines()[1:]
for i in content:
ticket = Ticket(i)
db.session.add(ticket)
db.session.commit()
| ethylomat/MathPhysTheoTS | seed.py | seed.py | py | 308 | python | en | code | 0 | github-code | 1 |
922075687 | import psycopg2
from flask import Blueprint, render_template, redirect, session, request, jsonify
from dbUtils import interact_db
# events blueprint definition
ranking_1 = Blueprint('ranking_1', __name__, static_folder='static', static_url_path='/ranking_1', template_folder='templates')
# Routes
@ranking_1.route('/r... | leorre/experiment1 | pages/ranking_1/ranking_1.py | ranking_1.py | py | 1,534 | python | en | code | 0 | github-code | 1 |
26773545961 | import json
import logging
import random
from concurrent.futures import ThreadPoolExecutor
import sentry_sdk
from ddtrace import tracer
from jsonschema import validate
from jsonschema.exceptions import ValidationError
from ..enip_common import s3
from ..enip_common.config import CDN_URL
from ..enip_common.pg import g... | vote/enip-backend | enip_backend/export/run.py | run.py | py | 5,896 | python | en | code | 2 | github-code | 1 |
11510959402 | # Released under the MIT License. See LICENSE for details.
#
"""UI functionality related to UI items."""
from __future__ import annotations
from typing import TYPE_CHECKING
import bascenev1 as bs
import bauiv1 as bui
if TYPE_CHECKING:
from typing import Any
def instantiate_store_item_display(
item_name: st... | efroemling/ballistica | src/assets/ba_data/python/bauiv1lib/store/item.py | item.py | py | 23,835 | python | en | code | 468 | github-code | 1 |
71566246435 | from bot.commands.commands import CommandExecutor
from bot.models import Command
from bot.utils import range_some
from random import randint
class CommandSelect(CommandExecutor):
def get_names(self):
return ["select"]
def get_help(self):
return "Usage: 複数の単語から指定個数ランダムで選択します。\n" \
... | Getaji/GetajiBot | src/bot/commands/cmd_select.py | cmd_select.py | py | 1,293 | python | en | code | 0 | github-code | 1 |
38701188884 | import asyncio
import aiohttp
async def GetAnswer(prompt):
url = "https://www.kato.to/advancedApi/ai/chat"
headers = {
"content-type": "application/json",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"
}
payload = [
... | mishalhossin/Anime-GPT | koto.py | koto.py | py | 770 | python | en | code | 0 | github-code | 1 |
27470853052 | #!/usr/bin/env python
import os
import wave
import rospy
import pyaudio
import speech_recognition as sr
from std_msgs.msg import String
from pmb2_face.srv import listen_service
class speech2text_node():
def __init__(self):
rospy.init_node('speech2text_node')
rospy.loginfo("Starting sp... | lfvm0001/pmb2_UJA | pmb2_face/scripts/speech2text_node_2.py | speech2text_node_2.py | py | 2,219 | python | en | code | 0 | github-code | 1 |
3667435969 | import sys
from typing import Any
import bpy
bl_info = {
"name" : "UV_Texture",
"author" : "FlagYoung",
"description" : "",
"blender" : (3, 20, 0),
"version" : (0, 0, 1),
"location" : "",
"warning" : "",
"category" : "Generic"
}
##
# import files
# ##---------------
from .UI import... | 1641585051/UVTexture | __init__.py | __init__.py | py | 3,105 | python | en | code | 1 | github-code | 1 |
18119095039 | import argparse
from pythonosc import udp_client
def send_osc_message(ip, port, address, cue_id):
client = udp_client.SimpleUDPClient(ip, port)
client.send_message(address, cue_id)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Send an OSC command to QLab to start a cue.")
pa... | BarryAbrams/dracula | Gmmy/python/old/qlab.py | qlab.py | py | 871 | python | en | code | 0 | github-code | 1 |
25851709868 | print("Input a word")
word = input()
numOfA = 0
numOfE = 0
numOfI = 0
numOfO = 0
numOfU = 0
for i in word:
if(i.lower() == "a"):
numOfA += 1
elif(i.lower() == "e"):
numOfE += 1
elif(i.lower() == "i"):
numOfI += 1
elif(i.lower() == "o"):
numOfO += 1
elif(i.lower() == ... | arjunycoding/pythonBook | chapter5/loopyLetters.py | loopyLetters.py | py | 580 | python | en | code | 0 | github-code | 1 |
32655540313 | from flask import request as current_request, g as request_context
from werkzeug.exceptions import Unauthorized
from server.auth.secrets import secure_hash
from server.db.domain import Service, ServiceToken
from server.logger.context_logger import ctx_logger
def get_authorization_header(is_external_api_url, ignore_m... | SURFscz/SBS | server/auth/tokens.py | tokens.py | py | 1,622 | python | en | code | 4 | github-code | 1 |
24046431936 | # -*- coding: utf-8 -*-
import argparse
import math
import pybullet as p
from time import sleep
#Intervalle de temps entre chaque fenêtre
dt = 0.01
#Longeurs des composantes des pattes
l1 = 40
l2 = 45
l3 = 65
l4 = 87
def init():
"""Initialise le simulateur
Retourne:
int -- l'id du robot
"""
... | EBeauvillard/quadruped | quadruped.py | quadruped.py | py | 11,003 | python | fr | code | 0 | github-code | 1 |
75035566753 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# https://towardsdatascience.com/3-easy-ways-to-deploy-your-streamlit-web-app-online-7c88bb1024b1
import streamlit as st
st.title("Housing Prediction")
st.write("""
### Project description
We have trained the data to predict the n cheap house based on the following inf... | aslam7861/Software_development | housing_streamlit.py | housing_streamlit.py | py | 1,497 | python | en | code | 0 | github-code | 1 |
21318435869 |
import yaml
# data = {
# "client": {"default-character-set": "utf8"},
# "mysql": {"user": 'root', "password": 123},
# "custom": {
# "user1": {"user": "张三", "pwd": 666},
# "user2": {"user": "李四", "pwd": 999},
# }
# }
#
# # 直接 dump 可以把 python 对象转为 YAML 文档
# with open('./my.yaml', 'w', e... | Phila-china/yude | test_game_by_data/yaml_demo/yaml_demo.py | yaml_demo.py | py | 607 | python | en | code | 0 | github-code | 1 |
39284302958 | from sqlalchemy.orm import Session
from fastapi import HTTPException
from . import models
from . import schemas
from ..gpt import validate_tag
def create_user(db: Session, user: schemas.UserCreate):
db_user = models.User(login=user.login, email=user.email, phone_number=user.phone_number,
... | choseenonee/MISIS-Hub | backend/database/CRUD.py | CRUD.py | py | 5,890 | python | en | code | 0 | github-code | 1 |
36848626231 | from libqtile import qtile, widget, bar
from libqtile.lazy import lazy
from font import font, windowname
from color import colors
from info import hardware
from layouts import MARGIN, BORDER_WIDTH
import os
CENTER_SPACERS = 100
fontinfo = dict(
font=font["secondary"]["family"],
padding=font["secondary"]["padd... | the-argus/nixsys | modules/home-manager/desktops/qtile/config/bar.py | bar.py | py | 6,245 | python | en | code | 50 | github-code | 1 |
30394716367 | from flask import Flask
import win32print
import win32ui
import win32api
import win32print
app = Flask(__name__)
GHOSTSCRIPT_PATH = "./GHOSTSCRIPT/bin/gswin32.exe"
GSPRINT_PATH = "./GSPRINT/gsprint.exe"
currentprinter = win32print.GetDefaultPrinter()
@app.route('/')
def root():
return "Home page"
@app.route... | TranHoangKhoi/Python-Tool | routeApi.py | routeApi.py | py | 586 | python | en | code | 0 | github-code | 1 |
24183708020 | # Databricks notebook source
import requests
import json
def request_llamav2_13b(question, url,token):
headers = {
"Content-Type": "application/json",
"Authentication": f"Bearer {token}"
}
data = {
"prompt": question
}
response = requests.post(url, headers=h... | sebrahimi1988/speech-enabled-QA-chatbot | backend/06_hit_the_proxy.py | 06_hit_the_proxy.py | py | 700 | python | en | code | 0 | github-code | 1 |
2573940128 | from sdv.model import (
DataPointBoolean,
DataPointFloat,
DataPointInt8,
DataPointUint8,
DataPointUint16,
Model,
)
from sdv_model.Cabin.Seat.Airbag import Airbag
from sdv_model.Cabin.Seat.Backrest import Backrest
from sdv_model.Cabin.Seat.Headrest import Headrest
from sdv_model.Cabin.Seat.Occup... | eclipse-velocitas/vehicle-model-python | sdv_model/Cabin/Seat/__init__.py | __init__.py | py | 2,920 | python | en | code | 1 | github-code | 1 |
17038320373 | from sklearn.model_selection import train_test_split, GridSearchCV, ShuffleSplit
import pandas as pd
import numpy as np
import lightgbm as lgb
import pickle
from sklearn.metrics import mean_squared_error
from math import sqrt
def RMSE(y_actual, y_predicted):
rms = sqrt(mean_squared_error(y_actual, y_predicted))
... | sklinl/Competition_Tunghai | Preliminary/lgbm.py | lgbm.py | py | 4,581 | python | en | code | 0 | github-code | 1 |
413232590 | import os
import math
import numpy as np
from box import Box # type: ignore
def study_id_from_path(filepath):
return os.path.splitext(os.path.basename(filepath))[0]
def str2bool(value):
if value is None:
return False
if isinstance(value, bool):
return value
return value.lower() in {... | iossifovlab/gpf | dae/dae/utils/helpers.py | helpers.py | py | 1,807 | python | en | code | 1 | github-code | 1 |
21144554269 | """
Project running module.
Created on 26.01.2020
@author: Ruslan Dolovanyuk
"""
import multiprocessing
from drawer import Drawer
def main():
drawer = Drawer()
drawer.mainloop()
if __name__ == '__main__':
multiprocessing.freeze_support()
main()
| DollaR84/HotSound | main.pyw | main.pyw | pyw | 270 | python | en | code | 0 | github-code | 1 |
72498217634 | # vim:fileencoding=UTF-8:filetype=python:ts=4:sw=4:sta:et:sts=4:ai
"""Extend calibre's EPUBContainer to work for a KePub."""
__license__ = "GPL v3"
__copyright__ = (
"2010, Kovid Goyal <kovid@kovidgoyal.net>; "
+ "2013, Joel Goguen <jgoguen@jgoguen.ca>"
)
__docformat__ = "restructuredtext en"
# Be careful ed... | jgoguen/calibre-kobo-driver | container.py | container.py | py | 23,722 | python | en | code | 246 | github-code | 1 |
41168682746 | # runtime n * log(n)
def merge_sort(uList):
if len(uList) <= 1:
return uList
middle = len(uList) / 2
right, left = [], []
for n in uList[:middle]:
left.append(n)
for n in uList[middle:]:
right.append(n)
left = merge_sort(left)
right = merge_sort(right)
return _mer... | optionalg/cracking-the-coding-interview-7 | chapter_11/merge_sort.py | merge_sort.py | py | 912 | python | en | code | 0 | github-code | 1 |
28033235382 | import numpy as np
import pandas as pd
import csv
data = np.load('./193603_3.png.npy')
arr=np.array(data,dtype=str).tolist()
arr=','.join(arr)
arr+='\t'
image_mask=np.ones(64,dtype=str).tolist()
arr+=','.join(image_mask)
arr+='\t'
masked_patch_position=np.ones(5,dtype=str).tolist()
arr+=','.join(masked_patch_positio... | ggxxding/EasyTransfer | scripts/fashion_bert/npy2train.py | npy2train.py | py | 725 | python | en | code | null | github-code | 1 |
5583859040 | import re
import os
import sys
import unittest
import cv2
import numpy as np
import threading
from PIL import ImageGrab
from functools import wraps
from time import sleep, time
from appium.webdriver.common.mobileby import MobileBy as By
from selenium.webdriver.support import expected_conditions as ec
from s... | johnny-butter/UI-Automation | supportiveFunction.py | supportiveFunction.py | py | 13,743 | python | en | code | 0 | github-code | 1 |
71487148833 | import random
from clarifai_grpc.grpc.api import service_pb2, resources_pb2
from clarifai_grpc.grpc.api.status import status_code_pb2
# Insert here the initialization code as outlined on this page:
# https://docs.clarifai.com/api-guide/api-overview
# This is how you authenticate.
metadata = (('authorization', f'Key a... | clara7089/Gray | clarifai.py | clarifai.py | py | 6,857 | python | en | code | 1 | github-code | 1 |
5701850514 | from logging import getLogger
import threading as th
from django.conf import settings
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from .. import common_handlers
from .handlers import handlers
from .decorators import adapter
logger = getLogger(__name__)
def setup_webhook(updater):
w... | conyappa/mvp | app/bot/telegram/replier.py | replier.py | py | 1,288 | python | en | code | 0 | github-code | 1 |
10230056627 | # -*- coding: utf-8 -*-
from tkinter import *
from tkinter import filedialog
class HeaderFrame(Frame):
'''
Frame : Contient le fomulaire du haut des pages "Renommer" et "Créér une règle"
'''
def __init__(self, root, mainTitle, formTitle) :
Frame.__init__(self, root)
self.mainTitle ... | Skg-754/MyRenamingApp | Sources/views/HeaderFrame.py | HeaderFrame.py | py | 1,987 | python | en | code | 0 | github-code | 1 |
36909051788 | import json
import os
import subprocess
import requests
from dotenv import load_dotenv
from web3 import Web3
#get env
load_dotenv('price-timestamping/.env')
gitlab_email = os.getenv('gitlab_email')
infura_url = os.getenv('infura_url')
account_sender = os.getenv('account_sender')
account_receiver = os.getenv('account_... | qredo/price-timestamping | etl_pricedumping/pricedumping.py | pricedumping.py | py | 2,829 | python | en | code | 0 | github-code | 1 |
71015515875 | import sys
if __name__ == '__main__':
n, r = -1, -1
while n != 0 or r != 0:
n, r = list(map(int, sys.stdin.readline().strip().split(' ')))
if n == 0 and r == 0:
break
else:
r = min(n-r, r)
ans = 1
for k in range(1, r+1):
... | yskang/AlgorithmPractice | baekjoon/python/binomial_coefficient_showdown_6591.py | binomial_coefficient_showdown_6591.py | py | 382 | python | en | code | 1 | github-code | 1 |
1443260575 | # -*- coding: utf-8 -*-
"""
Author : Alexandre
Created : 2021-06-30 11:58:56
Comments : (low-level) functions handling export of data / figures for HAL
"""
# %% IMPORTS
# -- global
import logging
import h5py
import numpy as np
from pathlib import Path
from datetime import datetime
from PyQt5.QtWidgets import QFil... | adareau/HAL | HAL/gui/export.py | export.py | py | 4,973 | python | en | code | 2 | github-code | 1 |
20203726768 | class Solution:
def pancakeSort(self, arr: List[int]) -> List[int]:
currMax = max(arr)
ans = []
while currMax > 1:
maxInd = arr.index(currMax)
if maxInd + 1 == currMax:
currMax -= 1
continue
else:
arr[0:maxI... | Birook2023/A2SV--Group-4A-Progress | Pancake Sorting.py | Pancake Sorting.py | py | 553 | python | en | code | 0 | github-code | 1 |
10959291510 | from flask import Flask;
import importlib;
STATIC_URL_PATH_ATTRIBUTE_NAME = 'STATIC_URL_PATH';
class AppFactory:
@staticmethod
def create_app(config_class):
"""Send a email with the latest HED schema.
Parameters
----------
config_class: string
The configuration cl... | VisLab/HEDToolsArchived | python/hedemailer/hedemailer/app_factory.py | app_factory.py | py | 1,249 | python | en | code | 6 | github-code | 1 |
38774881338 | import numpy as np
def Wagner_Whitin(k, h, b, D):
"""
Wagner-Whitin algorithm for production planning
:param k: (float) fixed cost
:param h: (float) unit inventory holding cost
:param b: (float) production cost
:param D: (list) demand w.r.t time
:return:
"""
time_len = len(D)
v... | MikeZheng777/IOE512_2021 | hw2/WW_Algorithm.py | WW_Algorithm.py | py | 1,245 | python | en | code | 0 | github-code | 1 |
34542443585 | import helpers
import unittest
import database as db
import copy
class TestDatabase(unittest.TestCase):
def setUp(self):
db.Clientes.lista = [
db.Cliente("15J", "Marta", "Perez"),
db.Cliente("48H", "Manolo", "Lopez"),
db.Cliente("28Z", "Ana", "Garcia")
... | CSprog87/Gestor | Gestor/tests/test_database.py | test_database.py | py | 1,814 | python | es | code | 0 | github-code | 1 |
29106036893 | from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
#from rest_framework_swagger.views import get_swagger_view
#schema_view = get_swagger_view(title='Pastebin API')
urlpatterns = [
#path('', schema_view),
path('', ... | TulsiSharma206/New | auth/urls.py | urls.py | py | 756 | python | en | code | 0 | github-code | 1 |
24485937594 | import sys
import math
import copy
n=1; deckList = ['AS', 'AH', 'AD', 'AC']
n=1; deckList = ['2S', '5D', 'QH', '3S', '4S', 'JH', 'JD', '5S', 'KH']
n=10;deckList = ['KS', 'KC', '4S', '5D', '7H', 'KH', 'AH', '9D', 'QH', '8S', '5C', 'JH', 'QS', '3S', 'AS', 'KD', '6D', '5H', '5S', 'JS']
deck1 = []
deck2 = []
ergList = []... | mw197hub/codingame | easy/Faro shuffle/main.py | main.py | py | 937 | python | en | code | 0 | github-code | 1 |
34874768696 | '''
백준 2812번 크게 만들기
그리디
'''
_, a = map(int, input().split())
N = list(input())
flg = 0
i = 0
ans = []
while i < len(N):
if ans and \
ans[-1] < N[i] and \
flg < a:
ans.pop()
flg += 1
else:
ans.append(N[i])
i += 1
if a > flg:
ans = ans[:-(a-flg)]
print(''.join(... | CodeNinja1126/coding_test | coding_test_py/2812.py | 2812.py | py | 347 | python | ko | code | 0 | github-code | 1 |
24997981874 | from requests_html import HTMLSession
from bs4 import BeautifulSoup
a_buscar='jamon'
url_base='https://www.amazon.es/s?k='+a_buscar+'&__mk_es_ES=%C3%85M%C3%85%C5%BD%C3%95%C3%91&ref=nb_sb_noss'
s=HTMLSession()
def get_data(url):
r=s.get(url)
r.html.render(sleep=1)
soup=BeautifulSoup(r.html.html,'html.parser')
... | LuisJulian17/botprecios | webs3.py | webs3.py | py | 915 | python | es | 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.