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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
2268055482 | # Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
#
# An input string is valid if:
#
# Open brackets must be closed by the same type of brackets.
# Open brackets must be closed in the correct order.
# Note that an empty string is also considered val... | pradepghr/my_leet_solutions | src/valid_parentheses.py | valid_parentheses.py | py | 1,812 | python | en | code | 0 | github-code | 36 |
72644993064 | import os
import unittest
from pathlib import Path
import numpy as np
from pkg_resources import resource_filename
from compliance_checker.acdd import ACDDBaseCheck
from compliance_checker.base import BaseCheck, GenericFile, Result
from compliance_checker.suite import CheckSuite
static_files = {
"2dim": resource_... | ioos/compliance-checker | compliance_checker/tests/test_suite.py | test_suite.py | py | 10,559 | python | en | code | 92 | github-code | 36 |
34955184359 |
import os
import gspread
from gplus import ClientPlus
from datetime import datetime
from oauth2client.service_account import ServiceAccountCredentials
from flask import Flask, render_template
application = Flask(__name__, static_url_path='/static')
CURRENT_DIR = os.... | CrabbyPete/coastalflyrodders | main.py | main.py | py | 2,877 | python | en | code | 0 | github-code | 36 |
26301777253 | from functools import reduce
from hashlib import md5
from jsonpath import jsonpath
from jsonpath_ng.parser import JsonPathParser
from tools.funclib import get_func_lib
import json
import re
import time
from tools.utils.utils import extract_by_jsonpath, quotation_marks
class Template:
def __init__(self, test, co... | Chras-fu/Liuma-engine | core/template.py | template.py | py | 12,092 | python | en | code | 116 | github-code | 36 |
20764888384 | from bs4 import BeautifulSoup
import csv
with open("carviewer2.html") as fp:
soup = BeautifulSoup(fp, 'html.parser')
employee_file = open('week02data.csv', mode='w')
employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
rows = soup.findAll("tr")
#print(ro... | eamonnofarrell/dataRepresentation | week03-webScraping/PY05-readFileFinal.py | PY05-readFileFinal.py | py | 602 | python | en | code | 0 | github-code | 36 |
2119785373 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
@FILE : Month6_general_analysis.py
@TIME : 2023/07/20 22:34:20
@AUTHOR : wangyu / NMC
@VERSION : 1.0
@DESC : 本文件负责进行 2023年 6 月 华北地区高温事件的基础统计分析
华北地区 6 月份高温事件集中在 6月14-17日, 6月21-30日
'''
### to import parent dir files ###
# import os, sy... | wangy1986/HB-HeatWave-Analysis | heatwave_general_analysis.py | heatwave_general_analysis.py | py | 5,896 | python | en | code | 0 | github-code | 36 |
6714176411 | """
Core config implementations.
"""
import importlib
import logging
import os
import sys
from collections import KeysView, ItemsView, ValuesView, Mapping
from .. import abc
from ..compat import text_type, string_types
from ..decoders import Decoder
from ..exceptions import ConfigError
from ..interpolation import Bas... | viniciuschiele/central | central/config/core.py | core.py | py | 30,318 | python | en | code | 3 | github-code | 36 |
35866755353 | import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Запуск парсера офисных документов."
def handle(self, *args, **options):
run_parser = subprocess.getoutput(
f'poetry run parser -r -p {settings.RESOUR... | Studio-Yandex-Practicum/adaptive_hockey_federation | adaptive_hockey_federation/core/management/commands/fill-db.py | fill-db.py | py | 574 | python | en | code | 2 | github-code | 36 |
35920582247 | from flask import Flask
from pymongo import MongoClient
import json
client = MongoClient()
db = client.devdb
collection = db.jobs
# reads json file, returns data as python dict
def load_data():
with open("./app/data.json", "r") as file:
data = json.load(file) # gets python dict
return data
# insert ... | shailstorm/joblistings | app/__init__.py | __init__.py | py | 627 | python | en | code | 0 | github-code | 36 |
28319118444 | # 认识什么是字符串
# python中的字符串,就是包含在一对单引号、双引号中的一堆字符
# python中特有的长字符串,包含在一对三引号中间的一堆字符
# 字符串:专门用来进行信息交互[展示信息、提示信息、交互信息]
title = "欢迎来到python神奇的世界"
print (title)
info = 'python是一种神秘的语言'
print(info)
# 字符串中,不可避免的有可能会出现引号【特殊的引号】
#单引号字符串中,可以直接使用双引号
#双引号字符串中,可以直接使用单引号
#单引号字符串中,要使用单引号请使用\转义;双引号也是一样
info2 = "python是一种'跨平台的'语言"
print(i... | laomu/py_1709 | python-base/days06_code/demo02_认识字符串.py | demo02_认识字符串.py | py | 1,637 | python | zh | code | 0 | github-code | 36 |
12441845301 | def gen_primes():
lst = []
for i in range(2, 100):
for k in range(2, i):
if i % k == 0:
break
else:
lst.append(i)
return lst
print(gen_primes())
| SmetanskaK/hw | task_30.py | task_30.py | py | 219 | python | en | code | 0 | github-code | 36 |
44481601561 | #! python3.11
# coding: utf8
""" Singleton metaclass """
__author__ = 'Sihir'
__copyright__ = '© Sihir 2021-2023 all rights reserved'
class Singleton(type):
""" metaclass for Singleton """
_instances = {} # a dictionary containing all instances
def __call__(cls, *args, **kwargs):
... | Pippin555/show_help | utils/singleton.py | singleton.py | py | 518 | python | en | code | 0 | github-code | 36 |
9163305742 | # A variable is a container for a value, which can be of various types
'''
This is a
multiline comment
or docstring (used to define a functions purpose)
can be single or double quotes
'''
"""
VARIABLE RULES:
- Variable names are case sensitive (name and NAME are different variables)
- Must start with a letter or... | techmynd/python | concepts/variables.py | variables.py | py | 1,128 | python | en | code | 0 | github-code | 36 |
11565125878 |
import keras
import morse
import numpy as np
import cwmodel
checkpoint_fn = "weights_detect.h5"
try:
from google.colab import drive
drive.mount('/content/drive')
checkpoint_fn = '/content/drive/MyDrive/Colab Notebooks/' + checkpoint_fn
except:
print("Couldn't mount Google Colab Drive")
model = cwmod... | sehugg/cwkeras | train_detect.py | train_detect.py | py | 1,183 | python | en | code | 1 | github-code | 36 |
23467111744 | import os
import io
import lmdb
import six
import cv2
from PIL import Image
IMAGE_SAMPLE_HEIGHT = 64
def image_bin_to_pil(image_bin):
buf = six.BytesIO()
buf.write(image_bin)
buf.seek(0)
img = Image.open(buf)
return img
def is_valid_label(label, classes):
for ch in label:
if classes... | gucheol/CreateLMDB | lmdb_helper.py | lmdb_helper.py | py | 6,254 | python | en | code | 0 | github-code | 36 |
3717849813 | from PySide2.QtWidgets import QWidget, QTableWidgetItem, QAbstractItemView, QHeaderView, QMessageBox
from Ventanas.agendar_vuelo import AgendarVuelo
from Database.aeropuerto import *
from Database.hangares_db import traer_todas_aerolineas
from PySide2.QtCore import Qt
import datetime
from datetime import datetime
from ... | SofhiAM/Aeropuerto_Campanero | Controles/agenda.py | agenda.py | py | 5,405 | python | es | code | 0 | github-code | 36 |
15969019025 | import torch.nn as nn
class MultiOutputCNN(nn.Module):
def __init__(self, ndigits, nvocab):
# inputsize 32*112
super(MultiOutputCNN, self).__init__()
feature_net = nn.Sequential()
def Conv_Relu(depth, ni, no, nk):
feature_net.add_module('layer_' + str(depth), nn.Conv2... | waitwaitforget/VerificationCodeRecognition | multiCNN.py | multiCNN.py | py | 1,279 | python | en | code | 0 | github-code | 36 |
23995852764 | from math import inf
import sys
import time
def sommeMin(t, n):
return sommeMinRec(t, n)
def sommeMinRec(t, i):
if i == 0:
return 0
opt = inf
for x in [1, 3, 5]:
if x <= i:
tmp = t[i] + sommeMinRec(t, i - x)
if tmp < opt:
opt = tmp
return... | Yuss9/TP1_ANALYSE_ALGO | src/probleme3/algo3.py | algo3.py | py | 1,664 | python | fr | code | 0 | github-code | 36 |
22509727291 | import re
import subprocess
import pygit2
from git_deps.utils import abort, standard_logger
from git_deps.gitutils import GitUtils
from git_deps.listener.base import DependencyListener
from git_deps.errors import InvalidCommitish
from git_deps.blame import blame_via_subprocess
class DependencyDetector(object):
... | aspiers/git-deps | git_deps/detector.py | detector.py | py | 15,150 | python | en | code | 291 | github-code | 36 |
38269425685 | import random
import matplotlib.pyplot as plt
import math
import numpy as np
import time
plt.style.use('ggplot')
mutation = True
elitism = False
mutationPorcentage = .90
tournamentPercentage = 0.02
generations = 100
nPopulation = 400
fuzzyNetworks = 7
chromosomeSize = fuzzyNetworks*4
weight = 5
pMain = [8,25,4,... | monzter50/fuzzy_ga | copy.py | copy.py | py | 9,520 | python | en | code | 1 | github-code | 36 |
43506629792 | #!/usr/bin/env python3
"""This modual contains the class created for task 0"""
class Poisson:
"""
This class Represents the poisson distribution.
Estimations used:
e = 2.7182818285
π = 3.1415926536
"""
def __init__(self, data=None, lambtha=1.):
if lambtha < 1:
... | chriswill88/holbertonschool-machine_learning | math/0x03-probability/poisson.py | poisson.py | py | 1,583 | python | en | code | 0 | github-code | 36 |
28779401751 | """
Black card
author: Manny egalli64@gmail.com
info: http://thisthread.blogspot.com/2017/01/codeeval-black-card.html
https://www.codeeval.com/open_challenges/222/
"""
import sys
def solution(line):
data = line.split(' | ')
players = data[0].split()
black = int(data[1]) - 1
while len(players) ... | egalli64/pythonesque | ce/c222.py | c222.py | py | 691 | python | en | code | 17 | github-code | 36 |
23862248439 | # -*- coding: utf-8 -*-
import csv
from .base import (SynDataDriver, FileConnMixin)
class Csv(SynDataDriver, FileConnMixin):
@property
def file_name(self):
return self.conn_str.split("/")[-1]
def get_records(self, query_template, **params):
try:
kwargs = dict(query_templ... | dan-win/fairways_py | fairways/io/syn/csv.py | csv.py | py | 1,567 | python | en | code | 0 | github-code | 36 |
4013445842 | # 문제 출처 : https://www.acmicpc.net/problem/10773
# 리스트를 돌며 새로운 배열에 숫자를 담는데 0일때는 마지막에 들어온 숫자를 지운다.
from sys import stdin
n = int(input())
p = list(map(int, stdin.read().split()))
new_list = []
result = 0
for i in range(len(p)):
if p[i] == 0:
new_list.pop()
else:
new_list.append(p[i])
result = s... | ThreeFive85/Algorithm | Algorithm_type/Stack/zero/zero.py | zero.py | py | 423 | python | ko | code | 1 | github-code | 36 |
12878610002 | number_grid= [
[1,2,3],
[4,5,6],
[7,8,9],
[0]
]
print(number_grid[0][0])
for row in number_grid: # afisare fiecare termen din matrice, cu doar primul for afisai randurile
for col in row:
print(col)
#translator (schimabre vocale cu un altul)
def translate (propozitie):
... | AnaMaghear/Python-Beginner | 2D List & Nested loops.py | 2D List & Nested loops.py | py | 786 | python | ro | code | 0 | github-code | 36 |
31590916957 | author = input()
points_academy = float(input())
number_evaluators = int(input())
current_score = 0
for i in range(1, number_evaluators+1):
name_evaluator = input()
points_evaluator = float(input())
length_name_evaluator = len(name_evaluator)
current_score = (length_name_evaluator * points_evaluator... | TeodorChakalov/Python | Python_Basics/For_Loop_Exercise/Oscars.py | Oscars.py | py | 648 | python | en | code | 0 | github-code | 36 |
21250532752 | # -*- coding:utf-8 -*-
# coding=utf-8
import os
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
# from skimage.transform import resize
import numpy as np
import cv2
# 膨胀算法 Kernel
_DILATE_KERNEL = np.array([[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
... | Tkwitty/watermark | Put_water_mark.py | Put_water_mark.py | py | 7,777 | python | en | code | 0 | github-code | 36 |
17257187558 | import tree_helpers
def inorder_traverse(tree_array):
stack = [tree_array[0]]
visited = []
while len(stack) > 0:
last_item = stack[0]
last_item_index = tree_array.index(last_item)
left_child = tree_helpers.left(tree_array, last_item_index)
if left_child is not None and left_... | abarciauskas-bgse/code_kata | tree_traversals/inorder_traverse.py | inorder_traverse.py | py | 632 | python | en | code | 1 | github-code | 36 |
4298322287 |
# 发送纯文本
# SMTP: 邮件传输协议
# 发邮件
import smtplib
# 邮件标题
from email.header import Header
# 邮件正文
from email.mime.text import MIMEText
"""
user, pwd, sender, receiver, content, title
用户名,授权码,发送方邮箱,接收方邮箱,内容,标题
"""
def sendEmail(user, pwd, sender, receiver, content, title):
# 163的SMTP服务器
mail_host = "smtp.163.com"
... | H-Gang/exercise | learn.py | learn.py | py | 1,978 | python | en | code | 0 | github-code | 36 |
13076610042 | import numpy as np
import pandas as pd
import matplotlib
from matplotlib import pyplot as plt
from matplotlib.ticker import AutoMinorLocator
# datafile from COMSOL
path_to_data = "E://COMSOL//laminar_mesh_refinement/"
# % Model: run40_lam_mesh_fluid_0.5_out.mph
# % Version: COMSO... | kromerh/phd_python | 03_COMSOL/02.rotatingTarget/old_py/COMSOL_new_target/mesh_refinement/mesh_refinement_fluid_T_along_z_at_beamspot.py | mesh_refinement_fluid_T_along_z_at_beamspot.py | py | 3,229 | python | en | code | 0 | github-code | 36 |
23411420670 | from django.conf.urls import url
from .import views
# from views import ClienteAutocomplete
urlpatterns = [
# url(r'^cliente-autocomplete/$', ClienteAutocomplete.as_view(), name='cliente-autocomplete'),
url(regex=r'^$', view=views.index, name='index'),
url(r'^cliente/(?P<cliente_id>\d+)/edit/$', views.clie... | pmmrpy/SIGB | clientes/urls.py | urls.py | py | 625 | python | en | code | 0 | github-code | 36 |
1372191329 | from onewire import OneWire
class DS18X20(object):
def __init__(self, pin):
self.ow = OneWire(pin)
# Scan the 1-wire devices, but only keep those which have the
# correct # first byte in their rom for a DS18x20 device.
self.roms = [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0... | jiapei100/uPyCraft_PyQt5 | examples/uPy_lib/ds18x20.py | ds18x20.py | py | 1,955 | python | en | code | 17 | github-code | 36 |
2663498928 | # -*- coding: utf-8 -*-
from Haier import Haier
from TCL import TCL
from Hisense import Hisense
from Television import Television
from Refrigeratory import Refrigeratory
from AirConditioner import AirConditioner
def start():
tv = Television()
frigeratory = Refrigeratory()
air = AirConditioner()
haie... | Tiierr/Design-Patterns | Python/bridge/sample01/main.py | main.py | py | 898 | python | en | code | 0 | github-code | 36 |
6379736623 | from functools import partial
import jax
import numpy as np
from tessellate_ipu import tile_map, tile_put_sharded
data = np.array([1, -2, 3], np.float32)
tiles = (0, 2, 5)
@partial(jax.jit, backend="ipu")
def compute_fn(input):
input = tile_put_sharded(input, tiles)
# input = tile_put_replicated(input, til... | graphcore-research/tessellate-ipu | examples/demo/demo1.py | demo1.py | py | 492 | python | en | code | 10 | github-code | 36 |
3637163420 | import cv2
from openvino.inference_engine.ie_api import IECore, IENetwork
import pprint
# default threshold
THRESHOLD = 0.5
class Face_Detection:
def __init__(self, model_name, device='CPU', extensions=None, perf_counts="False"):
self.model_weights = model_name + '.bin'
self.model_structure = mode... | alihussainia/Computer_Pointer_Controller | face_detection.py | face_detection.py | py | 2,813 | python | en | code | 0 | github-code | 36 |
43298458764 | from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
from pypy.module.cpyext.test.test_api import BaseApiTest
from rpython.rtyper.lltypesystem import rffi
class AppTestSysModule(AppTestCpythonExtensionBase):
def test_sysmodule(self):
module = self.import_extension('foo', [
... | mozillazg/pypy | pypy/module/cpyext/test/test_sysmodule.py | test_sysmodule.py | py | 1,414 | python | en | code | 430 | github-code | 36 |
40794410326 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
... | Devjyoti29/LeetHub | 0103-binary-tree-zigzag-level-order-traversal/0103-binary-tree-zigzag-level-order-traversal.py | 0103-binary-tree-zigzag-level-order-traversal.py | py | 1,286 | python | en | code | 0 | github-code | 36 |
38567859669 | '''
Input # A graph represented as an adjacency list and a starting vertex
Output # A string containing the vertices of the graph listed in the correct order of traversal
'''
adjList = {
0 : [1,2],
1 : [3,4],
2 : [],
3 : [],
4 : []
}
def dfs(source, paths):
if source == len(adjList)-1 ... | archanakalburgi/Algorithms | Graphs/traversalString.py | traversalString.py | py | 635 | python | en | code | 1 | github-code | 36 |
6667722703 | """empty message
Revision ID: 764dadce9dd1
Revises:
Create Date: 2017-09-28 01:16:36.519727
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '764dadce9dd1'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | ThreeOhSeven/Backend | migrations/versions/764dadce9dd1_.py | 764dadce9dd1_.py | py | 1,289 | python | en | code | 0 | github-code | 36 |
38092916023 | from ._convert import ToPandas, pandas_params
from ._debug import Dump, Dumpable, PandasCSVDumper, Sniff
from ._generic import Apply, MapReduce, PandasConcat, PandasDrop, PandasSelect
from ._split import CrossValidable, CVFoldable, PandasCVFolds
__all__ = [
'Apply',
'CrossValidable',
'CVFoldable',
'Dum... | formlio/forml | forml/pipeline/payload/__init__.py | __init__.py | py | 511 | python | en | code | 103 | github-code | 36 |
27207422081 | # Game Settings
import random
import os
#set directories
game_Folder = os.path.dirname(__file__)
assets_Folder = os.path.join(game_Folder, "assets")
img_Folder = os.path.join(assets_Folder, "imgs")
audio_Folder = os.path.join(assets_Folder, "audio")
print(img_Folder)
#High score file
HS_FILE = "highscore.txt"
#Spri... | jordendickerson/Python-Portfolio-Jorden-D | Platformer/settings.py | settings.py | py | 1,346 | python | en | code | 0 | github-code | 36 |
34912332593 | import serial
import time
"Arduino Controller Object"
class Arduino_Controller(object):
def __init__(self, path):
self.path = path
self.arduino = serial.Serial(self.path, 9600, timeout = 5)
self.nums = "0123456789"
self.angle = 0
self.is_Button_Pressed = False
"Arduino ... | rviccina/Space-Defense | Arduino_Controller_Class.py | Arduino_Controller_Class.py | py | 1,135 | python | en | code | 0 | github-code | 36 |
73137746664 | from django import forms
from .models import Submission, Dataset, Method
class SubmitForm(forms.Form):
def __init__(self,data=None,*args,**kwargs):
def conv(private):
if private:
return " (private Leaderboard)"
else:
return " (public Leaderboard)"
... | bcm-uga/ChallengeWebSite | challenge/forms.py | forms.py | py | 1,147 | python | en | code | 0 | github-code | 36 |
33066890373 | class Polynomial:
def __init__(self, n, k=None):
self.degree = n
if k is None:
self.koef = [0 for i in range(n + 1)]
else:
if len(k) > n:
k = k[:n + 1]
self.koef = [x for x in k]
def __imul__(self, other):
for i in range(len(se... | Xatabch/iu7_algorithms | lab_06/polynom.py | polynom.py | py | 1,324 | python | en | code | 0 | github-code | 36 |
73192378344 | #coding:UTF-8
#import simplegui
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
import random
# helper function to start and restart the game
def new_game(num_range):
print ("新一轮游戏")
global secret_number
global limit_step
if (num_range == RANGE100):
secret_number = random.randi... | csufuyi/mooc.py | src/iippy-1/GuessNumber.py | GuessNumber.py | py | 2,092 | python | en | code | 0 | github-code | 36 |
22192896243 | from telegram import Bot
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
bot = Bot(token='5593423447:AAEe0rCZnZdYXNpxxyatR37l6afSppj-yZI')
updater = Updater(token='5593423447:AAEe0rCZnZdYXNpxxyatR37l6afSppj-yZI')
dispatcher = updater.dispatcher
def start(update, context):
context.bot.se... | Minions-Wave/GB-Minions-Wave | The Big Brain Solutions/Personal Zone/NighTramp Solutions/Blok 2/Python/HomeWork/Seminar009/main.py | main.py | py | 1,271 | python | en | code | 2 | github-code | 36 |
7004126038 | # compare list
# ==, is
fruits1 = ['apple', 'banana', 'orange' ]
fruits2 = ['pear', 'kiwi', 'apple', 'banana']
fruits3 = ['apple', 'banana', 'orange' ]
# print(fruits1 == fruits2) # gives False
print(fruits1 == fruits3) # gives True (because values are same)
print(fruits1 is fruits3) # it check same memory loc... | salmansaifi04/python | chapter5(list)/07_list_compare_(in_vs_equal).py | 07_list_compare_(in_vs_equal).py | py | 339 | python | en | code | 0 | github-code | 36 |
3320859772 | import scrapy
import json
import csv
from ..items import FoodyItem
OUTPUT_DIRECTORY = "/Users/user/Desktop/Crawl/foody/OUTPUT/foody_output.json"
class CrawlfoodySpider(scrapy.Spider):
name = 'crawlFoody'
allowed_domains = ['www.foody.vn']
total_comment = 0
num_of_page = 1
url = 'https://www.food... | LENGHIA-CN8/FoodyCrawl | foody/spiders/crawlFoody.py | crawlFoody.py | py | 4,850 | python | en | code | 0 | github-code | 36 |
44542833866 | # This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
import requests
import scrapy
api_endpoint = 'http://localhost:5000/api/domains'
class QuotesSpider(scrapy.Spider):
name = "quotes"
def start_requ... | imfht/sec-flask-cookiecutter | spider/spider/spiders/__init__.py | __init__.py | py | 790 | python | en | code | 0 | github-code | 36 |
16371835834 | from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflow.hooks.postgres_hook import PostgresHook
from warnings import warn
class CheckFutureYearsOperator(BaseOperator):
"""
Checks number of observations in Postgres table with a year in the future
:param... | davidrubinger/political-contributions-canada | plugins/operators/check_future_years_operator.py | check_future_years_operator.py | py | 1,496 | python | en | code | 0 | github-code | 36 |
35575503668 | """Miscellaneous functions used for plotting gradient data"""
import gzip
import math
import os.path as op
import pickle
import nibabel as nib
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
from neuromaps.datasets import fetch_fslr
from nilearn import image, masking, plotting
from nilear... | NBCLab/gradient-decoding | figures/utils.py | utils.py | py | 10,146 | python | en | code | 0 | github-code | 36 |
73161250024 | from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.exceptions import ResponseValidationError
from app.crud import users_dao
from app.schemas import UserBase
from sqlalchemy.orm import Session
from ..database import get_db
router = APIRouter()
@router.get("/{cbu}", response_model=UserBase)
de... | FelipeCupito/DB2-TP | backendBanks/app/routers/users.py | users.py | py | 1,315 | python | en | code | 0 | github-code | 36 |
23408765544 | # -*- coding: utf-8 -*-
from sqlalchemy import Table, Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy_mate import EngineCreator, ExtendedBase
from sfm import rnd
import random
engine = EngineCreator(
host="rajje.db... | MacHu-GWU/Dev-Exp-Share | docs/source/01-AWS/01-All-AWS-Services-Root/31-Migration-and-Transfer/02-Database-Migration-Service-(DMS)-Root/Practice-Postgres-to-AWS-RDS/source_database.py | source_database.py | py | 1,468 | python | en | code | 3 | github-code | 36 |
32860658892 | # rsa key generation module
import random
"""
Note: ea_gcd and eea_gcd should return a SINGLE VALUE
the greatest common divisor of two number a and b
"""
def gen_key(p, q):
"""
Implement rsa key generation, public and private key
p, q are prime numbers less than 10,000
((d,n), (e,n)) is a tupl... | richardjamolodmagsalayjr/RSA-decryption | key_generation.py | key_generation.py | py | 1,617 | python | en | code | 0 | github-code | 36 |
9624083818 | from boto3.session import Session
session = Session(aws_access_key_id='[your_key_id]', aws_secret_access_key='[your_secret_key]')
def shutdown_all(resource_name,region):
resource = session.resource(resource_name, region_name=region)
instances = resource.instances.filter(
Filters=[{'Values': ['running'... | tiago-clementino/desafioDevOps | ops/scripts/q1.py | q1.py | py | 411 | python | en | code | 0 | github-code | 36 |
23073952009 | from webapp import app
import os
from flask import render_template, url_for, flash, redirect, request, abort
from webapp.models import Video
from os import path
from sqlalchemy.sql import text
@app.route("/")
@app.route("/home")
def home():
page = request.args.get('page', 1, type=int)
videos = Video.query.orde... | sheikhhanif/cslesson | webapp/routes.py | routes.py | py | 2,179 | python | en | code | 0 | github-code | 36 |
978437268 | import torch
from torch import nn
import numpy as np
import torch.nn.functional as F
def inverse_sigmoid(epoch, k=20):
return k / (k + np.exp(epoch/k))
class Encoder(nn.Module):
def __init__(self, input_size, hidden_size, latent_dim, num_layers=1, bidirectional=True):
super(Encoder,... | Jinhoss/MusicVAE | model.py | model.py | py | 6,869 | python | en | code | 0 | github-code | 36 |
19557411940 | import sys
from collections import deque
input = sys.stdin.readline
t = int(input())
for _ in range(t):
l = int(input())
n_x, n_y = map(int, input().split())
m_x, m_y = map(int, input().split())
visited = [[0] * l for _ in range(l)]
visited[n_x][n_y] = 1
dq = deque([(n_x, n_y)])
while dq:
... | hyotaime/PS.py | Silver/Silver1/7562.py | 7562.py | py | 722 | python | en | code | 0 | github-code | 36 |
4255502864 | from unittest import TestCase, main
from leet.rotate_image.main import Solution
s = Solution()
class TestSuite(TestCase):
def test_1(self):
image = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
s.rotate(image)
expected = [
[7, 4, 1],
... | blhwong/algos_py | leet/rotate_image/test.py | test.py | py | 824 | python | en | code | 0 | github-code | 36 |
505960290 | """
Querying by location and extract data location
"""
def places_by_query(bfShp, epsgIn, keyword=None, epsgOut=4326,
_limit='100', onlySearchAreaContained=True):
"""
Get absolute location of facebook data using the Facebook API and
Pandas to validate data.
Works only for the ... | jasp382/glass | glass/acq/dsn/fb/places.py | places.py | py | 4,253 | python | en | code | 2 | github-code | 36 |
15566377203 | # complete k-means++
from copy import deepcopy
import matplotlib.pyplot as plt
import numpy as np
#load data
data = np.loadtxt('Downloads/mnist_small.txt')
#normalize the data
data=np.divide(data,16)
#distance function
def dist(a, b, ax=1):
return np.linalg.norm(b - a, axis=ax)
#20 iterations
for k in range(20):
... | lizihao1999/k-means | k-means++.py | k-means++.py | py | 1,688 | python | en | code | 0 | github-code | 36 |
7116656902 | ##Richard Weaver
##01/03/2022
# Function to reformat a string based on specified character length.
def text_to_lines (text, max_length):
total_count= 0
output_text = ""
space = " "
word_list = text.split()
# For Loop iterating over each word in list
for word in word_list:
# print(word)... | weaverfish111/Python_Training_Official | reformatting.py | reformatting.py | py | 1,128 | python | en | code | 0 | github-code | 36 |
39510454656 | from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
def ngram_array(a_text, s_text, n):
'''
Calculate an ngram array for an answer and source text
Arguments:
a_text: answer text
s_text: source text
n : choice of n-gram (1 == unigram, 2 == bigram e... | tonyjward/plagiarism_detection | src/utils/create_features.py | create_features.py | py | 6,006 | python | en | code | 7 | github-code | 36 |
17581795142 | import urllib
from typing import Any, Optional
from functools import lru_cache
import requests
from starwhale.utils.retry import http_retry
from starwhale.base.uri.instance import Instance
from starwhale.base.uri.exceptions import UriTooShortException
class Project:
id: str
name: str
instance: Instance
... | star-whale/starwhale | client/starwhale/base/uri/project.py | project.py | py | 4,147 | python | en | code | 171 | github-code | 36 |
27467144269 | #retorna se é par
def eh_par(n):
if n % 2 == 0:
return True
else:
return False
#entra como string
numero = input('digite o numero: ')
#converte para inteiro
numero = int(numero)
if eh_par(numero):
print (f'{numero} é par')
else:
print (f'{numero} é impar') | GiulianeEC/praticas_python | modulo02/matematica.py | matematica.py | py | 294 | python | pt | code | 0 | github-code | 36 |
8560169917 | import matrika
import Naloga2
def Minstopnja(mat):
min = len(mat)
for i in range(len(mat)):
m = len(Naloga2.Sosede(mat, i))
if m < min:
min = m
return min
def Maxstopnja(mat):
max = 0
for i in range(len(mat)):
M = len(Naloga2.Sosede(mat, i))
if M > max:
... | TheJim123/OPDM-vaje | Vaje2/Naloga3.py | Naloga3.py | py | 738 | python | en | code | 0 | github-code | 36 |
6382383579 | # -*- coding: UTF-8 -*-
# by:Caiqiancheng
# Date:2022/9/16
from bin.Generation_cmd import generation
from bin.Generation_gui import generation_ui
from src.common import read_config
def get_start_mode():
"""
从配置文件获取启动方式
:return: cmd or gui
"""
start_mode = read_config("start").get("mode")
ret... | Ciciy-l/Schedule-Generator | main.py | main.py | py | 501 | python | en | code | 1 | github-code | 36 |
72968145703 | from settings import *
class Sound:
path = 'sound/'
def __init__(self, game, btn_name) -> None:
self.game = game
self.mixer = self.game.pg.mixer
self.mixer.init()
self.file = self.mixer.Sound(self.path + f'{btn_name}.wav')
def play_sound(self):
self.file.play()
... | h4sski-programming/Memory_pygame_001 | sound.py | sound.py | py | 365 | python | en | code | 0 | github-code | 36 |
4013763262 | # 문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/12906
def solution(arr):
answer = []
for i in range(len(arr)):
if len(answer) == 0:
answer.append(arr[i])
elif answer[-1] == arr[i]:
continue
else:
answer.append(arr[i])
return answer
#... | ThreeFive85/Algorithm | Programmers/level1/noRepeatNumbers/norepeat_numbers.py | norepeat_numbers.py | py | 511 | python | en | code | 1 | github-code | 36 |
257207853 | import sys
def main():
nb = int(input())
arr = list(map(int, input().split()))
_u = set(arr)
arr.sort()
_arr = []
for i in range(nb):
el = arr[i]
if el >= 0:
break
if abs(el) in _u and not(abs(el) in _arr):
_arr.append(abs(el))
print(... | SlicedPotatoes/France_IOI | Niveau 3/11 – Exercices d'entraînement du niveau 3/07 - Nombres opposés.py | 07 - Nombres opposés.py | py | 337 | python | en | code | 0 | github-code | 36 |
34434107143 | ## creating functions to write the output word file
import pandas as pd
def get_paragraph(paras, text):
"""Return the paragraph where the text resides
Args:
paras(document.paragraphs): All the paragraphs in the document
text (str): The text in the paragraph to match
... | LoSpiri/Cisco-Data-Retrieve-Automation | bookwriting.py | bookwriting.py | py | 1,744 | python | en | code | 0 | github-code | 36 |
570167896 | import logging
import math
from .geomsmesh import geompy
from .geomsmesh import smesh
from .putName import putName
def calculePointsAxiauxPipe_a(facesDefaut, centreFondFiss, wireFondFiss, \
lenSegPipe, \
nro_cas=None):
"""Maillage selon le rayon de courbu... | luzpaz/occ-smesh | src/Tools/blocFissure/gmu/calculePointsAxiauxPipe_a.py | calculePointsAxiauxPipe_a.py | py | 1,651 | python | en | code | 2 | github-code | 36 |
36458063236 | import abc
import json
from typing import Any, Dict, List, NoReturn, Optional, Tuple, Union, final
from erniebot_agent.agents.base import BaseAgent
from erniebot_agent.agents.callback.callback_manager import CallbackManager
from erniebot_agent.agents.callback.default import get_default_callbacks
from erniebot_agent.ag... | Southpika/ERNIE-Bot-SDK | erniebot-agent/src/erniebot_agent/agents/agent.py | agent.py | py | 9,943 | python | en | code | null | github-code | 36 |
39274786289 | import re
# from urllib.parse import urlparse
# from urllib.parse import urljoin
# from urllib.parse import urldefrag
import urllib
import time
from datetime import datetime
from urllib.robotparser import RobotFileParser
import queue
import random
import socket
import csv
import lxml.html
DEFAULT_AGENT = 'wswp'
DEFAU... | Code-In-Action/python-in-action | webscrap/c1.py | c1.py | py | 7,304 | python | en | code | 0 | github-code | 36 |
3093608476 | # Write a program that rounds all the given numbers, separated by a single space,
# and prints the result as a list. Use round().
num = input()
def rounding_func(a):
num1 = num.split(" ")
num_list = []
for x in num1:
z = float(x)
z = round(z)
num_list.append(z)
return num_list
pr... | ivn-svn/SoftUniPythonPath | Programming Fundamentals with Python/4_functions/lab/7_rounding.py | 7_rounding.py | py | 343 | python | en | code | 1 | github-code | 36 |
14783345102 |
# Built-In Python
import time
from pathlib import Path
import pickle
import random
import logging
# Third-Party
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tqdm import tqdm
from fire import Fire
# Custom
from .population import Population
from .flips import Flips, Flip
class History... | ryanlague/thePerfectlyJustSociety | thePerfectlyJustSociety/coinFlip/coinFlip.py | coinFlip.py | py | 9,029 | python | en | code | 0 | github-code | 36 |
8356155101 |
import re
import cv2
import numpy as np
import matplotlib.pyplot as plt
flat_chess=cv2.imread('DATA/flat_chessboard.png')
flat_chess=cv2.cvtColor(flat_chess,cv2.COLOR_BGR2RGB)
plt.subplot(321)
plt.imshow(flat_chess)
gray_flat_chess=cv2.cvtColor(flat_chess,cv2.COLOR_BGR2GRAY)
plt.subplot(322)
plt.imshow(gray_flat_c... | janezv/computerVision | plt.subplot.py | plt.subplot.py | py | 1,350 | python | en | code | 0 | github-code | 36 |
13988017107 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from skfmm import travel_time, distance
from scipy.interpolate import interp1d
import os
from utils import plot_2d_image
from math import log10
plt.style.use('ggplot')
def transform_normal_scores(scores, nscore):
# for now, the values of our s... | wsavran/sokrg | generate_scale_truncated.py | generate_scale_truncated.py | py | 12,819 | python | en | code | 3 | github-code | 36 |
5832039173 | import requests
from bs4 import BeautifulSoup
from datetime import datetime
from pymongo import MongoClient
client = MongoClient(port=27017)
db = client.historical_data4
def get_coins(url):
"""this function get all coins list"""
response = requests.get(url)
coin_list = [i['id'] for i in response.json()]
... | ShivaGuntuku/cryptos | coin_historical_data_with_mongodb.py | coin_historical_data_with_mongodb.py | py | 1,407 | python | en | code | 1 | github-code | 36 |
12894335645 | import pygame
import random
class boss(pygame.sprite.Sprite):
def __init__(self, game):
super().__init__()
self.game = game
self.health = 350
self.max_health = 350
self.attack = 6
self.image = pygame.image.load('assets/BOSS T.png')
self.image = pygame.transf... | MathieuTherias/Projet-Transverse | BOSS.py | BOSS.py | py | 1,440 | python | en | code | 0 | github-code | 36 |
41979414512 | import questionary
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from BrokerManager import server as broker_manager
from BrokerManagerReadOnly import server as broker_manager_readonly
import sys
def create_app():
app = Flask(__name__)
answer = questionary.select(
"Which Server do you want to st... | DistributedSystemsGroup-IITKGP/Assignment-3 | main.py | main.py | py | 754 | python | en | code | 0 | github-code | 36 |
43131538981 | import socket
import requests
import re
from urllib.parse import quote
# gopher利用脚本,此脚本内容可以任意的修改
#
# 最新测试版本
CRLF = '\r\n'
# redis_format函数用于进行redis的RESP协议的格式化
def redis_format(command):
cmd = []
data = command.split('\n')
for x in data:
if re.match(r'\s*',x):
data.remove(x)
cmd... | melody27/python_script | socket/gopher_payload.py | gopher_payload.py | py | 2,502 | python | en | code | 0 | github-code | 36 |
6609936224 | def total_shopping_card_change(shopping_list, cash):
total = 0
for x in shopping_list:
y = str(x[1])
pos = x[0] + "(" + y + ")"
print(pos,"x", x[2], " ", x[1]*x[2])
total += x[1]*x[2]
print("Do zapłaty", total )
print("Zapłacono", cash )
print("Reszta", cash - total ... | piotrm2/ProsteZadanka | exercise_17.py | exercise_17.py | py | 809 | python | pl | code | null | github-code | 36 |
11755542906 | from os import environ, listdir
from os.path import join, isfile, getmtime
from dataclasses import dataclass, field
import json
import time
import traceback
from datetime import datetime,timezone
savedGamePath = environ['USERPROFILE'] + "\Saved Games\Frontier Developments\Elite Dangerous"
@dataclass
class mission:
... | Matrixchung/EDAutopilot-v2 | utils/journal.py | journal.py | py | 10,593 | python | en | code | 42 | github-code | 36 |
4513885534 | n = int(input("Введите количество монеток: "))
coins = input("Введите состояние монеток (орел - 1, решка - 0): ")
count_heads = 0
count_tails = 0
for i in coins:
if i == '1':
count_tails += 1
else:
count_heads += 1
print(min(count_heads, count_tails)) | KronosHronos/pythone-2 | pythone/task10.py | task10.py | py | 340 | python | en | code | 0 | github-code | 36 |
21764487003 | from .auth_exception import *
from .authenticator import *
# import auth_exception
class Authorizer:
def __init__(self, authenticators):
self.authenticator = authenticator
self.permissions = {}
def add_permission(self, perm_name):
# Create a new permission that users can be added to
... | wangqian0613/python_test | exception_test/auth_lib/authorizer.py | authorizer.py | py | 1,453 | python | en | code | 0 | github-code | 36 |
8231955014 | """Client library for sending events to the data processing system.
This is for use with the event collector system. Events generally track
something that happens in production that we want to instrument for planning
and analytical purposes.
Events are serialized and put onto a message queue on the same server. These... | Omosofe/baseplate | baseplate/events/queue.py | queue.py | py | 4,735 | python | en | code | null | github-code | 36 |
33943744293 | import asyncio
import atexit
import dataclasses
import multiprocessing
import time
from typing import Any, Dict
from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher... | i026e/tg_filtering_bot | tg_filtering_bot/bot/filtering_bot.py | filtering_bot.py | py | 10,642 | python | en | code | 0 | github-code | 36 |
71411435305 | from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from traceback import format_exc
POOL_RESET_PERIOD = 10000
POOL_TASK_CHUNK = 1000
class PoolError(Exception):
pass
def process_in_pool(handler, task_iterator, thread_pool=False,
pool_reset_period=POOL_RESET_PERIOD,
... | baradhiren/libgen_telegram_bot | venv/Lib/site-packages/weblib/pool.py | pool.py | py | 1,300 | python | en | code | 2 | github-code | 36 |
35376021408 | import pandas as pd
import numpy as np
import streamlit as st
import plotly.express as px
from sklearn.datasets import fetch_california_housing
from sklearn.metrics import mean_squared_error
def main(verbosity=False):
cal_housing = fetch_california_housing()
df = pd.DataFrame(cal_housing.data, columns... | Wratch/TYBootcamp | youdo1.py | youdo1.py | py | 1,784 | python | en | code | 0 | github-code | 36 |
70847780583 | from setuptools import setup
import os
import sys
import codecs
here = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
# intentionally *not* adding an encoding option to open
return codecs.open(os.path.join(here, *parts), 'r').read()
install_requires = [
"virtualenv==15.1.0",
"requests... | cloudify-cosmo/cloudify-agent-packager | setup.py | setup.py | py | 981 | python | en | code | 1 | github-code | 36 |
38118890596 | import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
x = np.linspace(0,2,201)
y = np.linspace(0,1,101)
xy, yx = np.meshgrid(x,y)
ims = []
tmin, tmax = 0, 0.02
h = 1e-3
fig = plt.figure()
for i in range(int(np.ceil((tmax-tmin)/h))):
plt.pcolormesh(xy,yx,np.sin(xy+np.pi*i*h)+np.c... | arnemagnus/_oldversion_physicsproject | calculation_scripts/old_assorted_test_scripts/testmatplotliblive.py | testmatplotliblive.py | py | 420 | python | en | code | 0 | github-code | 36 |
10849889917 | import os
import datetime
from jira import JIRA
class JiraIssueReporterHandler(object):
def __init__(self, jiraURL, username, api_token, projectKey):
self.options = {'server': jiraURL}
# self.server = jiraURL
self.auth = (username, api_token)
self.projectKey = projectKey
#... | gravity239/PySeleFramework | selenpy/common/jira_issue_reporter_handler.py | jira_issue_reporter_handler.py | py | 2,100 | python | en | code | 0 | github-code | 36 |
41908721379 | from django.http import JsonResponse
from django.shortcuts import render
from .models import Userdata,Entry
from django.shortcuts import render,HttpResponse,HttpResponseRedirect
# Create your views here.
# def check(request):
# return render(request,'check.html')
# def save(request):
# if request.method == 'PO... | Farheen-14/Crud-Operations | ajaxproject/ajaxapp2/views.py | views.py | py | 2,874 | python | en | code | 0 | github-code | 36 |
29344342096 | import matplotlib
from matplotlib import pyplot as plt
import numpy as np
import cv2 as cv
import IO
import api
# >>> Przykładowe zadanie i proces wykonania na podstawie zestawu Artroom2 <<<
# Korzystając z metody StereoSGBM udostępnionej przez bibliotekę OpenCV wyznacz mapę rozbieżności oraz mapę głębi.
# Dobierz od... | SmartMaatt/How-to-Zaowr | Zad2.py | Zad2.py | py | 2,635 | python | pl | code | 6 | github-code | 36 |
36819201120 | # type: ignore
from functools import cached_property
from dataclasses import dataclass, field
from pathlib import Path
@dataclass
class File:
path: Path
size: int
@dataclass
class Dir:
path: Path
files: list[File] = field(repr=False, default_factory=list)
dirs: list["Dir"] = field(repr=False, de... | ocaballeror/adventofcode2022 | 07/day7.py | day7.py | py | 1,442 | python | en | code | 0 | github-code | 36 |
13397438206 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 1 11:47:13 2022
@author: noise
neural network plot utilitiy functions
"""
import matplotlib.pyplot as plt
import numpy as np
import os
from mpl_toolkits.axes_grid1 import make_axes_locatable
def plotFullFields(Enn,Etest, epoch,i, dir):
i... | demroz/pinn-ms | optimizeNeuralNetwork/plotUtil.py | plotUtil.py | py | 1,787 | python | en | code | 5 | github-code | 36 |
18690414084 | import math
import numpy as np
import csv
from itertools import chain
import random
Feature_number=4
all_Feature=False
CUS_NUMBER=50
Training_number=50
count_setosa = 0
count_versicolor = 0
count_virginica = 0
k=0
l=40
fold = []
Output = []
variance = []
h =np.array([0.01,0.5,10])
confussion_matrix = [[0] * 3] * 3... | mmSohan/IrisDataSet_Classification_GaussianMultivariant-ParzenWindow_MachineLearning | parzen_window.py | parzen_window.py | py | 20,987 | python | en | code | 0 | github-code | 36 |
29648505683 | #! /usr/bin/env python3
# pylint: disable=missing-module-docstring,missing-function-docstring
from . import std_headers
from .utils import Object
def customHeaderIdentificationHandler(header):
"""
A couple of headers don't fit into the target identification heuristics
we have implemented in CppSourceDeps... | mohitmv/depg | default_configs.py | default_configs.py | py | 2,600 | python | en | code | 0 | github-code | 36 |
17887416810 | from django.shortcuts import render, redirect
from .models import Reply
from review.models import Review
from .forms import ReplyForm
from django.contrib import messages
from django.core.exceptions import PermissionDenied
def Reply(request, pk):
""" Model for staff to reply to user reviews on menu """
review ... | Code-Institute-Submissions/yuyizhong-O.A.T-Vietnamese-Cuisine | reply/views.py | views.py | py | 1,090 | python | en | code | 0 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.