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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
12632788840 | # -*- coding: utf-8 -*-
#http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html
#ROSとOpenCVの競合を避ける
import sys
try:
py_path = sys.path
ros_CVpath = '/opt/ros/kinetic/lib/python2.7/dist-packages'
if py_path[3] == ros_CVpath:
... | TANUKIpro/color_tracker | hsv_supporter.py | hsv_supporter.py | py | 6,909 | python | en | code | 0 | github-code | 1 |
14868493748 | class Matrix22:
def __init__(self, top, bottom):
self.tl, self.tr = top
self.bl, self.br = bottom
def __mul__(self, other):
tl = self.tl * other.tl + self.tr * other.bl
tr = self.tl * other.tr + self.tr * other.br
bl = self.bl * other.tl + self.br * other.bl
br =... | showell/matrix-fib | matrix.py | matrix.py | py | 945 | python | en | code | 0 | github-code | 1 |
5737721660 | import click
from screeps_loan import app
import screepsapi.screepsapi as screepsapi
from screeps_loan.models.db import get_conn
from screeps_loan.screeps_client import get_client
from screeps_loan.models import db
from screeps_loan.services.cache import cache
import screeps_loan.models.alliances as alliances
import s... | LeagueOfAutomatedNations/Screeps-LoAN | screeps_loan/cli/import_rankings.py | import_rankings.py | py | 9,032 | python | en | code | 13 | github-code | 1 |
28538901581 | from django.http.response import HttpResponseRedirect
from django.shortcuts import render
from django.http import HttpResponse
from .forms import AddOfferForm
from .models import Offer
from main.models import Dog
import pyrebase
from pyrebase.pyrebase import Database
config = {
"apiKey": "AIzaSyAgaZYQDBNyfMNI3A7o... | zmazk123/GoDoggo | addOffer/views.py | views.py | py | 1,416 | python | en | code | 0 | github-code | 1 |
36180034799 |
drink_list2 = {'물': 20, '레몬워터': 20, '옥수수 수염차': 20, '콘트라베이스 커피': 20, '트레비': 20,
'밀키스': 20, '펩시': 20, '핫식스': 20, '칠성사이다': 20, '코코 망고맛': 20, '립톤 아이스티': 20,
'트로피카나 스파클링 사과맛': 20, '트로피카나 스파클링 포도맛': 20, '가나': 20,
'레쓰비': 20, '카타타 라떼... | HyeokjuKing/- | main.py | main.py | py | 7,099 | python | ko | code | 0 | github-code | 1 |
22854557677 | from odoo import fields, models, api
from odoo.addons import decimal_precision as dp
class PurchaseOrderLine(models.Model):
_inherit = 'purchase.order.line'
secondary_unit_price = fields.Float(
digits=dp.get_precision('Product Unit of Measure'),
)
@api.multi
def _create_stock_moves(self,... | ecosoft-odoo/rjc | rjc_purchase/models/purchase_order.py | purchase_order.py | py | 809 | python | en | code | 2 | github-code | 1 |
36905506190 | import os
import torch
import numpy as np
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from torchvision import transforms
from PIL import Image
from typing import List
from tqdm import tqdm
from two_tower_model.tower import TwoTowerModel
from two_tower_model.selectivesearch import selective_search,... | RickyDoge/WFGN | dataset/data_prepare.py | data_prepare.py | py | 4,068 | python | en | code | 0 | github-code | 1 |
20731047468 | from bs4 import BeautifulSoup as BSHTML
import os
import re
html_directory = "data/patent_htmls/"
fp_citations_dir = 'data/fp_citations_from_html'
if not os.path.exists(fp_citations_dir):
os.makedirs(fp_citations_dir)
citations_per_patent = dict() # key is patent_number; value is array of citation texts
ref_lo... | tmleiden/citation-extraction-with-flair | get_fp_citations_from_html.py | get_fp_citations_from_html.py | py | 1,861 | python | en | code | 5 | github-code | 1 |
6095696277 | import aoc_utils
def inc1(x):
return x + 1
def inc2(x):
return [x + 1, x - 1][x > 2]
def main(tape, inc):
index = 0
step = 0
while index >= 0 and index < len(tape):
next_index = index + tape[index]
tape[index] = inc(tape[index])
index = next_index
step += 1
re... | nabraham/advent-of-code | 2017/05_tape.py | 05_tape.py | py | 570 | python | en | code | 0 | github-code | 1 |
36112486215 | import sys
import getopt
import numpy as np
import scipy
from scipy import ndimage
from os import listdir
import matplotlib.pyplot as plt
def Read_CSV(fname):
f = open(fname, "r")
Y = np.empty((1, 0))
X = np.empty((64*64*3,0))
i=0
for line in f:
data = line.split(',')
with urllib.re... | palafrank/simpleNN | classifier.py | classifier.py | py | 12,102 | python | en | code | 0 | github-code | 1 |
28541314438 | import tkinter as tk
mat_op = ''
def click_vienads():
global mat_op
otrais_skaitlis = int(teksta_lauks.get())
result = 0
if mat_op == '+':
result = pirmais_skaitlis + otrais_skaitlis
elif mat_op == '-':
result = pirmais_skaitlis - otrais_skaitlis
elif mat_op == '*':
re... | aquarios77/python | 2021-04-15/kalkulators.py | kalkulators.py | py | 3,539 | python | en | code | 0 | github-code | 1 |
73654169313 | import math
from qgis.PyQt import QtGui, QtCore
from qgis.core import (
QgsCircle,
QgsPoint,
QgsPointXY,
QgsFeature,
QgsGeometry,
QgsCircularString,
QgsSnappingConfig,
QgsProject,
QgsTolerance,
)
from qgis.PyQt.QtCore import pyqtSignal
from qgis.gui import QgsMapTool, QgsVertexMar... | danylaksono/GeoKKP-GIS | modules/draw_dimension.py | draw_dimension.py | py | 16,267 | python | en | code | 2 | github-code | 1 |
19168913354 |
class Meta:
def __getattr__(self, name):
print('get', name)
def __setattr__(self, name, value):
print('set', name, value)
if __name__ == '__main__':
x = Meta()
x.append = '+'
x.append
x.lang = 'Python'
x.lang
x.framework
x.framework = 'Django'
| paulitstep/python_oop | 2_basic_tasks/4_metaclass.py | 4_metaclass.py | py | 300 | python | en | code | 0 | github-code | 1 |
13649089846 | import json
from rest_framework import status
from api.constans import AutoNotificationConstants, TaskStageConstants, \
CopyFieldConstants
from api.models import *
from api.tests import GigaTurnipTestHelper, to_json
class CategoryTest(GigaTurnipTestHelper):
def test_list_categories(self):
products_... | KloopMedia/GigaTurnip | api/tests/test_category.py | test_category.py | py | 2,712 | python | en | code | 2 | github-code | 1 |
2721128933 | class Solution:
def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:
ans = 0
j = -1
pMin = -1
pMax = -1
for i, num in enumerate(nums):
if num < minK or num > maxK:
j = i
if num == minK:
pMin = i
... | tushar-kumar/MyCodes | LeetCode/2444. Count Subarrays With Fixed Bounds/2444. Count Subarrays With Fixed Bounds.py | 2444. Count Subarrays With Fixed Bounds.py | py | 435 | python | en | code | 3 | github-code | 1 |
15994963349 | def addTwoNumbers1(self, l1, l2):
num1 = 0
num2 = 0
count = 0
while l1:
num1 += l1.val * (10 ** count)
count += 1
l1 = l1.next
count = 0
while l2:
num2 += l2.val * (10 ** count)
count += 1
l2 = l2.next
result = str(num1 + num2)
last = ... | Kynel/algorithm | python/선형 자료구조/code/addTwoNumbers.py | addTwoNumbers.py | py | 989 | python | ko | code | 0 | github-code | 1 |
3521363585 | from derivacao.derivada import derivada
from derivacao.polinomio import gerarpolinomio, gerarfuncao
import math
#x = int(input("Insira o valor de x >> "))
grau = int(input("Insira o grau do polinômio >> "))
poli = gerarpolinomio(grau)
f = gerarfuncao(poli)
x_par = int(input("Insira o valor de x >> "))
z = 1
while(... | ubiratann/CK0048 | main.py | main.py | py | 992 | python | pt | code | 2 | github-code | 1 |
15359754817 | import os
import cv2
import matplotlib.pyplot as plt
import numpy as np
import yaml
class Map:
'''
Wraps ros2 map into a class
'''
def __init__(self):
self.yaml_path = ''
self.image_path = ''
self.image = None
self.resolution = None
self.origin = [0.0,... | JChunX/libf1tenth | libf1tenth/planning/map.py | map.py | py | 5,213 | python | en | code | 0 | github-code | 1 |
16284337583 | from os import environ as env
from setuptools import find_packages, setup
from setuptools.command.install import install
import sys
VERSION = "0.1.0"
with open("README.md", "r", encoding="utf-8") as rdm:
long_description = rdm.read()
class VerifyVersionCommand(install):
"""Custom command to verify that the ... | BentoBox-Project/clipenv | setup.py | setup.py | py | 1,715 | python | en | code | 2 | github-code | 1 |
86577823 | # temperature
temp = int( input("What will be the maximum temperature today? ") )
if temp <10:
print("Cold today")
elif temp < 20:
print("Regular Wellington day, today")
else:
print("Hot today")
print(20*"-")
# allowance
kitchen = input("Have you helped clean the kitchen (y/n) ? ")
allowance = 5
if kitche... | paul-khouri/year11_2020 | code_activities/conditionals/worksheet_solutions.py | worksheet_solutions.py | py | 1,553 | python | en | code | 0 | github-code | 1 |
41096561337 | # imports
import datetime as dt
import os
import os.path as osp
import time
import numpy as np
from .global_imports.smmpl_opcodes import *
from .quickscanpat_calc import quickscanpat_calc
from .sop import sigmampl_boot
# params
_nodoubleinit_l = [
'suncone'
]
# main func
def main(quickscantype=None, **quicksc... | citypilgrim/smmpl_opcodes | quickscan_main.py | quickscan_main.py | py | 2,652 | python | en | code | 0 | github-code | 1 |
26025847015 | from inspect import getcomments
from pickle import FALSE, TRUE
import ee
import geemap
import datetime
import pandas as pd
import shapely.wkt
import multiprocessing
ee.Initialize()
visParamsTrue = {'bands': ['B4', 'B3', 'B2'], min: 0, max: 2000}
CLOUD_FILTER = 50
CLD_PRB_THRESH = 50
NIR_DRK_THRESH = 0.15
CLD_PRJ_DIST ... | aakashthapa22/Parcel-Level-Flood-and-Drought-Detection-using-AI | NDVI and NDWI on Sentinel-2A images/NDVINDWI.py | NDVINDWI.py | py | 11,646 | python | en | code | 1 | github-code | 1 |
8431592570 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Модуль класса управления ресурсом проекта.
Описание ресурсного файла проекта информационной системы:
<имя файла> := *.pro
<описание проекта информационной системы> =
[
{<описание проекта текущей информационной системы>},
{<описание проекта импортируемой информаци... | XHermitOne/defis3 | ic/prj/PrjRes.py | PrjRes.py | py | 39,301 | python | ru | code | 0 | github-code | 1 |
29476078580 | from itertools import count
from numpy import poly1d
import streamlit as st
from streamlit_option_menu import option_menu
import pandas as pd
import re
# Data Viz Pkgs
import plotly
import plotly.express as px
import plotly.graph_objs as go
from db_fxns import add_data, create_table, view_all_data, get_name, view_uni... | kinteog/sam-diseaseprediction | database_page.py | database_page.py | py | 19,402 | python | en | code | 0 | github-code | 1 |
1918061715 | #!/usr/bin/env python
# coding=utf-8
"""
TBW
"""
from __future__ import absolute_import
from __future__ import print_function
from collections import MutableSequence
import io
import os
import random
from ipapy.compatibility import to_str
from ipapy.compatibility import to_unicode_string
__author__ = "Alberto Petta... | pettarin/wiktts | wiktts/lexicon.py | lexicon.py | py | 5,575 | python | en | code | 5 | github-code | 1 |
927501499 | from __future__ import print_function
import argparse
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.util... | coimbra574/Projeto_IA376 | src/data/generate_samples_WGAN.py | generate_samples_WGAN.py | py | 2,902 | python | en | code | 1 | github-code | 1 |
28213535321 | #!/usr/bin/env python3
from aws_cdk import core
from cloudwatch_embedded_metric.cloudwatch_embedded_metric_stack import LambdaEmbeddedMetricsStack
app = core.App()
# Miztiik demonstration to show how to embed custom metrics alongside detailed log event data
miztiik_cloudwatch_embedded_metric_demo = LambdaEmbeddedMe... | miztiik/cloudwatch-embedded-metric | app.py | app.py | py | 912 | python | en | code | 0 | github-code | 1 |
34653970905 | from conabio_irekua_migrations.base_migration import BaseMigration
class Migration(BaseMigration):
dependencies = [
('conabio_irekua_migrations', 'annotation_types'),
]
items_subdir = 'types/mimes'
def load_models(self, apps):
self.MimeType = apps.get_model('irekua_database', 'MimeTy... | CONABIO-audio/conabio-irekua-data-migrations | conabio_irekua_migrations/migrations/mime_types.py | mime_types.py | py | 562 | python | en | code | 0 | github-code | 1 |
34197163170 | from math import pow, sqrt, pi, asin
x1 = float(input('x1: '))
y1 = float(input('y1: '))
x2 = float(input('\nx2: '))
y2 = float(input('y2: '))
x3 = float(input('\nx3: '))
y3 = float(input('y3: '))
def lenSide(x1, y1, x2, y2):
s1 = abs(x1 - x2)
s2 = abs(y1 - y2)
side = sqrt(pow(s1, 2) + pow(s2, 2))
return s... | mash2000/famen | task5/task5.py | task5.py | py | 2,524 | python | en | code | 0 | github-code | 1 |
1531048643 | from metadrive.envs.metadrive_env import MetaDriveEnv
def test_traffic_mode(render=False):
try:
for mode in ["hybrid", "trigger", "respawn"]:
env = MetaDriveEnv(
{
"num_scenarios": 1,
"traffic_density": 0.1,
"traffic_m... | metadriverse/metadrive | metadrive/tests/test_functionality/test_traffic_mode.py | test_traffic_mode.py | py | 1,270 | python | en | code | 471 | github-code | 1 |
5971353544 | from project.player.player import Player
class PlayerRepository:
def __init__(self):
self.count = 0
self.players = []
def add(self, player: Player):
if player.username in [p.username for p in self.players]:
raise ValueError(f"Player {player.username} already exists!")
... | LachezarKostov/SoftUni | 03_ОOP-Python/00-Exams/Python OOP Exam Preparation - 02. Avg 2020/skeleton/project/project/player/player_repository.py | player_repository.py | py | 885 | python | en | code | 1 | github-code | 1 |
10121361892 | import socket
import numpy as np
from gym import spaces
import pickle
#import paramiko
import copy
import os
class DCS_env:
def __init__(self, host_ip='192.168.3.37', host_port=30000, size=1024):
# 参数调整
self.state_dim = 12
self.action_dim = 7
self.observation_space = spaces.Box(low=... | BillChan226/RL_Plane_Strategy | rl_algorithms/algos/ppo/DCS_environment.py | DCS_environment.py | py | 4,736 | python | en | code | 4 | github-code | 1 |
38754189957 | # -*- coding: utf-8 -*-
"""
@author: gunning
This program takes the output from the QOFProcessor. It sums the list and prevalence for
each practice in each ward. Then it outputs a file called LondonQOFAggregated-yyyy
"""
import pandas as pd
from tkinter import Tk
from tkinter.filedialog import askopenfilenam... | SimonGunning/LAQNHealth | AggregateQOF.py | AggregateQOF.py | py | 1,477 | python | en | code | 0 | github-code | 1 |
19802050508 | import os
import argparse
import joblib
import pandas as pd
from sklearn import metrics
from sklearn import tree
import config
import model_dispatcher
def run(fold, model):
#read the training data with folds
df = pd.read_csv(config.TRAINING_FILE)
#to replace by feature engineering
df = df.drop(['Nam... | vitormnsousa/ml-template | src/train.py | train.py | py | 1,731 | python | en | code | 0 | github-code | 1 |
6668093221 | print("Secuencia Fibonacci")
def Fibonacci():
Numero1=0
Numero2=1
for Valor in range(0,10):
if(Valor==0):
Numero2=0
if(Valor==1):
Numero2=1
if(Valor==2):
Numero1=0
Resultado=Numero1+Numero2
Numero1=Numero2
Numero2=Resultado
print(Resultado)
if (__name__ == '__main__'):
Fibonacci() ... | Robert170/Intro_Progra | fibonacci.py | fibonacci.py | py | 364 | python | es | code | 0 | github-code | 1 |
21087590741 | import argparse
import matplotlib.pyplot as plt
import numpy as np
import h5py
import gusto_dataset
global_vars = dict(num_files=0, file_index=0)
def plot_faces(filename, args):
dset = gusto_dataset.GustoDataset(filename)
segments = dset.get_face_segments()
for seg in segments:
plt.plot(seg[:,0]... | jzrake/gusto | plot.py | plot.py | py | 3,290 | python | en | code | 0 | github-code | 1 |
18884483513 | import argparse
import glob
import os
import numpy as np
from scipy import ndimage
from PIL import Image
from tqdm import tqdm
def main(args):
image_paths = glob.glob(os.path.join(args.annotation_train_dir, "*.png"))
image_paths.extend(glob.glob(os.path.join(args.annotation_valid_dir, "*.png")))
invalid_i... | hmchuong/Detectron | test_invalid_image.py | test_invalid_image.py | py | 2,358 | python | en | code | 0 | github-code | 1 |
441496425 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 4 21:45:34 2019
@author: Reza
"""
a ='1174084' #variabel/angka yang akan di konversi.
integer = int(a) #konversi string ke integer
a = 1174084 #variabel/angka yang akan di konversi.
string = str(a) #konversi integer ke string
#while loop
i = 1
while i < 6:
print(i)
... | duktek/praktikum_2c | src/1174084/1174084.py | 1174084.py | py | 6,599 | python | en | code | 1 | github-code | 1 |
30322083670 | import random
import os
import numpy as np
# 将按顺序写入的训练数组置软
zlshuzhutrain = random.sample(range(800), 800)
# 将按顺序写入的测试置软
zlshuzhutest = random.sample(range(200), 200)
############################################################
# 读取按顺序存储的文件
###########################################################
# tmp_filename... | huilizhou/Deeplearning_Python_DEMO | operate_clouddata/shuzhuzhiluan_20190605.py | shuzhuzhiluan_20190605.py | py | 2,489 | python | en | code | 0 | github-code | 1 |
1747104065 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 1 16:53:16 2018
@author: dingyuhao
"""
class person():
def __init__(self, address, age, phone):
self.address = address
self.age = age
self.phone = phone
Jerry = person('huangpu', 18, 13131313133)
print(Jerry.a... | YuhaoDing-hub/ics | hw5/untitled0.py | untitled0.py | py | 327 | python | en | code | 0 | github-code | 1 |
25029481776 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 4 18:21:47 2022
@author: albertomengual
Studying the Chapter 7: Regular Expressions
"""
import re
message = 'Call me 415-555-1011 tomorrow, or at 415-555-9998 is my office'
message2 = 'Call me 555-1011 tomorrow, or at (415)-555-9998 is my of... | aldamepi/Udemy-AutomatePython | regex.py | regex.py | py | 6,750 | python | en | code | 0 | github-code | 1 |
29614390408 | import librosa, librosa.display
import os
import pandas as pd
import numpy as np
def normalize_volume(file_path):
y, sr = librosa.load(file_path)
y_norm = librosa.util.normalize(y, axis=0)
return y_norm, sr
def extract_features(y_norm, sr):
features = []
# Tempo and beats
tempo, beats = libr... | rsmassey/mcats | mcats/wav_extraction/feature_extraction.py | feature_extraction.py | py | 1,454 | python | en | code | 0 | github-code | 1 |
28544550581 | import os.path
from os import popen
import codecs
import sublime, sublime_plugin, re
import rubybeautifier
l_settings = sublime.load_settings("RubyFormat.sublime-settings")
class RubyFormatCommand(sublime_plugin.TextCommand):
def run(self, edit):
sublime_settings = self.view.settings()
selection = s... | zmbacker/RubyFormat | ruby_formatter.py | ruby_formatter.py | py | 2,971 | python | en | code | 12 | github-code | 1 |
19235227239 | from IAF.flows.iaf import IAF_mod
from torch import nn
import torch
class IAF_flow(nn.Module):
def __init__(self, dim, n_flows,tanh_flag,C=100):
super().__init__()
self.flow = nn.ModuleList([
IAF_mod(dim,dim,dim) for _ in range(n_flows)
])
self.C = C
self.tanh_fla... | MrHuff/DIF-NLDL | IAF/IAF.py | IAF.py | py | 621 | python | en | code | 0 | github-code | 1 |
5230043340 | import tempfile
import pdfkit
from django.contrib import messages
from django.http import FileResponse
from django.shortcuts import render
from django.template.loader import get_template
from rest_framework import generics
from rest_framework.permissions import (
SAFE_METHODS,
BasePermission,
IsAuthenti... | mumoj/Music-Festival-Scheduling | performances/views.py | views.py | py | 3,203 | python | en | code | 0 | github-code | 1 |
2845928618 |
import cv2
import os
import time
from time import sleep
import numpy as np
import pytesseract
import threading
from actions import doAction
import nxbt
import copy
import torch
from predictor import divide, predict
#pytesseract.pytesseract.tesseract_cmd = r'C:/Program Files/Tesseract-OCR/tesseract.exe'
r... | yannik603/Smash-Ultimate-Bot | env.py | env.py | py | 5,142 | python | en | code | 3 | github-code | 1 |
39560557801 | import streamlit as st
import numpy as np
import pandas as pd
import plotly.express as px
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
from datetime import datetime
import db
st.title("Product Review Analysis")
st.sidebar.title("Select Your Choices")
st.set_option('deprecation.showPyplotG... | AnythingIsFineLambton/Product_Review | Home.py | Home.py | py | 3,036 | python | en | code | 0 | github-code | 1 |
19839968648 |
groups = []
groups2 = []
with open('questionnaire.txt', 'r') as answers:
group = ''
group2 = []
for line in answers.readlines():
if line == '\n':
groups.append(group)
groups2.append(group2)
group = ''
group2 = []
continue
group +=... | brucejeremy/Advent-of-code | 2020/06/Day6.py | Day6.py | py | 962 | python | en | code | 0 | github-code | 1 |
8558487936 | from gensim.models.doc2vec import TaggedDocument
from utils import ExecutionTime
def tagging(cleaned_text: list):
print('Tagging started...')
t = ExecutionTime()
t.start()
idx = [str(i) for i in range(len(cleaned_text))]
tagged_text = []
for i in range(len(cleaned_text)):
tagged_text.a... | Cashaqu/wine_advisor | tagging.py | tagging.py | py | 467 | python | en | code | 0 | github-code | 1 |
24253712581 | import maze
from PIL import Image, ImageDraw
import time
from sys import argv
def print_maze(side, mymaze):
print("|-" * side + "|")
for i, slot in enumerate(mymaze):
print(slot, end=' ') if slot is not None else print('X', end=' ')
if (i + 1) % (side) == 0:
print("")
print("|-"... | Araggar/INE5417-MazeRunner | greyscale.py | greyscale.py | py | 2,073 | python | en | code | 1 | github-code | 1 |
14152913313 | # -*- coding: utf-8 -*-
import re
from flask import redirect, url_for
id_check = re.compile('([0-9a-f]+)')
genre_check = re.compile('([0-9a-z_]+)')
zip_check = re.compile('([0-9a-zA-Z_.-]+.zip)')
fb2_check = re.compile('([ 0-9a-zA-ZА-Яа-я_,.:!-]+.fb2)')
def unurl(s: str):
tr = {
'%22': '"',
'%27... | stanislavvv/fb2_srv_pseudostatic | app/validate.py | validate.py | py | 1,643 | python | en | code | 0 | github-code | 1 |
71223267555 | # O(unknown) https://en.wikipedia.org/wiki/Collatz_conjecture
class Solution:
def getKth(self, lo: int, hi: int, k: int) -> int:
powers = {0: 1, 1: 0}
arr = []
for i in range(lo, hi + 1):
self.calculatePower(i, powers)
arr.append((i, powers[i]))
return self.... | ClaudioCarvalhoo/you-can-accomplish-anything-with-just-enough-determination-and-a-little-bit-of-luck | problems/LC1387.py | LC1387.py | py | 1,226 | python | en | code | 0 | github-code | 1 |
29673511225 | import numpy as np
from jass.base.const import color_masks, card_values, card_strings, PUSH, trump_strings_german_long
from jass.base.player_round import PlayerRound
from jass.player.player import Player
import RuleBasedPlayer.rbp_score as rbp_score
# Win Threshold: we want at least x score (otherwise we try to PUSH... | tschibu/hslu-dl4g | RuleBasedPlayer/rbp_trump.py | rbp_trump.py | py | 1,669 | python | en | code | 0 | github-code | 1 |
12922555819 | # De Django
from django.urls import path
# Propios
from . import views
urlpatterns = [
path('',views.home,name='home'),
path('manual',views.manual,name='manual'),
path('login',views.login_page,name='login-page'),
path('register',views.register,name='register'),
path('logout',views.logout_staff,name... | Haziel-Soria-Trejo/GymAdmin | base/urls.py | urls.py | py | 544 | python | en | code | 0 | github-code | 1 |
15072056728 | from os import path
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.test import TestCase, override_settings
from django.test.client import RequestFactory
from django.urls import reverse
from ..errors import (
AttachmentTooLargeError,
AuthenticationError,
)
from... | yunojuno-archive/django-inbound-email | inbound_email/tests/test_views.py | test_views.py | py | 8,035 | python | en | code | 67 | github-code | 1 |
72337035875 | from bs4 import BeautifulSoup
import requests
import json
import time
import random
headers = {
'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Mobile Safari/537.36'
}
# GetAllLinksAndNamesFromPolitics
res = requests.get(f'https://www.... | Artemxxx2/ParserGermanParliament | ParliamentParser.py | ParliamentParser.py | py | 3,214 | python | en | code | 0 | github-code | 1 |
11324625878 | from __future__ import annotations
from typing import Any, List, Literal, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Callable, Union, Dict, overload
from contextvars import ContextVar
import inspect
import os
from .item import Item, ItemCallbackType
from ..enums import ChannelType, ComponentType
from ..partial_emo... | Rapptz/discord.py | discord/ui/select.py | select.py | py | 32,941 | python | en | code | 13,719 | github-code | 1 |
12288030546 | #!/usr/bin/env python2.7
import numpy as np
import cv2
import glob
import json
from copy import copy
import os
class Configure():
def __init__(self):
self.objpoints = []
self.imgpoints = []
self.height = 480
self.width = 640
def getCalibrationParameters(self):
dim = (8,... | pbsinclair42/SDP-2016 | vision/scripts/get_camera_configuration.py | get_camera_configuration.py | py | 2,294 | python | en | code | 2 | github-code | 1 |
35627619001 | from pytube import YouTube
def checkVideoResolution(tmp):
videoResolution = ["2160p","1440p","1080p","720p","480p","360p","240p", "144p"]
array = []
url = YouTube(tmp)
for i in range(len(videoResolution)):
if(len(url.streams.filter(adaptive=True, file_extension='mp4', res=videoResolution[i]))>0)... | RamkaTheRacist/python-RTR | PY_les10_s/HW/ytdl/dloadlogic/resolutions.py | resolutions.py | py | 699 | python | en | code | 0 | github-code | 1 |
39601964882 | import datetime
import json
import requests
from django.conf import settings
from django.db import models
class Bill(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
comment = models.CharField(max_length=45, default='')
amount = models.FloatField(default=1.00)
status = models.Char... | AlexFire-Dev/Billing | apps/bills/models.py | models.py | py | 2,918 | python | en | code | 0 | github-code | 1 |
43819454476 | from sqlalchemy import and_
from sqlalchemy import delete
from sqlalchemy import desc
from sqlalchemy import select
from sqlalchemy.orm import Session
from danswer.db.models import ConnectorCredentialPair
from danswer.db.models import DeletionAttempt
from danswer.db.models import DeletionStatus
from danswer.db.models ... | wuzhiping/danswer | backend/danswer/db/deletion_attempt.py | deletion_attempt.py | py | 2,567 | python | en | code | 0 | github-code | 1 |
26721674595 | import json
from flask import Flask, render_template, jsonify, request, make_response, current_app
from random import *
from flask_cors import CORS
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
import logging
from logging.handlers import RotatingFileHandler
from flask_httpauth import HTTPToken... | Ciscol/license_backend | run.py | run.py | py | 6,038 | python | en | code | 0 | github-code | 1 |
27800897397 | from XssMapObject import XssMapObject
class RequestVariableProbe(object):
"""
Isolates parameters from HTTP requests that can be probed with reflection checking
or XSS scanning.
"""
@staticmethod
def __has_URL_params(url):
"""
(Private) Checks if provided URL has parameters in ... | secdec/xssmap | RequestVariableProbe.py | RequestVariableProbe.py | py | 3,463 | python | en | code | 127 | github-code | 1 |
1892818579 | '''
Created on 29/11/2009
@author: Nahuel
'''
import unittest
from opsys.process.ProcessStore import ProcessStore
from opsys.process.Process import Process
class TestProcessStore(unittest.TestCase):
def setUp(self):
self.store = ProcessStore()
self.testPCB = Process(547, 'x', 10, [], 1, 1).get... | ngarbezza/tpi-so1-tp | src/testing/TestProcessStore.py | TestProcessStore.py | py | 1,131 | python | en | code | 0 | github-code | 1 |
70398785315 | rows, cols = [int(x) for x in input().split()]
matrix = []
for i in range(rows):
list = []
for j in range(cols):
first_last = 97 + i
middle = 97 + i + j
list.append(f'{chr(first_last)}{chr(middle)}{chr(first_last)}')
matrix.append(list)
for row in range(len(matrix)):
print(' '.jo... | bozhimirov/softuni_python_advanced | Multidimensional Lists - Exercise 1/05. Matrix of Palindromes.py | 05. Matrix of Palindromes.py | py | 347 | python | en | code | 1 | github-code | 1 |
30297055815 | #!/usr/bin/env python
import visvis as vv
app = vv.use()
f = vv.clf()
a = vv.cla()
vv.plot([12,34,21,38], lc='b', ls=':',mc='b', mw=7, lw=2, ms='s', mec='r')
vv.plot([1,3,4],[33,47,12], lc='r', mc='r', ms='.')
vv.plot([20,24,45,21], lc='g', ls='--', mc='g', mw=12, lw=3, ms='')
vv.plot([35,14,40,31], lc='k', ls='-.'... | almarklein/visvis | examples/plotting.py | plotting.py | py | 632 | python | en | code | 227 | github-code | 1 |
16521253775 | import os
import sys
import logging
from song import Song
import numpy as np
# Dataset: Loads and passes test data to the model
class Dataset:
def __init__(self, logger, config):
self.logger=logger
self.config=config
# Raw data
self.mixtures = []
self.vocals = []
# O... | zingmars/vocal-music-separation | dataset.py | dataset.py | py | 3,707 | python | en | code | 20 | github-code | 1 |
26673322022 | import os.path
import subprocess
def compressData(files, output, name, finalDirName):
print("Compressing data")
shellScriptCall = ["./dataCompressor.sh"]
shellScriptCall.append(output)
shellScriptCall.append(str(len(files)))
shellScriptCall.extend(files)
shellScriptCall.append(name)
shellSc... | nikiitin/RING-5 | dataParse.py | dataParse.py | py | 1,293 | python | en | code | 1 | github-code | 1 |
74525946592 | from collections import namedtuple
import dgl
from dgl.data.tree import SSTDataset
SSTBatch = namedtuple('SSTBatch', ['graph', 'mask', 'wordid', 'label'])
trainset = SSTDataset(mode='tiny')
tiny_sst = trainset.trees
num_vocabs = trainset.num_vocabs
num_classes = trainset.num_classes
vocab = trainset.voc... | acproject/GNNs | GNN/Model/TreeLSTM.py | TreeLSTM.py | py | 9,765 | python | en | code | 1 | github-code | 1 |
39594408669 | # editor: Wang Zhixiong
from typing import TypeVar, Generic, List, Iterator
from typing import Any
from typing import Union
from typing import Generator
from typing import Callable
from typing import Optional
K = Union[str, int, float]
D = Union[None, str, int, float]
class TreeNode:
def __init__(se... | Zhixiong-Wang/CPO-Dreams-of-billion-girs_lab2_varliant6 | immutable.py | immutable.py | py | 6,679 | python | en | code | 0 | github-code | 1 |
10808815511 | import requests
import sys
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
MAX_RETRY_NUM = 5
BACKOFF_FACTOR = 1
STATUS_FORCELIST = [502, 503, 504]
def get_request(url):
"""
Attempts to get the HTML content with the given URL by making an HTTP GET request. It ... | vonniewu/nga-artists | nga_artists/html_request.py | html_request.py | py | 1,651 | python | en | code | 1 | github-code | 1 |
487845027 | from PIL import Image
import colorsys
import numpy as np
nx, ny = 128, 128
def createHSVimage(hue, sat, val, alpha):
rgba = []
# convert hsv -> rgb
for h, s, v, a in zip(hue.tolist(), sat.tolist(), val.tolist(), alpha.tolist()):
r, g, b = colorsys.hsv_to_rgb(h, s, v)
rgba.append( (int(255*r... | will-henney/phabc2-post | mhdcuts-Bkey.py | mhdcuts-Bkey.py | py | 2,188 | python | en | code | 1 | github-code | 1 |
20347571825 | # Напишите программу, удаляющую из текста все слова, содержащие ""абв"".
# Добавлено сохранение пунктуации
import string
string.punctuation
def main():
text = 'вапроеалдад абв роло АБВ, абвапро апргшл'
for i in string.punctuation:
if i in text:
text = text.replace(i, f' {i}')
text = ... | oksanaverkh/Python_Homework5 | Task1.py | Task1.py | py | 688 | python | ru | code | 0 | github-code | 1 |
21199548543 | # -*- coding: utf-8 -*-
import math
import numpy as np
################################################################################
# ANGLE MATH
################################################################################
def quaternionToRotationMatrix( q ):
# algorithm expects q = [ qw, qx, qy, qz ] and ... | CIFASIS/object-detection-sptam | ros/sptam/plotters/utils/mathHelpers.py | mathHelpers.py | py | 7,122 | python | en | code | 23 | github-code | 1 |
33610804953 | from signal import signal
import Finder.CandleStick as candle
import Enum.CommonEnum as enum
def isPiercingCloudCoverPattern(prev_openPrice, prev_closePrice, openPrice, closePrice):
#closePrice < prev_openPrice and closePrice > prev_closePrice and openPrice < prev_closePrice and \ will move seperate method later
... | OurTradingLogic/TradingLogic | Finder/Pattern.py | Pattern.py | py | 3,927 | python | en | code | 2 | github-code | 1 |
592585735 | """
This code is for a Monte Carlo sensitivity analysis
of the ABM of environmental migration
@author: kelseabest
"""
#import packages
from matplotlib.colors import LinearSegmentedColormap
import random
import math
import numpy as np
import matplotlib.pyplot as plt
#define vars
N = 100 #number of individual agents
... | jonathan-g/ABM_py | monte_carlo.py | monte_carlo.py | py | 1,604 | python | en | code | 0 | github-code | 1 |
43184453169 | import cv2
import numpy as np
import os
# from .myEdgeDetector import myCanny
from myHoughLines import Handwrite_HoughLines
from myHoughTransform import Handwrite_HoughTransform
# parameters
sigma = 2
threshold = 0.03
rhostep = 2
thetastep = np.pi / 90
num_lines = 15
# end of parameters
img0 = cv2.imread(... | TaikiShuttle/ECE4880J | hw3/houghScript.py | houghScript.py | py | 1,668 | python | en | code | 1 | github-code | 1 |
5752293389 | import tensorflow as tf
from tensorflow.python.ops.losses.losses_impl import Reduction
def one_step_td_loss(reward_t_1, gamma, q_t, q_t_1, action_t, done, double_q=False, q_t_1_d=None):
with tf.name_scope('one_step_td_loss'):
with tf.name_scope('Q_Estimate'):
# Get shape of action vector (requ... | RoganInglis/RLAgents | agents/losses.py | losses.py | py | 1,919 | python | en | code | 0 | github-code | 1 |
25810988721 | import json
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from drawing import draw_pitch
def import_xtvalues():
with open('input_data/open_xt_12x8_v1.json', 'r') as f:
xTvalues = np.array(json.load(f))
return xTvalues
def offset_df(df, dx, dy):
df = df.copy()
df.x =... | omarkorim98/Football-Data-Analysis-master | data_statistics/threat_Potential/threat_values.py | threat_values.py | py | 1,704 | python | en | code | 1 | github-code | 1 |
12218730688 | # This program is created to test the functionality of the objects, objects can use the attributes inside the class as well as the methods inside them.
#creating classes
class User:
#creating objects attributes
def __init__(self, userid, username):
self.id = userid
self.uID = username
self.follo... | ejparth/Class_example | main.py | main.py | py | 687 | python | en | code | 0 | github-code | 1 |
5889736252 | #VARIABLES
zero = [1,1,0,1,1,1,1]
one = [0,0,0,1,0,0,1]
two = [1,0,1,1,1,1,0]
three = [1,0,1,1,0,1,1]
four = [0,1,1,1,0,0,1]
five = [1,1,1,0,0,1,1]
six = [1,1,1,0,1,1,1]
seven = [1,0,0,1,0,0,1]
eight = [1,1,1,1,1,1,1]
nine = [1,1,1,1,0,1,1]
error = [1,1,1,0,1,1,0]
list1 = [zero,one,two,three,four,five,six,sev... | DipakAgarwal0703/PRACTISE | BCD_7SEGMENT.py | BCD_7SEGMENT.py | py | 1,755 | python | en | code | 0 | github-code | 1 |
26816142196 |
def solution(N):
maxgap = 0
# Ignore the '0b' at the beginning.
inlst = list(bin(N))[2:]
# Convert to ints.
inlst = [int(x) for x in inlst]
if inlst.count(0) == 0:
# print(n, 0)
return 0
gap = 0
ingap = False
start = 0
for i,bitval in enumerate(inlst):
if... | jimlawton/codility | lessons/01/binary_gap/challenge.py | challenge.py | py | 623 | python | en | code | 0 | github-code | 1 |
16199796086 | import os
import time
import datetime
import subprocess
import yaml
import json
from cravat import admin_util as au
from cravat import ConfigLoader
import sys
import traceback
import shutil
from aiohttp import web
#from cryptography import fernet
#from aiohttp_session import get_session, new_session
impor... | pevs/open-cravat | cravat/websubmit/websubmit.py | websubmit.py | py | 26,894 | python | en | code | null | github-code | 1 |
17958690348 | # 테두리의 합(sum of bordering)
# 정수 N을 입력받아 1~N*N까지 2차원 배열에 저정한 후 사각 테두리에 있는
# 배열값들만 합하여 출력하시오. 예를 들어 3을 입력한다면 테두리의 값인
# 1+2+3+6+9+8+7+4=40을 출력하는 프로그램을 작성하시오.
# method 1
n = int(input())
d = []
k = 0
for i in range(n):
d.append([])
for j in range(n):
k += 1
d[i].append(k)
s = 0
for i in range(n):
... | junes7/python_algorithm | CodeUp/2D_array/1511.py | 1511.py | py | 609 | python | ko | code | 1 | github-code | 1 |
25793358290 | import numpy as np
from scipy.sparse import csr_matrix, vstack, isspmatrix_csr
from tqdm import tqdm
def tfidf_with_dates_to_weekly_term_counts(term_value_array, uspto_week_dates):
number_of_rows, number_of_terms = term_value_array.shape
week_counts_csr = None
if not isspmatrix_csr(term_value_array):
... | Haydn8/pyGrams | scripts/utils/datesToPeriods.py | datesToPeriods.py | py | 2,011 | python | en | code | null | github-code | 1 |
29123925476 | import glob
import os
import shutil
import subprocess
from conftest import aws_credentials_required
# External modules
import pytest
def pyinstaller_exists():
return shutil.which('pyinstaller') is not None
# PyTest doesn't let you place skipif markers on fixures. Otherwise,
# we'd ideally be able to do that a... | nchammas/flintrock | tests/test_pyinstaller_packaging.py | test_pyinstaller_packaging.py | py | 1,977 | python | en | code | 629 | github-code | 1 |
42748162077 | # Need a couple of tries to get shell, some issue in a_write
from pwn import *
#context.log_level = 'debug'
context.terminal = ['tmux', 'splitw', '-h']
file = "./election"
bin = ELF(file)
libc = ELF("libc-2.23.so")
env = {"LD_PRELOAD": os.path.join(os.getcwd(), "./libc-2.23.so")}
#conn = remote("election.pwn.secco... | DhavalKapil/ctf-writeups | seccon-2017/election-200/exploit.py | exploit.py | py | 3,190 | python | en | code | 22 | github-code | 1 |
69895816035 | """empty message
Revision ID: 7a0cb1100d0a
Revises: 3c79ca63799e
Create Date: 2022-06-19 23:56:15.292951
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '7a0cb1100d0a'
down_revision = '3c79ca63799e'
branch_labels = None
depe... | luvyingying/IntelligentFaultHandlingSystem | migrations/versions/7a0cb1100d0a_.py | 7a0cb1100d0a_.py | py | 969 | python | en | code | 1 | github-code | 1 |
170220764 | # -*- coding: utf-8 -*-
'''
/**************************************************************************************************************************
SemiAutomaticClassificationPlugin
The Semi-Automatic Classification Plugin for QGIS allows for the supervised classification of remote sensing images,
provid... | jem0101/BigSwag-SQA2022-AUBURN | TestOrchestrator4ML-main/resources/Data/supervised/GITHUB_REPOS/semiautomaticgit@SemiAutomaticClassificationPlugin/modules/qgisprocessing.py | qgisprocessing.py | py | 6,665 | python | en | code | 2 | github-code | 1 |
16780787848 | import datetime
class exception():
"""
exception(name: str, starttime: datetime, stoptime: datetime,
value: bool)
exceptions used when schemes should be overriden
Methods:
check if starttime and stoptime is now, if true return value
"""
def __init__(self,
name: str,
... | gurkslask/tiddur | app/time_cmd/exception.py | exception.py | py | 738 | python | en | code | 0 | github-code | 1 |
42548147202 | from django.core.paginator import Paginator
from django.http import Http404
from django.shortcuts import render
from .converters import DateConverter
from books.models import Book
def books_view(request):
template = 'books/books_list.html'
context = {'books': Book.objects.all()}
return render(request, te... | graticule/django-homeworks | 2.1-databases/models_list_displaying/books/views.py | views.py | py | 1,375 | python | en | code | 0 | github-code | 1 |
4566035845 | from datetime import datetime, timedelta
import pandas as pd
from framework.configuration.configuration import Configuration
from framework.logger.providers import get_logger
from clients.azure_gateway_client import AzureGatewayClient
from clients.email_gateway_client import EmailGatewayClient
from domain.usage impor... | danleonard-nj/kube-tools-api | services/kube-tools/services/usage_service.py | usage_service.py | py | 3,969 | python | en | code | 0 | github-code | 1 |
25646551717 | # -*- coding: utf-8 -*-
# @Time : 2021/3/2 11:25
# @Author : Zoey
# @File : add_member_page.py
# @describe:
from selenium.webdriver.common.by import By
from seleniumPO.pyse.pyselenium import PySelenium
class AddMemberPage:
def __init__(self, driver):
self.driver = driver
self.element = PyS... | ZhangYi8326/Selenium_Zoey | seleniumPO/page/add_member_page.py | add_member_page.py | py | 1,338 | python | en | code | 0 | github-code | 1 |
21168992917 | """
Question:
3. Create a python script that parses jmeter log files in CSV format,
and in the case if there are any non-successful endpoint responses recorded in the log,
prints out the label, response code, response message, failure message,
and the time of non-200 response in human-readable format in PST timezone
(e... | ujwalnitha/qa-python-exercises | exercise3/filter_responses.py | filter_responses.py | py | 2,635 | python | en | code | 0 | github-code | 1 |
3951785026 | # Variable which vlue is callable
def hellow():
print('hellow !')
hellow()
def user_age_in_seconds():
user_age = int(input("enter your age"))
age_in_seconds = user_age * 365*24*60*60
print("Welcome to my age in second program")
user_age_in_seconds()
print("gode bye")
# function with args
x = int(... | jatinsinghnp/python-3-0-to-master-course | 10_functions/code.py | code.py | py | 592 | python | en | code | 1 | github-code | 1 |
42507627564 | import turtle
import time
screen = turtle.Screen()
screen.bgcolor('orange')
t = turtle.Pen()
t.pensize(4)
t.speed('fast')
COLORS = ["red", "green", "blue", "black"]
for j in range(12):
t.pencolor(COLORS[j % 4])
for i in range(4):
t.forward(100)
t.left(90)
# time.sleep(1.5)
t.left(30)
... | mostafa-sadeghi/class805 | 805/aban_30.py | aban_30.py | py | 646 | python | en | code | 0 | github-code | 1 |
28548701178 | #!/usr/bin/python
# Python
import logging
from datetime import datetime
from time import mktime
# Libraries
import feedparser
# Local
import lifestream
logger = logging.getLogger('Atom')
lifestream.arguments.add_argument('type')
lifestream.arguments.add_argument('url')
args = lifestream.arguments.parse_args()
Lif... | aquarion/Lifestream | imports/atom.py | atom.py | py | 884 | python | en | code | 7 | github-code | 1 |
8040886307 | filename = 'all_hist.txt'
leapremoved = 0
datastartyear=1970
dataendyear =2011
init_year=2000
init_month = 8
init_day = 1
periodstart_year = 2000
periodstart_month = 1
periodstart_day = 1
periodend_year = 2001
periodend_month = 12
periodend_day = 31
climstartyear = 1970
climendyear = 2009
leapinit = 1
climatological_me... | tamsat-alert/v1-0 | config.py | config.py | py | 431 | python | en | code | 2 | github-code | 1 |
75256444833 | class Solution(object):
def distributeCandies(self, candies, num_people):
"""
:type candies: int
:type num_people: int
:rtype: List[int]
"""
res = [0] * num_people
a = 0
count = 0
while a < num_people:
count += 1
if coun... | HawkinYap/Leetcode | leetcode1103.py | leetcode1103.py | py | 775 | python | en | code | 0 | github-code | 1 |
22611037359 | # coding: utf-8
import time
from admin.models import PaymentAccountInfo
from common.models import SalesManUser
from common.serializers import CommonNoticeSerializer
from coupon.models import UserCoupon
from rest_framework.response import Response
from rest_framework.views import APIView
from authentication.models impo... | liaochenghao/StuSystem | StuSystem/common/views.py | views.py | py | 4,855 | 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.