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
8320514544
#!/usr/bin/env python # coding: utf-8 # In[2]: from pandas import DataFrame, read_csv, concat from keras.models import Sequential from keras.layers import Dense, Dropout, LSTM, Bidirectional, GRU,ConvLSTM2D, Flatten from matplotlib import pyplot as plt from numpy import concatenate, reshape, array from sklearn.metri...
TandonAnanya/Crypto-Trend-Prediction
Multiple Models/LSTM-multiple-datasets.py
LSTM-multiple-datasets.py
py
7,187
python
en
code
1
github-code
13
34745597648
import numpy as np import matplotlib.pylab as plt import matplotlib.gridspec as gridspec class FCM: def __init__(self, data, number_of_clusters=2, m=2, error = 0.01, random_state = 42, max_ind=150): self.number_of_clusters = number_of_clusters self.data = data.to_numpy().astype(np.float32) ...
arashHarirpoosh/UniversityProjects
ComputationalIntelligence/3.FCM/Clustering/FCM_C_Means.py
FCM_C_Means.py
py
8,264
python
en
code
0
github-code
13
38251350802
##################################### base_views ####################################################### from django.shortcuts import render, get_object_or_404 from ..models import Question from django.core.paginator import Paginator from django.db.models import Q def index(request) : # order_by('-create_da...
johnpark144/Practical_Study
Python_django/(FBV)파이보게시판 핵심/장고/base_views.py
base_views.py
py
8,223
python
en
code
3
github-code
13
37419661985
# 复原IP地址, 比较蛋疼, 用python class Solution(object): def valid(self, s): if len(s) == 1: return 0 <= int(s) elif len(s) == 2: return s[0] != '0' and 0 <= int(s) elif len(s) == 3: return s[0] != '0' and 0 <= int(s) <= 255 else: return False ...
butflame/LeetcodePractice
bytedance/string/RestoreIPAddresses.py
RestoreIPAddresses.py
py
1,001
python
en
code
0
github-code
13
36554202903
import os import json #import helper functions for lmnft import launchmynft def getConfig(): configFile = open("config.json", 'r') return list(json.load(configFile).values()) #gets config config = getConfig() #if windows True, else False (mac, linux) isWindows = True if os.name == 'nt' else Fals...
hankok16/LounchMyNFT-minting-bot
main.py
main.py
py
536
python
en
code
null
github-code
13
17062005794
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class ZhimaCreditEpSceneTradeConsultModel(object): def __init__(self): self._apply_amount = None self._biz_ext_param = None self._customer_rating_no = None self._out_ord...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/ZhimaCreditEpSceneTradeConsultModel.py
ZhimaCreditEpSceneTradeConsultModel.py
py
3,178
python
en
code
241
github-code
13
70148194257
import json import logging import requests from flask import abort from flask import request, Response, jsonify from marshmallow import ValidationError from util.sensitive_words_blocking.words_blocking import DFA from db.user import User from db import db def get_context(data_required=True): """ 获取用户的 open_...
NJU-uFFFD/DDLChecker
backend/src/routes/utils.py
utils.py
py
2,192
python
en
code
5
github-code
13
74262079056
import pprint import re def getLines(path): f = open(path) lines = f.read().splitlines() f.close() return lines def getRuleDict(input): rules = [x.split('bags contain') for x in input] ruleDict = {} for rule in rules: ruleDict[rule[0].strip()] = [x.strip().split(' ')[1] + " " + x.s...
jakobfje/advent-of-code
python/2020/07.py
07.py
py
2,796
python
en
code
0
github-code
13
22518103114
import requests import pandas as pd import sqlite3 from products import Products from user import User def create_product_objects(): valid_response = requests.get('https://fakestoreapi.com/products', verify = False) data2 = valid_response.json() df = pd.DataFrame(data2) with sqlite3.connect...
helloaseem/billing_system
main_project.py
main_project.py
py
3,849
python
en
code
0
github-code
13
22467469333
""" Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. Проверьте его работу на данных, вводимых пользователем. При вводе пользователем нуля в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой. """ def input_float(message: str) -> float: ""...
slavaprotogor/python_base
homeworks/lesson8/task2.py
task2.py
py
2,609
python
ru
code
0
github-code
13
18899092679
import os , requests import discord from discord.ext import commands from dotenv import load_dotenv import Cache local_cache = {} # stores name : cache object with users cached values NUM_OF_REQUEST = 0 players = [ 'roooge', 'molgera12', 'newtronimus', 'kayj0' ] # v5 api uses continental names whil...
firozt/DiscordBot
Lstater/src/bot.py
bot.py
py
8,188
python
en
code
0
github-code
13
3065271170
"""TnT (Train and Test) functions""" from experiment_params import Parameters from typing import Callable, Dict, Union import torch from torch import nn from torch import optim from torch.optim import lr_scheduler from torch.utils.data import DataLoader from networks import SmallNetwork, BigNetwork from tqdm import...
OsvaldFrisk/dp-not-all-noise-is-equal
src/tnt.py
tnt.py
py
4,118
python
en
code
0
github-code
13
38546199012
import os import os.path as osp import logging from tqdm import tqdm import pandas as pd import numpy as np import xml.etree.ElementTree as ET from utils import Center log = logging.getLogger(__name__) def load_xml(xml_path, frame_names=None, frame_dir=None): if frame_names is None: assert 0, 'frames_nam...
nttcom/WASB-SBDT
src/datasets/soccer.py
soccer.py
py
12,974
python
en
code
0
github-code
13
30938486379
def calculator(altitudeinput): from math import exp import numpy as np def isa(pressure,temperature,walk,a): R = 287 # [J/kgK] g0 = 9.80665 # [m/s2] temperatureend = temperature + a*walk if a ==0: pressureend = pressure * exp(g0 * walk / (-R * temper...
iamlucasvieira/ISA-Altitude
functionISA.py
functionISA.py
py
1,140
python
en
code
0
github-code
13
29752239316
from tkinter import * import cv2 from PIL import Image root = Tk() root.title("Ventana") root.config(bg="skyblue") left_frame = Frame(root, width=200, height=400) left_frame.grid(row = 0, column = 0, padx = 10, pady = 5) right_frame = Frame(root, width=650, height=400, bg='grey') right_frame.grid(row = 0, column = 1, ...
FranH20/GUI-Python
readhuli.py
readhuli.py
py
1,331
python
en
code
0
github-code
13
3928742530
import os import sys import inspect current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parent_dir = os.path.dirname(current_dir) sys.path.insert(0, parent_dir) import crawler as crawler def find_gen(baseSettings, tests): for i, test in enumerate(tests): settings = baseS...
b2aff6009/crawler
tests/testutils.py
testutils.py
py
3,048
python
en
code
0
github-code
13
21161016845
""" Dette programmet skal uttføre "tokenisering", dvs bryte opp en tekst opp i ord. Tokenisering er nødvendig utgangspunkt for de aller fleste språkteknologiske oppgaver. - dev.txt skal ligge i samme mappe. - Programmet er laget for python 3 For å kjøre programmet: obliga_steinrr.py """ # encoding: utf-8 class rea...
rayruu/inf1820
1a/oblig1a_steinrr.py
oblig1a_steinrr.py
py
4,195
python
en
code
0
github-code
13
31238910959
def homework_9(bag_size, items): # 請同學記得把檔案名稱改成自己的學號(ex.1104813.py) # depth first search / breadth first search + backtracking len_items=len(items) weight=[] #物品重量 price=[] #物品價值 for i in items: weight.append(i[0]) price.append(i[1]) matrix=[[0 for i in range(bag_size+1)]for j i...
daniel880423/Member_System
file/hw9/1100419/hw9_s1100419_0.py
hw9_s1100419_0.py
py
1,041
python
en
code
0
github-code
13
25823007530
import os from argparse import ArgumentParser from phonerouting import PhoneOperatorList def csv_to_dict(filename, delimiter=',', skip_header=1): """Read CSV file and convert it into a dictionary based on the first two columns. The first column is used as keys of type str, the second as the values, which...
ufeindt/alatest-challenge
get_price.py
get_price.py
py
2,696
python
en
code
0
github-code
13
70486631058
import multiprocessing # import copy_reg import os import types from allennlp.predictors.predictor import Predictor _model_url = "https://storage.googleapis.com/allennlp-public-models/coref-spanbert-large-2020.02.27.tar.gz" # def _reduce_method(m): # if m.im_self is None: # return getattr, (m.im_class, m....
arg-hya/CRModels
MultiProcCRClass.py
MultiProcCRClass.py
py
2,236
python
en
code
0
github-code
13
24534387320
""" Given an integer array nums and an integer k, return thek most frequent elements. You may return the answer in any order. Test/edge cases: - single element, k = 1 - one unique num, multiple elements of same type, k = 1 - multiple unique elements, k = max - multiple unique, k = 1 - multiple unique, k != 1 or max (s...
Hintzy/leetcode
Medium/347_top_k_frerquent_elements/top_k_frequent.py
top_k_frequent.py
py
1,392
python
en
code
0
github-code
13
29762283959
# -*- coding: utf-8 -*- """ Created on Thu May 19 12:26:26 2022 @author: aceso """ #%% Modules import pandas as pd import os from sklearn.preprocessing import OneHotEncoder import numpy as np import datetime import pickle from sklearn.model_selection import train_test_split from tensorflow.keras.callbacks import Tens...
AceSongip/Article_Categorization_Using_NLP
text_classification_training.py
text_classification_training.py
py
2,984
python
en
code
0
github-code
13
23765601380
from securityheaders.checkers import Finding, FindingType, FindingSeverity from .checker import ExpectCTChecker class ExpectCTHTTPReportURIChecker(ExpectCTChecker): def check(self, headers, opt_options=dict()): findings = [] expectct = self.getexpectct(headers) if not expectc...
koenbuyens/securityheaders
securityheaders/checkers/expectct/httpreporturi.py
httpreporturi.py
py
680
python
en
code
206
github-code
13
40791256980
import os import torch import numpy as np import re from torchvision.io import read_image from pathlib import Path from tqdm import tqdm from PIL import Image import torch.nn.functional as F from torch.utils.data import DataLoader import torchvision.transforms as transforms import torchvision from torch.utils.data i...
zheyizhu/Generative-models
evaluation/clip_score.py
clip_score.py
py
4,809
python
en
code
0
github-code
13
37205035144
# -*- coding: utf-8 -*- import os import unittest # pytest in future config_filename = os.path.join(os.path.dirname(__file__), "../config.yaml") secrets_filename = os.path.join(os.path.dirname(__file__), "../secrets/secrets") os.environ["ARTIFACT_TRACKER...
oduwsdl/scholarly-orphans-trackers
tests/__init__.py
__init__.py
py
1,900
python
en
code
0
github-code
13
34651988228
import re import os import sys import csv import shutil import logging from subprocess import Popen, PIPE from dataclasses import dataclass from bs4 import BeautifulSoup import requests __version__ = "0.3.7" CFG_DIR = os.path.expanduser("~/.venvipy") DB_FILE = os.path.expanduser("~/.venvipy/py-installs") ACTIVE_DIR ...
sinusphi/venvipy
venvipy/get_data.py
get_data.py
py
12,348
python
en
code
37
github-code
13
12229060250
# -*- coding:utf-8 -*- from django.conf.urls import url from django.contrib import admin from .views import ( BigmeterRTListAPIView, getmapstationlist, getmapsecondwaterlist, showinfoStatics, getinstanceflow, getinstanceflow_data, getWatermeterflow, getWatermeterflow_data, getWaterm...
apengok/bsc2000
monitor/api/urls.py
urls.py
py
2,379
python
en
code
1
github-code
13
15214298592
# -*- coding: utf-8 -*- # greburs by InteGreat from odoo import api, fields, models, SUPERUSER_ID, _ from odoo.osv import expression class SaleOrderLine(models.Model): _inherit = 'sale.order.line' production_ids = fields.One2many('mrp.production', 'sale_line_id', string='Produccion') purchase_reques...
sgrebur/e3a
integreat_sale_mrp_mtso/models/sale.py
sale.py
py
10,290
python
en
code
0
github-code
13
7505915210
# 시간초과 (탑-다운 방식) import sys input = lambda: sys.stdin.readline().rstrip() sys.setrecursionlimit(10**6) m = 1000000007 d = [0] * 1000001 def dp(x): if x == 0: return 1 if x == 1: return 2 if x == 2: return 7 if d[x]: return d[x] d[x] = 3 * dp(x - 2) + 2 * dp(x - 1) ...
ryong9rrr/coding-test
동적계획법/백준14852-타일채우기3.py
백준14852-타일채우기3.py
py
1,245
python
en
code
0
github-code
13
15721403756
from django.conf.urls import url from . import views urlpatterns = [ url( r"^control/event/(?P<organizer>[^/]+)/(?P<event>[^/]+)/settings/swap$", views.SwapSettings.as_view(), name="settings", ), url( r"^control/event/(?P<organizer>[^/]+)/(?P<event>[^/]+)/settings/swap/new/...
rixx/pretix-swap
pretix_swap/urls.py
urls.py
py
1,468
python
en
code
0
github-code
13
44793479222
import csv from textblob import TextBlob file1 = open('/Users/Lucien/Documents/LevelEdu/sentiment_analysis/R_Scripts/pos_neg_labeled.csv', 'rb') reader = csv.reader(file1) new_csv = [] for row in reader: text = row[2].decode('utf-8') text = TextBlob(text) row.append(text.sentiment.polarity) new_csv.append(row) fil...
lgendrot/midtown-sentiment-analysis
Python_Scripts/validation.py
validation.py
py
515
python
en
code
0
github-code
13
13155845944
# -*- coding: utf-8 -*- r""" Module for plotting cluster properties. For inspiration, see http://www.astroexplorer.org/ """ import sys import numpy as np import matplotlib.pyplot as pl import matplotlib.colors as mcolors from matplotlib.patches import Circle import pandas as pd import lightkurve as lk # from transitl...
jpdeleon/chronos
chronos/plot.py
plot.py
py
45,997
python
en
code
5
github-code
13
7772687970
import os import kaa import kaa.metadata import core backends = {} def init(base): """ Initialize the kaa.webmetadata databases """ if backends: return import thetvdb as backend backends['thetvdb'] = backend.TVDB(os.path.expanduser(base + '/thetvdb')) def parse(filename, metadata=Non...
freevo/kaa-webmetadata
src/tv/__init__.py
__init__.py
py
1,797
python
en
code
2
github-code
13
28679669165
#펠린드롬? import sys input = sys.stdin.readline n = int(input()) numbers = list(map(int,input().split())) isPel = [[0] * n for _ in range(n)] #N * N 격자크기 for i in range(n): isPel[i][i] = True #자기 자신은 무조건 펠린드롬 if i < n-1: isPel[i][i+1] = (numbers[i] == numbers[i+1]) for diff in range(2,n): for i in range(n -...
hodomaroo/BOJ-Solve
백준/Gold/10942. 팰린드롬?/팰린드롬?.py
팰린드롬?.py
py
569
python
en
code
2
github-code
13
43370956216
from sklearn.model_selection import train_test_split import glob import pickle ''' This function creates train and validation sets to build model. Also test set to test the model. ''' def create_train_validation_test_sets(input_dir): txtfiles=[] ''' Reading all files from the directory''' class_label=[] ...
Nayyaroddeen/spam_classification
preprocess.py
preprocess.py
py
1,142
python
en
code
0
github-code
13
13529831262
import pytz import datetime import cv2 import json from openpyxl import Workbook from django.http import JsonResponse, StreamingHttpResponse from django.shortcuts import render, HttpResponse, redirect from django.views.generic.detail import DetailView from django.contrib.auth.decorators import login_required from djang...
HENNESSYxie/NPR_web
NPR_web/carRegister/views.py
views.py
py
7,922
python
en
code
0
github-code
13
21937531072
from typing import Dict from telegram import Update, MessageEntity from telegram.ext import CallbackContext, Handler from Constants import logger from conversations.commands import MainCommands from conversations.handlers import ADD_TASK_CONVERSATION_HANDLER, CHECK_TASK_CONVERSATION_HANDLER, \ LIST_TASKS_CONVERSA...
dattatreya303/round_robin_tasker
conversations/callbacks/root_handler_callbacks.py
root_handler_callbacks.py
py
2,499
python
en
code
0
github-code
13
36305313443
import os import requests import time import re import random import argparse import logging from config import IMPORTANT_COINS, WURL, MROOM, MTOKEN, MSERVER def send_matrix_msg(msg): if "**" not in msg: data = { "msgtype": "m.text", "body": msg, } else: formatt...
MQ37/crypto-price-matrix-bot
main.py
main.py
py
4,783
python
en
code
0
github-code
13
33582931227
import discord from discord import app_commands, Object import re import os import random as rand import asyncio from typing import List import logging intents = discord.Intents.default() intents.guilds = True client = discord.Client(intents=intents) tree = app_commands.CommandTree(client) @client.event async def on_...
taisei12232/order-bot
discordbot.py
discordbot.py
py
4,504
python
en
code
0
github-code
13
6929927110
# -*- coding: utf-8 -*- import os import sys import time import math import numpy as np import random from threading import Thread from math import exp from math import log import torch import torch.distributed as dist from torch.autograd import Variable from cjltest.utils_model import MySGD, test_model def fixed_up...
wanglikuan/FedNova
learner.py
learner.py
py
9,901
python
en
code
0
github-code
13
16617943199
# https://leetcode.com/problems/permutations/ import itertools from typing import List # Example 1: # nums = [1,2,3] # Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] # Example 2: # # Input: nums = [0,1] # Output: [[0,1],[1,0]] # Example 3: # # Input: nums = [1] # Output: [[1]] class Solution: def permu...
jihuncha/python_study_duplicated
Algorithm_95/pycharm_folder/210412_graph/210420_practice.py
210420_practice.py
py
3,937
python
en
code
2
github-code
13
23382792943
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html from scrapy.item import Item, Field class MovieItem(Item): MainPageUrl = Field() Title = Field() Rating = Field() Year = Field() ID = Field() D...
dorseg/places-in-movies
crawler/crawler/items.py
items.py
py
384
python
en
code
0
github-code
13
23631413312
from db.run_sql import run_sql from models.supplier import Supplier #Save new Supplier def save(supplier): sql = "INSERT INTO suppliers (supplier_name, supplier_number, supplier_manager, supplier_address, supplier_phone) VALUES (%s, %s, %s, %s, %s) RETURNING *" values = [supplier.supplier_name, supplier.suppl...
JackSlater99/ConstructionCostTracker-SoloProject
repositories/supplier_repository.py
supplier_repository.py
py
1,926
python
en
code
1
github-code
13
27036466525
import pickle from unittest import result from flask import Flask, request, app, jsonify, url_for, render_template from flask_cors import cross_origin import pandas as pd import numpy as np from app_log import log from mongodb import MongoDBManagement from sklearn.preprocessing import StandardScaler import warnings war...
Arkintea/Project-Algerian_Fire_Prediction
app.py
app.py
py
4,095
python
en
code
1
github-code
13
38757036022
# coding=utf-8 # author= YQZHU from django.conf.urls import url, include from django.contrib import admin from . import views urlpatterns = [ url(r'^ranking/', include([ url(r'^list_rules', views.list_rules, name='list_rules'), url(r'^add_rule', views.add_rule, name='add_rule'), url(r'^e...
lianhuness/hongda_v2
finance/finance_urls.py
finance_urls.py
py
1,118
python
en
code
0
github-code
13
5867102645
from flask import Flask, jsonify, render_template, request import json from datetime import timedelta from service import Service import model app = Flask(__name__) app.jinja_env.variable_start_string = '[[' # 解决jinja2和vue的分隔符{{}}冲突 app.jinja_env.variable_end_string = ']]' app.config['SEND_FILE_MAX_AGE_DEFAULT'] = ti...
MaxLEAF3824/Trajectory
web/app.py
app.py
py
1,358
python
en
code
0
github-code
13
73537228176
"""doc""" def table(lis): """doc""" print("+-+-+-+") for i in lis: print('|', end="") for j in i: print("%c|" % j, end="") print() print("+-+-+-+") def checkwinner(lis): """doc""" for i in range(3): if lis[i][0] == lis[i][1] == lis[i][2]: ...
film8844/KMITL-Computer-Programming-Year-1
week10/[Week 10] Tic-Tac-Toe.py
[Week 10] Tic-Tac-Toe.py
py
1,619
python
en
code
0
github-code
13
14945258055
from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from good.models import Good, Order from contract.models import Montage from django.views.generic import ListView, DetailView, FormView, TemplateView, CreateView from good.forms import SearchOrderForm from django.db.models import...
duutka/windows_django
good/views.py
views.py
py
4,342
python
en
code
0
github-code
13
10668462215
import os import click from flask import Flask from todoism.settings import config from todoism.blueprints.todo import todo_bp from todoism.blueprints.auth import auth_bp from todoism.blueprints.home import home_bp from todoism.extensions import db, login_manager def create_app(config_name = None): if config_na...
parkerhsu/Flask_Practice
BlueTodoism/todoism/__init__.py
__init__.py
py
1,040
python
en
code
0
github-code
13
9537712457
import os import shutil import signal import time import random fr0m = 'monitor_dir' to = 'monitor_dir_1' def handle_signal(signal, frame) -> None: global file_dict print('Handler start') for file in os.listdir(to): os.remove(f'{to}/{file}') print('Handler stop. Files have been deleted') ...
SimpleIN1/process_fires2
ftp_tracker/copy_file.py
copy_file.py
py
606
python
en
code
0
github-code
13
42700425295
from random import randint import pygame as pg from .particles import create_particles, draw_particles RED = (255, 0, 0) def get_pos_center() -> tuple[int, int]: width, height = pg.display.get_surface().get_size() return int(width / 2), int(height / 2) def gen_pos_random() -> tuple[int, int]: width, ...
Fernando-Medeiros/Pleiades
src/enemy/entity.py
entity.py
py
2,464
python
en
code
0
github-code
13
34605548073
# !/usr/bin/env python import rospy from std_msgs.msg import String, Int8, Float64 from robot.robot import ExoRobot r = ExoRobot() def callback(data): rospy.loginfo(rospy.get_caller_id() + 'I heard %f', data.data) goal_angle = (data.data / 180.0) *3.14 r.step(goal_angle) def listener(): rospy.init_nod...
QinjieLin-NU/exoedu-robot
main.py
main.py
py
461
python
en
code
0
github-code
13
38460966365
from multiprocessing import parent_process import random import math class Chromosome: genes=None score = None def __init__(self,g,f): self.genes=g self.score=f def _generate_parent(target, geneSet, fitnessFn): genes = [] while len(genes)<len(target): sampleSize = min(l...
bkgsur/GeneticAlgorithms
genetic.py
genetic.py
py
1,380
python
en
code
0
github-code
13
29276682281
import pandas as pd import numpy as np from sklearn.preprocessing import scale from sklearn import preprocessing import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.optimizers import SGD, RMSprop, Adadelta, Adam import matplotlib.pyplot as plt from keras impor...
JonOnEarth/indoor-position
auto_regression.py
auto_regression.py
py
2,783
python
en
code
3
github-code
13
8965495757
# all fund code import requests from lxml import etree from sql import Sql Sql = Sql() db_conn = Sql.conn_db('fund') url = 'http://fund.eastmoney.com/allfund.html' r = requests.get(url) r.encoding = 'gb2312' html = r.text html = etree.HTML(html) num_boxes = html.xpath('//div[@id="code_content"]//div[@class="num_box"...
ryjfgjl/Fund
Spider/allfund.py
allfund.py
py
842
python
en
code
0
github-code
13
42958759444
#!/usr/bin/python3 # intents_blueprint.py import os import sys sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'util')) from flask import Blueprint, request, jsonify from db_assets import aggregate_assets, get_total_capital from StockPrices import getActives as getHotAssets, g...
therealsharath/fizz
backend/src/flask/dialogflow_blueprint.py
dialogflow_blueprint.py
py
3,443
python
en
code
1
github-code
13
15391978284
import tkinter as tk root = tk.Tk() def line(event): canvas.create_line(0,0, event.x,event.y) canvas = tk.Canvas(root, width=400, height=400) canvas.pack() root.bind("<Button-1>", line) root.mainloop()
chunin1103/BGclipping
drawing.py
drawing.py
py
210
python
en
code
0
github-code
13
10844202415
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Assignment in BMP course - Program Association Table parser Author: Jakub Lukac E-mail: xlukac09@stud.fit.vutbr.cz Created: 16-10-2019 Testing: python3.6 """ import sys from psi import PSI class PAT(PSI): __PAT_TABLE = 0x00 __TABLE_EXTENSION_...
cubolu/School-Projects
Python/BMS/dvb-t/pat.py
pat.py
py
2,015
python
en
code
0
github-code
13
74176775379
""" Panacea - throughput.py 1) Measures differential atmospheric refraction .. moduleauthor:: Greg Zeimann <gregz@astro.as.utexas.edu> """ import numpy as np import os.path as op from utils import biweight_bin from fiber_utils import bspline_x0 from astropy.io import fits from dar import Dar from telluricabs impor...
grzeimann/Panacea
throughput.py
throughput.py
py
5,997
python
en
code
8
github-code
13
5477184460
import json import requests import pandas as pd import boto3 from datetime import datetime from flatten_json import flatten from io import BytesIO, StringIO from airflow.contrib.hooks.aws_hook import AwsHook def get_aws_config(conn_id): aws_hook = AwsHook(conn_id) credentials = aws_hook.get_credentials() return cr...
gurjarprateek/bixi-data-repository
airflow/dags/scripts/task_incremental_stations.py
task_incremental_stations.py
py
2,237
python
en
code
0
github-code
13
13222391255
import enum from pydantic.types import Optional from sqlmodel import Field, SQLModel, Enum, Column from src.core.helpers.type_choices import UserStatusType class UserBase(SQLModel): name: str email: str username: str = Field(unique=True) phone_number: Optional[str] = None is_superuser: bool = Fiel...
MahmudulHassan5809/fastapi-starter
src/accounts/models.py
models.py
py
1,276
python
en
code
3
github-code
13
25918575239
#!/usr/bin/env python3 # モジュールのインポート import os import tkinter import tkinter.filedialog import tkinter.messagebox from strip_ansi import strip_ansi from functools import reduce def main(): # ファイル選択ダイアログの表示 root = tkinter.Tk() root.withdraw() fTyp = [("", "*")] iDir = os.path.abspath(os.path.dirn...
Ischca/log-brewer
src/main.py
main.py
py
1,466
python
en
code
0
github-code
13
36973574006
from django.shortcuts import render, get_object_or_404, redirect from blog.models import Post from .models import Comment from .forms import CommentForm def post_comment(request, post_pk): post = get_object_or_404(Post, pk=post_pk) if request.method == 'POST': form = CommentForm(request.POST) ...
a4322296/django
comments/views.py
views.py
py
1,186
python
zh
code
1
github-code
13
39129547136
from .constants import ( LRC_ATTRIBUTE, LRC_LINE, LRC_TIMESTAMP, LRC_WORD, MS_DIGITS, TRANSLATION_DIVIDER, ) from .file import LrcFile from .line import LrcLine from .parser import LrcParser from .text import LrcText, LrcTextSegment from .time import LrcTime from .utils import * __all__ = [ ...
283375/lrcparser_python
lrcparser/__init__.py
__init__.py
py
536
python
en
code
0
github-code
13
19299886538
from tabnanny import check class Account: def __init__(self,filepath): self.filepath = filepath with open(filepath,'r') as file: self.balance = int(file.read()) def withdraw(self, amount,fees=0): self.balance = self.balance - (int(amount) + int(fees)) self.com...
mohamedawnallah/Object-Oriented-Programming
Bank Account Exercise/acc.py
acc.py
py
1,121
python
en
code
0
github-code
13
22223093594
''' 利用string库和os库编写程序,去除开单日期中的‘.’、‘/’符号,月和日保持2位,不足需要补齐,最后输出日期yyyyMMdd(20211207)。 把处理后的结果保存到‘\\home\\数据处理结果\\kdDate.csv’中 ''' import csv import datetime import xlrd wj_path = 'C:\\Users\\14404\\Desktop\\数据分析\\原始数据-某图书机构在各电商平台销售数据 1130.xls' # 工作簿 file = xlrd.open_workbook(wj_path) # 第一个工作表 gzb = file[0] # 行数 hs = gzb.nr...
qifiqi/codebase
python_codebase/数据分析/去除标点符号/去除符号.py
去除符号.py
py
1,846
python
zh
code
3
github-code
13
31843321571
from keras.models import load_model from keras.models import Model from keras.layers import Conv2D from keras.layers import Flatten from keras.layers import concatenate from keras.layers import Activation from keras.layers import Reshape import keras.backend as K filepath = '../trained_models/300x300/weights.17-1.00.h...
oarriaga/SSD-keras
src/utils/tests/modify_model.py
modify_model.py
py
1,956
python
en
code
84
github-code
13
189994737
from fastapi import FastAPI from server.routes.sequence import router as SequenceRouter app = FastAPI() app.include_router(SequenceRouter, tags=["Sequence"], prefix="/sequence") @app.get("/", tags=["Root"]) async def read_root(): return {"message": "Welcome :)"}
megharosejayan/fastapi-sql
app/server/app.py
app.py
py
276
python
en
code
0
github-code
13
35216414894
from django.urls import path, include from rakes import views urlpatterns = [ path('', views.RakesHomePageView.as_view(), name='Rakes_home'), path('RakeEntry', views.AddRake, name='Rakes_entry'), path('ModuleAutocomplete', views.autocomplete1, name='autocomplete1'), path('AddModule', views.AddModule, n...
vinaykumar1908/082021i
rakes/urls.py
urls.py
py
1,392
python
en
code
0
github-code
13
40200148393
import pyfiglet import sys import socket from datetime import datetime # Defining a name ascii_banner = pyfiglet.figlet_format("PORT SCANNER") print(ascii_banner) # Defining a target if len(sys.argv) == 2: # translate hostname to IPv4 ip = socket.gethostbyname(sys.argv[1]) else: print("Invalid amount of Argument...
dummy-co-der/Port-Scanner
port_scanner.py
port_scanner.py
py
1,023
python
en
code
0
github-code
13
70108455378
from telebot import types def hotel_result_mark_up(text=None, prev=False, next=True, row_width=None, hotel_id=None): search_res_mark_up = types.InlineKeyboardMarkup(row_width=row_width) btn = types.InlineKeyboardButton(text=text, callback_data=text) next_btn = types.InlineKeyboardButton(text='>', callback...
lexsorokin/HotelsForYou_bot
keyboards/custom_functions_kewboards/hotel_search_result_markup.py
hotel_search_result_markup.py
py
2,191
python
en
code
0
github-code
13
6178260414
import os from numpy import array from numpy.random import shuffle from sentence_transformers import losses from abc import ABC, abstractmethod from torch import load, tensor, sum, clamp, long, save from torch.nn.functional import normalize from torch.optim import Adam from torch.utils.data import IterableDataset, Da...
gjorgjevik/embed4sd
embed4sd/learners.py
learners.py
py
10,050
python
en
code
0
github-code
13
42151242865
from CVariable import CReadVariable,CWriteVariable from Vector import * #/========================================================================== #*! # @brief t_AssetVersionOne #/ class t_AssetVersionOne: #/========================================================================== #*! # @brief Member #/ m_mId =...
3Dsamples/MakeHuman-unity
Assets/MakeHuman/Icons/KsSoft/Editor/Multilingual/tools/protocol/t_AssetVersionOne.py
t_AssetVersionOne.py
py
1,543
python
en
code
2
github-code
13
18770809269
# 외벽 점검 # N : dist 길이 # 시간복잡도: O(N!) import itertools def solution(n: int, weak: list, dist: list) -> int: dist_len = len(dist) weak = weak + [w + n for w in weak] len_weak = len(weak) for number_of_permutation in range(1, dist_len + 1): # 외벽 검사할 친구들 뽑기 for friends in itertools.permuta...
galug/2023-algorithm-study
level_3/outside_wall_inspection.py
outside_wall_inspection.py
py
1,396
python
ko
code
null
github-code
13
23026709382
# -*- coding: utf-8 -*- # @Author: IBNBlank # @Date: 2019-01-20 19:32:03 # @Last Modified by: IBNBlank # @Last Modified time: 2019-01-20 23:02:20 import cv2 as cv gray_path = "..\\example\\image\\lena256.bmp" gray = cv.imread(gray_path, cv.IMREAD_UNCHANGED) color_path = "..\\example\\image\\lenacolor.png" color ...
IBNBlank/toy_code
OpenCV-Repository-master/02.图像处理基础/my_code/01.read_pixels.py
01.read_pixels.py
py
665
python
en
code
0
github-code
13
41229412144
class Solution: def my_sol(self, dividend: int, divisor: int) -> int: # time limit excceded if dividend == 0: return 0 isPositive = True if dividend < 0: isPositive = not isPositive dividend = abs(dividend) if divisor < 0: ...
devpotatopotato/devpotatopotato-LeetCode-Solutions
Solutions/29.py
29.py
py
1,186
python
en
code
0
github-code
13
40173140703
import random def create(width, heigth): sideA = random.randint(0, width) sideB = random.randint(0, heigth) field = [sideA, sideB] return field def paint(pen, field): sideA = field[0] sideB = field[1] pen.up() pen.goto(sideA / 2 * (-1), sideB / 2 * (-1)) pen.down() for _ in...
incente/LearningPython
Projects/Field helper/create_field.py
create_field.py
py
491
python
en
code
0
github-code
13
35647056999
from apscheduler.schedulers.asyncio import AsyncIOScheduler from requests_cache import CachedSession from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from tzlocal import get_localzone from app.configs import ( DATABASE_URI, IPGEO_CACHE, OPENWEATHER_CACHE, SCHEDULER_JOBS_STOR...
avillia/tg-weather-bot
app/configs/extensions.py
extensions.py
py
711
python
en
code
1
github-code
13
24126515880
# setting up the main window or using qcheckbox widgets import sys from PyQt6.QtWidgets import QApplication, QWidget, QCheckBox, QLabel from PyQt6.QtCore import Qt class MainWindow(QWidget): def __init__(self) -> None: super().__init__() self.initializeUI() def initializeUI(self): ...
jonasht/beginning_pyQt_book
3-addingMoreFunctionalityWithWidgets/7.py
7.py
py
560
python
en
code
0
github-code
13
1596988578
""" @author: Matheus José Oliveira dos Santos Last Edit: 26/05/2023 """ import pandas as pd import urllib.parse import psycopg2 # ex: # import os # variable_value = os.getenv('VARIABLE_NAME') class DB_interface: def __init__(self,db_name) -> None: print('connecting in: '+db_name) self.d...
maj-oliveira/quant-finance-strategy
src/db_interface.py
db_interface.py
py
3,528
python
en
code
0
github-code
13
25247344836
from flask_restful import Resource from flask import request from bson import ObjectId from dao.gameInstance import get_game_instance , make_move from dao.user import get_user_by_id from dao.move import make_move_entry from validators.move import validate_move_obj , validate_move, get_winner ,check_status from utils.co...
mukeshbhakuni/messenger
tictactoe/gameservice/business_logic/serviceapis/move.py
move.py
py
2,397
python
en
code
0
github-code
13
4500857112
import tkinter as tk # MÓDULO PARA AÑADIR ELEMENTOS A LA INTERFAZ from tkinter import ttk from tkinter import OptionMenu from tkinter import StringVar from tkinter import Text from tkinter import messagebox from interfaz_grafica2 import mostrar_mensaje def insertar_producto(): producto = input_producto...
zengotita/SGE-Ejemplos
Tkinter/productos.py
productos.py
py
3,760
python
es
code
0
github-code
13
71068117138
# -*- coding: utf-8 -*- """ Created on Wed Jul 11 14:49:33 2018 @author: pwfa-facet2 """ import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit #import pyzdde.arraytrace as at import pyzdde.zdde as pyz import random as rand def beamline_matrix(d, c_x, c_y, rot_angle):...
eseguraca6/slacecodes
raytracing/lensmirrornodecenter.py
lensmirrornodecenter.py
py
9,953
python
en
code
2
github-code
13
73570781776
def add_twos(target): count = 0 pile = 0 while pile < target and pile + 2 <= target: pile = pile + 2 count = count + 1 return pile def solve_case(): n = int(input()) weights = sorted([int(c) for c in input().split()]) two_amount = sum(list(filter(lambda x: x == 2, weig...
JDSeiler/programming-problems
codeforces/round-693/b-candies.py
b-candies.py
py
876
python
en
code
0
github-code
13
16987145781
import unittest from RefactoringKata.VideoRental.VideoRental import Customer, Rental, Movie class Test_VideoRental(unittest.TestCase): def test_should_when(self): customer = Customer("John") movie = Movie("Fantasia", Movie.Children) rental = Rental(movie, 1) customer.add_rental(re...
AAFINSYS/CleanerCodeInPython
RefactoringKata/VideoRental/test_videoRental.py
test_videoRental.py
py
546
python
en
code
0
github-code
13
2864484188
import httplib import os import mock import stubout import webtest from google.apputils import app from google.apputils import resources from google.apputils import basetest from simian import settings from simian.mac import models from simian.mac.admin import main as gae_main from simian.mac.admin import xsrf from...
googlearchive/simian
src/tests/simian/mac/admin/upload_icon_test.py
upload_icon_test.py
py
1,811
python
en
code
334
github-code
13
2850641455
from ...abstasks.AbsTaskRetrieval import AbsTaskRetrieval from ...abstasks.BeIRPLTask import BeIRPLTask class FiQAPLRetrieval(AbsTaskRetrieval, BeIRPLTask): @property def description(self): return { "name": "FiQA-PL", "beir_name": "fiqa-pl", "description": "Financia...
embeddings-benchmark/mteb
mteb/tasks/Retrieval/FiQAPLRetrieval.py
FiQAPLRetrieval.py
py
714
python
en
code
755
github-code
13
9069119938
import requests import os from os import path import preprocessor as pre #import TF_IDF as tf_idf list_path=[] def getFile(p): for element in os.listdir(p): if('.' not in element): getFile(p+'/'+element)# else: list_path.append(p+"/"+element) return list_path # getFile(...
nvtuehcmus/datamining
crawl_from_files.py
crawl_from_files.py
py
1,649
python
en
code
0
github-code
13
48031287064
# Random Modules import random for i in range(3): random.random() print(random.random()) # ========================== for i in range(3): print(random.randint(10, 20)) # ========================== members = ['John', 'Merry', 'Bob', 'Mars'] leader = random.choice(members) print (leader) ...
artemkiryu/Trunk_Repo
generatingRandomValues.py
generatingRandomValues.py
py
534
python
en
code
1
github-code
13
32397892072
""" Defineert de class ZAL """ from __future__ import annotations from typing import AnyStr, Optional, Mapping, Iterator, Tuple import dataclasses from lxml import etree from . import xml_utils __all__ = ['Gegevensdienst', 'Zorgaanbieder', 'ZAL'] @dataclasses.dataclass(frozen=True) class Gegevensdienst: # pylin...
Zorgdoc/medmij-python
medmij/zal.py
zal.py
py
3,426
python
nl
code
0
github-code
13
20999522690
import glob, os import cv2 import numpy as np import matplotlib.pyplot as plt import math from shutil import copyfile import datetime import pickle import csv ## IMAGE DISPLAY def showImages(images, cols=None, rows=None, cmap=None): if len(images) == 1: showImage(images[0],cmap=cmap) return ...
cesare-montresor/deep-document-parser
utils.py
utils.py
py
5,192
python
en
code
0
github-code
13
18025985935
""" 问题:根据每条边的权值,求出从起点s到其他每个顶点的最短路径和最短路径的长度。 说明:不考虑权值为负的情况,否则会出现负值圈问题。 s:起点 v:算法当前分析处理的顶点 u:与v邻接的顶点 d:从s到v的距离 d(u):从s到u的距离 e(v,u):顶点v到顶点u的边的权值 问题分析: Dijkstra算法按阶段进行,同无权最短路径算法(先对距离为0的顶点处理,再对距离为1的顶点处理,以此类推) 一样,都是先找距离最小的。在每个阶段,Dijkstra算法选择一个顶点v,它在所有unknown顶点中具有最小的d(v)。 同时算法声明从s到v的最短路径是known的。阶段的其余部分为,对w的d(v)距离)和 prev(上一个顶点...
7Bcoding/Python-data-structure-algorithm
5-图论算法/Dijkstra-迪杰斯特拉算法.py
Dijkstra-迪杰斯特拉算法.py
py
5,475
python
zh
code
1
github-code
13
17040795144
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.RcsmartCommonAppInfo import RcsmartCommonAppInfo from alipay.aop.api.domain.ApprovalQuery import ApprovalQuery class AlipayFincoreComplianceRcservcenterRcsmartQueryModel(object): ...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/AlipayFincoreComplianceRcservcenterRcsmartQueryModel.py
AlipayFincoreComplianceRcservcenterRcsmartQueryModel.py
py
1,908
python
en
code
241
github-code
13
13614130380
# Load libraries import os import matplotlib.image as mpimg import numpy as np import cv2 import torch from torch.utils.data import Dataset, DataLoader from skimage import transform # Create facial keypoint dataset class class FacialKeypointsDataset(Dataset): def __init__(self, key_points, root_dir, transform=No...
cverdence/face_detection
src/transforms.py
transforms.py
py
4,935
python
en
code
1
github-code
13
42586654525
# -*- coding: utf-8 -*- import cv2 as cv import time import RPi.GPIO as GPIO GPI0.setmode (GPI0.B0ARD) GPIO.setup(13, GPIO.IN, pull_up_down=GPI0.PUD_DOWN) capture = cv .VideoCapture(0) index = 0 while(True) : if(GPI0. input(13) == 1) : print(1) #capture = cv.VideoCapture(0) ret...
inseasonzzz/camerause
tian.py
tian.py
py
623
python
en
code
0
github-code
13
74564552978
#!/usr/bin/env python """ _New_ Oracle implementation of Masks.New """ from WMCore.WMBS.MySQL.Masks.New import New as NewMasksMySQL class New(NewMasksMySQL): sql = NewMasksMySQL.sql def getDictBinds(self, jobList, inclusivemask): binds = [] maskV = 'T' if inclusivemask else 'F' for ...
dmwm/WMCore
src/python/WMCore/WMBS/Oracle/Masks/New.py
New.py
py
1,051
python
en
code
44
github-code
13
29498185056
import asyncio import logging import os import re import requests import subprocess import sys import threading from hashlib import sha512 from operator import itemgetter from handlers.base import BaseHandler from handlers.mixins import NonemptyMessageMixin, RateLimitMixin from handlers.registry import register_handl...
Ninjaclasher/Ninjabot
handlers/third_party.py
third_party.py
py
4,531
python
en
code
1
github-code
13
12216925557
import cv2 import face_recognition import numpy as np import known_faces as faces # https://github.com/ageitgey/face_recognition/blob/master/examples/facerec_from_webcam_faster.py # 1. Need to load all images and resize photos and make a new set in new folder. # 2. Fixed red error during running and found. # 3. Refact...
atthana/computer_vision_codium
base_code.py
base_code.py
py
3,871
python
en
code
0
github-code
13
71996118739
def calculate_average(scores): total_subjects = len(scores) total_score = sum(scores.values()) average_score = total_score / total_subjects return average_score scores = {} num_subjects = int(input("Enter the number of subjects: ")) for i in range(num_subjects): subject = input(f"Enter the name o...
uakk101/Material
PythonPractice/Tasks/Task_03.py
Task_03.py
py
884
python
en
code
0
github-code
13
72626466578
#!/usr/bin/env python3 import sys def read_fasta(filepath): """ Generator to read multiline fasta found at the filepath as required. Yields a tuple containing the (accession, sequence) Arguments: filepath -- string containing path to Fasta formatted file Return: (accession, ...
Znigneering/BioinformaticTurtorial
Comments/find_shared_motif.py
find_shared_motif.py
py
3,350
python
en
code
0
github-code
13