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
36768435919
def main(): for i in range(int(input())): s = input() if len(s) > 10: print(f"{s[0]}{len(s)-2}{s[-1]}") else: print(s) if __name__ == '__main__': main()
arbkm22/Codeforces-Problemset-Solution
Python/WayTooLongWords.py
WayTooLongWords.py
py
211
python
en
code
0
github-code
6
16708430730
import networkx as nx import matplotlib.pyplot as plt import pandas as pd # nodes=['A','B','C','D','E','F','1'] dataset = pd.read_csv("./topology.csv", header=None) lenth = dataset.shape[0] G=nx.Graph() edges=[] for i in range(lenth): edges.append((dataset.values[i, 0], dataset.values[i, 1])) r=G....
GAVIN-YAN/FinTechauthon2022
topology/topology.py
topology.py
py
712
python
en
code
0
github-code
6
7859737668
liste_mois = [ ('janvier', 31), ('fevrier', 28), ('mars', 31), ('avril', 30), ('mai', 31), ('juin', 30), ('juillet', 31), ('aout', 31), ('septembre', 30), ('octobre', 31), ('novembre', 30), ('decembre', 31) ] calendrier = [] for nom_mois, nb_jours in liste_mois: for ...
mercator-ocean/python-notes
exercices/makina/syntaxe-bases/calendrier_1.py
calendrier_1.py
py
473
python
fr
code
0
github-code
6
26529327586
#유기농 배추 from collections import deque def bfs(x,y): queue = deque() queue.append((x,y)) graph[x][y] = 0 while queue: x, y = queue.popleft() for i in range(4): nx = x + dx[i] ny = y + dy[i] if 0<=nx<n and 0<=ny<m and graph[nx][ny] == 1: ...
Jaeheon-So/baekjoon-algorithm
DFS, BFS/1012.py
1012.py
py
822
python
en
code
0
github-code
6
31536399436
from project.hardware.heavy_hardware import HeavyHardware from project.hardware.power_hardware import PowerHardware from project.software.express_software import ExpressSoftware from project.software.light_software import LightSoftware class System: _hardware = [] _software = [] @staticmethod def reg...
iliyan-pigeon/Soft-uni-Courses
pythonProjectOOP/project/system.py
system.py
py
4,537
python
en
code
0
github-code
6
41457482585
from sqlite3 import IntegrityError, Connection import schema from flask import g from flask import request from flask import Blueprint from flask.views import MethodView from werkzeug.exceptions import abort from flaskr import settings from flaskr.utils.auth import login_required from flaskr.utils.db import get_db, g...
MioYvo/unlimited-level-messages
backend/flaskr/views/post.py
post.py
py
5,566
python
en
code
0
github-code
6
18100605374
""" https://leetcode.com/problems/maximum-ice-cream-bars/ 1833. Maximum Ice Cream Bars It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy in...
hirotake111/leetcode_diary
leetcode/1833/solution.py
solution.py
py
1,538
python
en
code
0
github-code
6
7869115009
import math # 入力 A, B, H, M = map(float, input().split()) # 座標を求める PI = 3.14159265358979 AngleH = 30.0 * H + 0.5 * M AngleM = 6.0 * M Hx = A * math.cos(AngleH * PI / 180.0) Hy = A * math.sin(AngleH * PI / 180.0) Mx = B * math.cos(AngleM * PI / 180.0) My = B * math.sin(AngleM * PI / 180.0) # 答えを出力 d = ...
E869120/math-algorithm-book
editorial/chap4-1/prob4-1-4.py
prob4-1-4.py
py
408
python
en
code
897
github-code
6
5026987486
# -*- coding:utf-8 -*- my_name = "分数" import pygame pygame.init() my_font = pygame.font.SysFont("simSun", 66) name_surface = my_font.render(u'分数', True, (0, 0, 0), (255, 255, 255)) pygame.image.save(name_surface, "name.png") enemy_hit_dict = dict() score = 0 ENEMY_SCORE = 100 # enemy_hit_dict = pygame.sprite.grou...
xinlongOB/python_docment
飞机大战/字体.py
字体.py
py
737
python
en
code
0
github-code
6
17961314485
from urllib import request, parse import json from getAccessToken import getToken def newNotification(filename, touser, key1, key2, key3, key4, first, remark): ACCESS_TOKEN = getToken() url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN' url = url.replace('ACCESS_TOKEN...
pkugeeklab/wx-server
notification/newNotification.py
newNotification.py
py
708
python
en
code
0
github-code
6
14816787756
"""web URL Configuration""" from django.conf.urls import include,url from django.contrib import admin from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name='index'), url(r'^pdx/(?P<pk>\w{0,50})/$', views.pdx, name="pdx"), url(r'^search/', views.search, name="...
jmason-ebi/pdx
web/urls.py
urls.py
py
442
python
en
code
0
github-code
6
9460034812
""" Запуск класса с датасетами твитов и генома ВИЧ """ import Hyperbolic import numpy as np import Levenshtein as Lev import pandas as pd from grad_descent import MSE import draw """ ТВИТЫ """ positive = np.array(pd.read_csv( r'twitter_data/positive.csv', sep=';', usecols=[3], names=['text'])) negative = np.arra...
DanilShishkin/Hyperbolic
actual/main.py
main.py
py
2,184
python
en
code
1
github-code
6
22251514739
import time def isprime(n): mas = [] d = 1 while d * d < n: if n % d == 0: mas.append(d) mas.append(n // d) d += 1 if d * d == n: mas.append(d) if len(mas) == 2: return mas[1] def g(n): counter = 0 mas = [] d = 2 while d * d...
MakinFantasy/xo
25/hw/2_correct.py
2_correct.py
py
775
python
en
code
0
github-code
6
14070127148
import math import numpy as np from scipy.special import expit class LogReg(): def __init__(self, lambda_1=0.0, lambda_2=1.0, gd_type='full', tolerance=1e-4, max_iter=1000, w0=None, alpha=1e-3): """ lambda_1: L1 regularization param lambda_2: L2 regularization param ...
idStep/hse_ml
logreg.py
logreg.py
py
2,793
python
en
code
0
github-code
6
651508757
from . learningTasks import RandomForest import os import luigi import numpy as np import logging # import the proper nifty version try: import nifty.graph.rag as nrag except ImportError: try: import nifty_with_cplex.graph.rag as nrag except ImportError: import nifty_with_gurobi.graph.rag ...
constantinpape/mc_luigi
mc_luigi/defectRandomForests.py
defectRandomForests.py
py
4,204
python
en
code
0
github-code
6
31360177466
#Long Short-Term Memory import numpy as np import pandas as pd import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import Dense, Dropout, LSTM from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error dataset_train = pd.read_csv('files/Salestrain.cs...
francinehahn/ai-and-machine-learning
detectingAnomalies/LSTM.py
LSTM.py
py
4,027
python
en
code
0
github-code
6
39220567289
from sklearn.preprocessing import StandardScaler file_name2 = 'data2.csv' df = pd.read_csv(file_name2) df['race_date'] = pd.to_datetime(df['race_date']).dt.date # 情報不足行を削除 df = df.dropna(subset=['past_time_sec1', 'past_time_sec2', 'past_time_sec3', 'past_time_sec4', 'past_time_sec5']).reset_index...
keisukee/horse_racing
normalize_3.py
normalize_3.py
py
2,492
python
en
code
1
github-code
6
71484383548
A, K = map(int, input().split()) ans = A for i in range(len(str(A))): for p in range(10): for q in range(10): s = str(A)[:i] + str(p) + str(q) * (len(str(A))-i-1) if (len(set(str(int(s)))) <= K): ans = min(ans, abs(A-int(s))) print(ans)
knuu/competitive-programming
atcoder/corp/codefes2014qa_d.py
codefes2014qa_d.py
py
290
python
en
code
1
github-code
6
39922767694
# THIS FILE IS SAFE TO EDIT. It will not be overwritten when rerunning go-raml. from flask import jsonify, request import sqlite3 def books_postHandler(): connection = sqlite3.connect("BookStore") cursor=connection.cursor() inputs = request.get_json() cursor.execute("CREATE TABLE IF NOT EXISTS BookSt...
BolaNasr/BookStore-API
server/handlers/books_postHandler.py
books_postHandler.py
py
608
python
en
code
0
github-code
6
21509830674
import pickle import numpy as np referrence_vec = {} ## list of numpy average vectors to compare with synonym_dict={} names=["safety","products and services","technical skills","soft skills","orientation","onboarding"] synonym_dict["safety"] = ["safety", "wellbeing","welfare","security"] synonym_dict["products and se...
yashbhtngr/employee-training-chatbot
comparision_vectors.py
comparision_vectors.py
py
1,110
python
en
code
0
github-code
6
32592778621
import geoip2.database """ Requirements: geoip2 use this page to download the db: https://dev.maxmind.com/geoip/geolite2-free-geolocation-data?lang=en """ # This creates a Reader object. You should use the same object # across multiple requests as creation of it is expensive. with geoip2.database.Reader('...
steriospydev/tutools
Functions/get_ip_location.py
get_ip_location.py
py
927
python
en
code
0
github-code
6
42602524063
#!/usr/bin/env python import numpy as np from subprocess import call from ase.io import read def argparse(): import argparse parser = argparse.ArgumentParser(description = """ This code will give you the (Total/Partial) Raidial Distribution Function. Return npy file. """) # Positional arguments...
hitergelei/tools
ase_rdf.py
ase_rdf.py
py
14,474
python
en
code
0
github-code
6
10506264622
""" a very simple MNIST classifier """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import sys from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf FLAGS = None def main(_): #import data mnist = input_d...
RuanYB/tensorflow
mnist.py
mnist.py
py
1,897
python
en
code
0
github-code
6
26889693373
import cv2 import numpy as np import matplotlib.pyplot as plt def viz2(img, regions, rooms, all_ctrs): all_ctrs_img = np.zeros((img.shape[0], img.shape[1], 3), np.uint8) cv2.drawContours(all_ctrs_img, all_ctrs, -1, (0, 255, 0), 3) filtered_ctrs_img = np.zeros((img.shape[0], img.shape[1], 3), np.uint8) ...
jmou/quarks-knit
viz2.py
viz2.py
py
736
python
en
code
0
github-code
6
34118032788
# Going to be extremely similar to the staff groups file from __future__ import print_function import os.path import json from typing import get_type_hints from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from...
Philip-Greyson/D118-Google-Groups-Licensing
doStudentGroups.pyw
doStudentGroups.pyw
pyw
16,072
python
en
code
0
github-code
6
22858483582
import sys CASE_FMT = "{} {}" def pos(x, y): if x == -1 and y == -1: return 0 if x == -1 and y == 0: return 1 if x == -1 and y == 1: return 2 if x == 0 and y == -1: return 3 if x == 0 and y == 0: return 4 if x == 0 and y == 1: return 5 if x ...
tivvit/codejam-2018
Q1/go-gopher/main-final.py
main-final.py
py
1,158
python
en
code
0
github-code
6
39473494610
#!/usr/bin/python3 # coding=utf-8 import sys,os import string import random import time import subprocess from binascii import unhexlify random.seed(time.time) charset=string.ascii_letters+string.ascii_lowercase+string.ascii_uppercase patchbytes=16 print("You are allowed a maximum patch of {} bytes".format(patchbyt...
Himanshukr000/CTF-DOCKERS
SeasidesCTF/rev/patch/wrapper.py
wrapper.py
py
1,601
python
en
code
25
github-code
6
5675740119
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) import os, re, collections, getpass, functools, click, six, logging, json, threading import dash from dash import dcc from dash import html import dash_bootstrap_components as dbc from dash.dependencies i...
meghanstell/SNOWIE
megalodon/web/apps/launch.py
launch.py
py
9,144
python
en
code
0
github-code
6
40787804441
''' Created on Feb 18, 2018 @author: fdunaway ''' class thermalCalculations: # Formula to calculate thermal rise rate: #f(x)=1.11676445E-14 * x^4 - 1.313037E-10 * x^3 + 4.08270207E-07 * x^2 + 0.00141231184 * x + 0.9994399220259089 # takes the number of seconds and returns the temperature rise of the heater. d...
mrncmoose/smart_controller
pi-code/ThermalPrediction/PredictDeltaTemp.py
PredictDeltaTemp.py
py
1,200
python
en
code
3
github-code
6
16970226908
from setuptools import setup from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open("README.md") as f: long_description = f.read() version = {} with open(path.join(here, "emv", "__init__.py")) as fp: exec(fp.read(), version) setup( name="emv", version=versi...
russss/python-emv
setup.py
setup.py
py
1,114
python
en
code
100
github-code
6
31014617376
import numpy as np import os import matplotlib.pyplot as plt import sys import NeuralTrainerCustoms as ntc import AdaMod as am import keras from keras import backend as K from keras.models import Sequential, Model from keras.layers import Input, Layer, Dense, Activation, Embedding, LSTM, Bidirectional, Lambda, conca...
fspring/NeuralArgMining
NeuralModel.py
NeuralModel.py
py
13,844
python
en
code
0
github-code
6
811362006
# Rotate List - https://leetcode.com/problems/rotate-list/ '''Given a linked list, rotate the list to the right by k places, where k is non-negative. Example 1: Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5...
Saima-Chaity/Leetcode
LinkedList/rotateList.py
rotateList.py
py
2,414
python
en
code
0
github-code
6
11753378103
import urllib3 import requests from bs4 import BeautifulSoup from csv import writer import csv import pandas as pd url = 'https://www.mubawab.tn/fr/cc/immobilier-a-louer-all:o:i:sc:houses-for-rent:p:' + str(1) page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') lists = soup.find_all('li', clas...
sofienne-chouiekh/Scraping_data_estate_location
test.py
test.py
py
1,091
python
en
code
0
github-code
6
44999838
import networkx as nx import numpy as np # from GPy.kern import Kern from functools import reduce from itertools import product import copy # class Ours(Kern): # def __init__(self, input_dim, G, scale=1., variance = 1, # active_dims=None, name='ours', K_matrix = None, kern = "linear", # ...
MichelangeloConserva/CutFunctionKernel
interleaving/our_kernel.py
our_kernel.py
py
8,950
python
en
code
2
github-code
6
26552265149
import os import sys import subprocess import concurrent.futures import tomllib addon_base_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) files_to_ignore_lower = [ x.lower() for x in ["initSettings.sqf", "initKeybinds.sqf", "XEH_PREP.sqf"] ] sqfvm_exe = os.path.join(addon_base_path, "sqfvm.ex...
acemod/ACE3
tools/sqfvmChecker.py
sqfvmChecker.py
py
3,556
python
en
code
966
github-code
6
33754030058
#!/usr/bin/env pybricks-micropython from pybricks.hubs import EV3Brick from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor) from pybricks.parameters import Port, Stop, Direction, Button, Color from pybricks.tools import wait, St...
KiroWasHere/Robocup-2023
RoboSusa[DEPRECATED]/4BERobocup [DEPRECATED]/main.py
main.py
py
9,063
python
en
code
2
github-code
6
3709323219
import pandas as pd import numpy as np from cloudservice import get_documenttask, download_doc from cloudservice import get_doctag, create_doctag, delete_doctag from cloudservice import create_doctagrel, delete_doctagrel from cloudservice import change_step from cloudservice import get_docs_byid, fill_docinfo from clou...
pengyang486868/PY-read-Document
analysislocal.py
analysislocal.py
py
8,022
python
en
code
0
github-code
6
30357818911
from pyface.qt import QtCore, QtGui, is_qt4 from pyface.image_resource import ImageResource from pyface.timer.api import do_later from pyface.ui_traits import Image from traits.api import ( Any, Bool, Button, Dict, Event, List, HasTraits, Instance, Int, Property, Str, cac...
enthought/traitsui
traitsui/qt/table_editor.py
table_editor.py
py
49,857
python
en
code
290
github-code
6
28322769353
from django.urls import path, include from . import views app_name = 'api' employment = [ path('', views.EmploymentListEmployee.as_view(), name='list'), ] employee = [ path('<int:pk>/employment/', include((employment, 'employment'))), ] urlpatterns = [ path('employee/', include((employee, 'employee'))...
crowmurk/mallenom
mallenom/api/urls.py
urls.py
py
325
python
en
code
0
github-code
6
73883744829
import os _, filename = os.path.split('/a/b/c/t.txt') print(filename) metro_areas = [ ('Tokyo', 'JP', 36.933, (35.689722, 139.691667)), ('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)), ('Mexico City', 'MX', 20.142, (19.433333, -99.133333)), ('New York-Newark', 'US', 20.104, (40.808611, -74.020386...
yubo-yue/yubo-python
fluentpython/ch02.py
ch02.py
py
857
python
en
code
0
github-code
6
31141179192
import transformers import torch def shape(structure): try: return structure.shape except AttributeError: return (f"list[{len(structure)}]", *shape(structure[0])) short_prompt = """To be or not to""" long_prompt = """It was the best of times, it was the worst""" if __name__ == "__main...
jjjmillist/ttc-workbench
scripts/23-05-18@13:50:44.py
23-05-18@13:50:44.py
py
2,176
python
en
code
0
github-code
6
728222177
import string # Initializing Variables num_sentences = 0 num_words = 0 the_num_sentences = 0 frequency_the = 0 # Task 0 with open('war_and_peace.txt', 'r') as f: # opening and reading file for line in f: line = line.rstrip() # removing the space on right side num_sentences += lin...
ruchitakatkar04/CNS-project-1
project1.py
project1.py
py
2,634
python
en
code
0
github-code
6
31022754626
import sys import numpy as np def compute_class_precision_recall(L,K): _,L = np.unique(np.array(L),return_inverse=True) _,K = np.unique(np.array(K),return_inverse=True) if(len(L) != len(K)): sys.stderr.write("Labels and clusters are not of the same length.") sys.exit(1) num_elements = l...
fspring/NeuralArgMining
b_cubed_measures.py
b_cubed_measures.py
py
1,672
python
en
code
0
github-code
6
36734211163
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ @author: Pramod Bharadwaj Chandrashekar, Li Liu @email: pchandrashe3@wisc.edu, liliu@asu.edu """ import numpy as np from sklearn.cluster import KMeans import scipy.stats as stats def get_cdf_pval(data): """ Function for guassian mixture of dat and computing pval...
liliulab/DeepCORE
DeepCORE_attention_util.py
DeepCORE_attention_util.py
py
1,744
python
en
code
0
github-code
6
74281642429
''' Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descen...
casanas10/practice_python
Recursion/lca_of_bst.py
lca_of_bst.py
py
2,292
python
en
code
0
github-code
6
18804693997
import copy from typing import Dict, Optional, TypeVar from pymilvus.exceptions import CollectionNotExistException, ExceptionsMessage from pymilvus.settings import Config Index = TypeVar("Index") Collection = TypeVar("Collection") class Index: def __init__( self, collection: Collection, ...
milvus-io/pymilvus
pymilvus/orm/index.py
index.py
py
4,921
python
en
code
744
github-code
6
43585654615
"""fitnesspro URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-ba...
sanjaymurali1910/fitnessclub
fitnesspro/urls.py
urls.py
py
4,115
python
en
code
0
github-code
6
11946226959
import sys, os, urllib.request, urllib.error, urllib.parse, logging, pwd import subprocess, site, cgi, datetime, threading, copy, json import uuid, time, re from html import escape # ***MUST COME before `from lxml import html`!*** from collections import defaultdict, OrderedDict from lxml import html from lxml.html im...
jcomeauictx/pyturn
myturn.py
myturn.py
py
32,136
python
en
code
0
github-code
6
27834268107
#! /usr/bin/python3 import numpy as np from matplotlib import pyplot as plt # Simple Euler forward # Input variables Q = 10. b = [20.] S = 1E-2 D = 2E-2 h_b = 4 intermittency = 1 # Constants phi = 3.97 g = 9.805 rho_s = 2700. rho = 1000. tau_star_crit = 0.0495 # Derived variables a1 = 1. / h_b a2 = S**0.7 / ( 2.9 ...
MNiMORPH/OTTAR
examples/standalone-widening-intuitive/transport-limited-width.py
transport-limited-width.py
py
1,398
python
en
code
5
github-code
6
16832434416
# 图形画布 from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas import matplotlib # 导入图表模块 import matplotlib.pyplot as plt # 导入绘图模块 class PlotCanvas(FigureCanvas): def __init__(self, parent=None, width=0, height=0, dpi=100): # 避免中文乱码 matplotlib.rcParams['font.sa...
yunmi02/MyProject
11/源程序/ticket _analysis/chart.py
chart.py
py
1,900
python
zh
code
1
github-code
6
33247661764
import sys from pathlib import Path import cv2 import imutils import numpy as np FILE = Path(__file__).resolve() ROOT = FILE.parents[1] if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) code_dir_path = ROOT.joinpath("Code") data_dir_path = ROOT.joinpath("Data") class BlurTool: def __init__(self): ...
Beau-Yang/CapstoneProject
Code/blur_tool_version.py
blur_tool_version.py
py
6,194
python
en
code
0
github-code
6
25499068282
# -*- coding: utf-8 -*- __author__ = 'Liang Zhao' __email__ = 'liangz8@vt.edu' __version__ = '1.0.0' import hashlib import unicodedata def get_hash_key(x): return hashlib.sha1(str(x)).hexdigest() def normalize_str(s): if isinstance(s, str): s = s.decode("utf8") s = unicodedata.normalize("NFKD", s...
klyc0k/EDSFilter
kmethods/warning_format.py
warning_format.py
py
5,127
python
en
code
0
github-code
6
73966289468
#!/usr/bin/env python # -*- coding:utf-8 -*- import requests import json #药监总局地址:http://scxk.nmpa.gov.cn:81/xk/ if __name__ == "__main__": url = 'http://scxk.nmpa.gov.cn:81/xk/itownet/portalAction.do?method=getXkzsList' user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chro...
xjuun/Note
Python/爬虫/code/request基础/06.requests之药监总局相关数据爬取.py
06.requests之药监总局相关数据爬取.py
py
1,414
python
en
code
0
github-code
6
33043283636
import base64 import os from django.conf import settings from django.contrib import messages from django.contrib.auth import login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.core.files.base import ContentFile ...
Vleyked/django-template
dinosaur_app/dinosaurs/views.py
views.py
py
6,837
python
en
code
0
github-code
6
35987644586
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import argopandas as argo wmos = [4902596, 4902597] var_names = ['PRES', 'TEMP', 'PSAL', 'DOXY', 'CHLA', 'BBP700'] for wmo in wmos: ix = argo.float(wmo).synthetic_prof up = ix.subset_direction('asc') down = ix.subset_directio...
cgrdn/argo-sci
src/pac-provor/initial_plot.py
initial_plot.py
py
951
python
en
code
0
github-code
6
3901695878
from parse import parse import pygame from pygame.locals import * from cube import Cube from const import * from pygame.math import Vector3 from utils import * from drawable_chunk import DrawableChunk from hero import Hero from level import * class Level(pygame.sprite.Sprite): def __init__(self): super(...
odrevet/isometric-map
level.py
level.py
py
5,207
python
en
code
0
github-code
6
71578033787
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Simple check list from AllenNLP repo: https://github.com/allenai/allennlp/blob/master/setup.py To create the package for pypi. 1. Change the version in __init__.py, setup.py as well as docs/source/conf.py. 2. Commit these changes with the message: "Release: VERSION...
langfield/asta
setup.py
setup.py
py
2,854
python
en
code
14
github-code
6
14870918627
import logging def initLogging(): # Use simple logging in this file # See whether I can seperate logging from this program and my library logging.basicConfig(filename='test_logging.log',level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%Y%m%d-%H%M%S') logger = logging.getLogger('...
qiuwch/tenon
test/test_logging.py
test_logging.py
py
934
python
en
code
9
github-code
6
72532713149
from pathlib import Path from .code_description import CodeDescriptionParams, CodeDescriptionXLSXDocument from .dataset_description import ( DatasetDescriptionParams, DatasetDescriptionXLSXDocument, ) from .manifest import ManifestXLSXDocument def write_xlsx_files( base_path: Path, dataset_descriptio...
ITISFoundation/osparc-simcore
services/web/server/src/simcore_service_webserver/exporter/_formatter/xlsx/writer.py
writer.py
py
892
python
en
code
35
github-code
6
16705170564
from django.shortcuts import render, redirect from .models import Todo from .forms import TodoForm def tasks_list(request): todos = Todo.objects.all() context = {'todos': todos} return render(request, 'tasks_list.html', context) def add_todo(request): if request.method == 'POST': form = Todo...
Chikitonik/DI_Bootcamp
Week_12_PY/Day2/exercises_xp/todo_project/todo_list/todos/views.py
views.py
py
622
python
en
code
0
github-code
6
31546382074
from functools import reduce def main(): # one liner functions culc_sum = lambda number_list: sum(number_list) check_palindrome = lambda number: str(number) == str(number)[::-1] factorial = lambda number: reduce((lambda a, b: a * b), range(1, number + 1)) # check functions print(culc_sum([1, ...
lidorelias3/Lidor_Elias_Answers
python/One Liners/OneLiners.py
OneLiners.py
py
437
python
en
code
0
github-code
6
42560466022
# Sparse Search: Given a sorted array of strings that is interspersed with empty strings, write a # method to find the location of a given string. def sparse_search(l, item): def search(start, end): mid = start + (end - start) // 2 if l[mid] == "": radius = 1 while l[mid] ==...
JSchoreels/CrackingTheCodingInterview
Chapter_10_SortingAndSearching/ex_10_5_SparseSearch.py
ex_10_5_SparseSearch.py
py
1,077
python
en
code
0
github-code
6
1199044805
import copy import time class Krpsim: def __init__(self, agent, delay, verbose, random=False): self.inventory = [] self.agent = agent.copy() self.delay = delay self.stock = (agent.stock) self.verbose = verbose self.random = random @property def stock(self):...
jmcheon/krpsim
Krpsim.py
Krpsim.py
py
5,278
python
en
code
0
github-code
6
24854584741
# -*- coding: utf-8 -*- import copy class Population(): """ Hold relevant information and bookkeeping functions for a population. """ def __init__(self, pop_name, ea_mu, ea_lambda, dmax_init, dmax_overall, parent_selection, overselection_top, p_m, survival_selection, t...
dennisgbrown/pacman-competitive-coevolutionary-genetic-programming
code/population.py
population.py
py
5,791
python
en
code
0
github-code
6
25349797554
# Juhusliku valiku valimiseks importige arvutisse juhuslik teek import random # Valikute loend options = ["kivi", "paber", "käärid"] # Funktsioon mängu mängimiseks def play_game(): # Arvuti teeb juhusliku valiku computer_choice = random.choice(options) # Kasutaja teeb valiku user_choice = input("Vali...
Joosepi/ulesanned
yl22.py
yl22.py
py
985
python
et
code
0
github-code
6
14177896732
"""Reads parameters of received http request""" import http.client as http_client import logging from typing import Optional import azure.functions as func from .custom_error import DownloadBlobError log = logging.getLogger(name="log." + __name__) def main(req: func.HttpRequest, params_list: Optional[list] = None)...
wieczorekgrzegorz/ksef-krportal-communication
modules/download_blob/modules/read_params.py
read_params.py
py
1,531
python
en
code
0
github-code
6
22329982080
import imp import discord from discord.ext import commands import json import os from os import listdir from os.path import isfile, join from datetime import datetime import subprocess from discordLevelingSystem import DiscordLevelingSystem import aiosqlite def micsid(ctx): return ctx.author.id == 481377376475938...
micfun123/Simplex_bot
cogs/micsid.py
micsid.py
py
9,632
python
en
code
24
github-code
6
18995573707
import os os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" from paddleocr import PaddleOCR,draw_ocr # Paddleocr supports Chinese, English, French, German, Korean and Japanese. # You can set the parameter `lang` as `ch`, `en`, `fr`, `german`, `korean`, `japan` # to switch the language model in order. ocr = PaddleOCR(use_ang...
tota1Noob/autoBookmarkGen4PDF
moduleTryouts/ocrTest.py
ocrTest.py
py
983
python
en
code
1
github-code
6
73955138107
from tkinter import * from PIL import Image, ImageDraw from src.Model import Model b1 = "up" xold, yold = None, None image1, drawimg = None, None model = Model() def create_lines(canv): canv.create_line(30, 0, 30, 140, smooth=TRUE, fill="red", width="1") canv.create_line(110, 0, 110, 140, smooth=TRUE, fill="r...
Freyb/LegoAI-homework
src/Gui.py
Gui.py
py
2,185
python
en
code
0
github-code
6
24133449429
#!/usr/bin/env python import argparse import csv import logging import math import sys import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from pylab import rcParams def plot_bar(data_fh, target, xlabel, ylabel, zlabel, title, x_label, y_label, x_order, y_order, fig_width, fig...
supernifty/plotme
plotme/bar.py
bar.py
py
7,407
python
en
code
0
github-code
6
44551517900
import numpy as np # this matrix will store the data labels = np.array ([]) # and this vector will store the labels points = np.array ([]) # open up the input text file with open('bc.txt') as f: # # read in the lines and init the data and labels lines = f.readlines () labels = np.zeros (len (line...
cjdiaz98/Comp330_HW4
SVM.py
SVM.py
py
8,225
python
en
code
0
github-code
6
18520546657
import tensorflow as tf class DoubleConvolutionBlock(tf.keras.layers.Layer): def __init__(self, filter, layer_name): super(DoubleConvolutionBlock, self).__init__(name="double_conv_3x3_" + layer_name) self.filter = filter self.pool = tf.keras.layers.MaxPool2D((2, 2)) self.layers = [...
KushGabani/Biomedical-Image-Segmentation
unet.py
unet.py
py
3,501
python
en
code
1
github-code
6
22100947365
import sys n,k=map(int,sys.stdin.readline().split()) trees=list(map(int,sys.stdin.readline().split())) start,end=1, max(trees) while start<=end: mid=(start+end)//2 sum=0 for i in trees: if i>=mid: sum+=i-mid if sum>=k: start=mid+1 else: end=mid-1 print(end)
dhktjr0204/beakjoon
이분탐색/2805.py
2805.py
py
318
python
en
code
0
github-code
6
24628062484
import random sproby=1 Vgadav=False s=random.randint(1,100) print('Ia zagadav chyslo. Sprobuy ugadaty ') a=int(raw_input()) while (sproby<9) and (Vgadav==False) : sproby=sproby+1 if a>s : print('Zabagato') if a<s : print('Zamalo') if a==s : Vgadav=True else: a=int(raw_input('Sprobuy shche raz, spro...
Nahtigal/PythonStudy
STR2/Rand.py
Rand.py
py
482
python
en
code
0
github-code
6
38714648302
from rest_framework import serializers from .models import Animal import serializer_company class AnimalSerializer(serializers.HyperlinkedModelSerializer): company = serializer_company.CompanySerializer() class Meta: model = Animal fields = [ 'id', 'name', ...
pohara9720/lma-python
lma/api/serializer_animal.py
serializer_animal.py
py
591
python
en
code
0
github-code
6
31126427233
from gpiozero import DigitalInputDevice import time class EncoderCounter(object): def __init__(self,pin_number,side): self.side = side self.test_mode = False self.pulse_count = 0 self.device = DigitalInputDevice(pin=pin_number) self.device.pin.when_changed = self.count_pulses self.previous = ...
gregorianrants/legobot-7
Encoder.py
Encoder.py
py
1,404
python
en
code
1
github-code
6
21569497560
#!/usr/bin/env python """ Script to: Extract 3D images from a 4D image and then extract one selected slice from each of these 3D images and combine them as a gif. """ # Author: Bishesh Khanal <bishesh.khanal@inria.fr> # Asclepios INRIA Sophia Antipolis import subprocess import sys import argparse as ag import ...
Inria-Asclepios/simul-atrophy
scripts/extractSliceVideoFrom4d.py
extractSliceVideoFrom4d.py
py
4,284
python
en
code
7
github-code
6
43449602370
#!/usr/bin/env python3 import re import json import urllib.request import pymysql.cursors def ipToCountry(ip): url = 'http://api.ipstack.com/' + ip + '?access_key=dfe38edcd4541577119d91e7053a584a' data = urllib.request.urlopen(url).read().decode("utf-8") json_data = json.loads(data) if not json_data['country_name...
VadimAspirin/usml
back/log_mapper.py
log_mapper.py
py
9,005
python
en
code
0
github-code
6
9638599695
# this class to get user information from user input class GetUserInfor: def __init__(self): print("""Welcome to Elena's Flight Clue.\n We find the best flight deals and email you. """) self.first_name = input("What is your first name?\n").rstrip() self.last_name...
na-lin/100-days-of-Python
day39-Flight-deal-Finder/get_user_information.py
get_user_information.py
py
769
python
en
code
0
github-code
6
14779367237
import adsk.fusion import unittest # note: load_tests is required for the "pattern" test filtering functionality in loadTestsFromModule in run() from fscad.test_utils import FscadTestCase, load_tests from fscad.fscad import * class Builder2DTest(FscadTestCase): def test_line_to(self): builder = Builder2...
JesusFreke/fscad
tests/builder2d_test.py
builder2d_test.py
py
1,550
python
en
code
44
github-code
6
44083406715
# -*- coding: utf-8 -*- ## Add uid to data gathered from qMp nodes in GuifiSants ## http://dsg.ac.upc.edu/qmpsu/index.php ## meshmon-format.py ## (c) Llorenç Cerdà-Alabern, May 2020. ## debug: import pdb; pdb.set_trace() import json cache = {} graph = [] tabs = {} def find_node_by_address(d, k, v): """ find ...
llorenc/meshmon-parser
meshmon-format.py
meshmon-format.py
py
4,474
python
en
code
0
github-code
6
19475609630
from django.apps import AppConfig from django.conf import settings import os import joblib class SentimentConfig(AppConfig): name = 'sentiment' path = os.path.join(settings.MODELS, 'models.p') path_emosi = os.path.join(settings.MODELS, 'models_emotion.p') path_general = os.path.join(settings.MODELS, ...
kholiqcode/skripsi
sentiment/apps.py
apps.py
py
927
python
en
code
0
github-code
6
40662041520
import os from tkinter import * class AuroraOS: def __init__(self, master): self.master = master master.title("AuroraOS") # GUI elementy self.label = Label(master, text="Witaj w AuroraOS!") self.label.pack() self.dir_button = Button(master, text="DIR"...
Github673/Moje-Aplikacje
Python/System Operacyjny.py
System Operacyjny.py
py
3,312
python
en
code
1
github-code
6
7047537895
# import cv2 # # videoCapture = cv2.VideoCapture("/home/haoyu/yuhao_video/a827.avi") # # # # fps = videoCapture.get() # # size = (int(videoCapture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)), # # int(videoCapture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT))) # # # # # videoWriter = cv2.VideoWriter('./data/video_plane.avi',) ...
ylltest/myscripts-github
traffic_lights/new_pil_pd.py
new_pil_pd.py
py
6,966
python
en
code
0
github-code
6
8201488763
from flask import render_template, redirect, url_for from flask_login import login_user, logout_user, current_user from . import home from ..models import User, Account, Role, Course from ..forms import LoginForm, RegisterForm from sha_training_app import db import datetime @home.route('/') def homepage(): course...
ScottishHD/training_site
sha_training_app/_home/views.py
views.py
py
2,385
python
en
code
0
github-code
6
19108144876
import colors import info from icon_path import icon_path from tooltip import Tooltip from scan_media_window import ScanMediaWindow from ingest_window import IngestWindow from open_window import OpenWindow from info_window import InfoWindow try: import tkinter except ImportError: import Tkinter as tkinter clas...
NPS-DEEP/SectorScope
python/menu_view.py
menu_view.py
py
4,423
python
en
code
11
github-code
6
26038693036
from __future__ import annotations import logging import os import re import textwrap from collections import defaultdict from dataclasses import dataclass from pants.backend.codegen.protobuf.protoc import Protoc from pants.backend.codegen.protobuf.target_types import ( AllProtobufTargets, ProtobufGrpcToggleF...
pantsbuild/pants
src/python/pants/backend/codegen/protobuf/go/rules.py
rules.py
py
25,015
python
en
code
2,896
github-code
6
9304520532
from rest_framework.generics import GenericAPIView from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import BasePermission from rest_framework import status from game.serializers import GameSerializer, TileSerializer, NextMoveSerializer from game.mode...
earlyche/gomoku
backend/game/views.py
views.py
py
4,210
python
en
code
0
github-code
6
24922743914
import time import os import sys SDK_HOME_PATH = os.path.dirname(os.path.abspath(__file__)) + '/../../' sys.path.append(SDK_HOME_PATH) up_dir = os.path.dirname(os.path.abspath(__file__)) + '/../' sys.path.append(up_dir) from display.lcd import LCD as LCD from ubo_keypad import * # Might have to revisit this form of ...
ubopod/ubo-sdk
ubo_keypad/examples/keypad_example_scroll.py
keypad_example_scroll.py
py
2,605
python
en
code
1
github-code
6
71765759867
""" REPSVM Agresores v3, esquemas de pydantic """ from pydantic import BaseModel from lib.schemas_base import OneBaseOut class RepsvmAgresorOut(BaseModel): """Esquema para entregar agresores""" id: int | None distrito_id: int | None distrito_clave: str | None distrito_nombre: str | None dist...
PJECZ/pjecz-plataforma-web-api-new
plataforma_web/v3/repsvm_agresores/schemas.py
schemas.py
py
824
python
es
code
0
github-code
6
1826616432
import cv2 import matplotlib.pyplot as plt import numpy as np from skimage.measure import label from skimage.io import imread, imshow def read_image(url): imagem = cv2.cvtColor(imread(url), cv2.COLOR_RGB2HSV) return imagem def apply_mask(imagem): x = imagem.shape[0] y = imagem.shape[1] mask = np....
EricaFer/Nudity-Detection
utils/preprocessing.py
preprocessing.py
py
1,487
python
pt
code
0
github-code
6
70205052348
import os import argparse import sys import warnings from pathlib import Path warnings.filterwarnings('ignore') import torch import torchvision as tv import pytorch_lightning as pl import webdataset as wds from resnet_sagemaker.models import ResNet from resnet_sagemaker.callbacks import PlSageMakerLogger, ProfilerCall...
johnbensnyder/resnet-sagemaker
pytorch/train.py
train.py
py
4,937
python
en
code
2
github-code
6
72960120187
import string def subtract(d1, d2): res = dict() for key in d1: if key not in d2: res[key] = None return res a = open('throughtelescope.txt') b = open('word1.txt') #c = subtract(a, b) #for word in c.keys(): #print(word) #print(subtract(a, b)) def linecount(filename): count = 0 for ...
derinsola01/Projects
subtractwords.py
subtractwords.py
py
414
python
en
code
0
github-code
6
29572346979
from __future__ import annotations from typing import TYPE_CHECKING, Any, Literal from transformers import AutoTokenizer from partial_tagger.data.collators import TransformerCollator from partial_tagger.encoders.transformer import ( TransformerModelEncoderFactory, TransformerModelWithHeadEncoderFactory, ) fr...
yasufumy/pytorch-partial-tagger
src/partial_tagger/utils.py
utils.py
py
1,230
python
en
code
1
github-code
6
7672099342
import random class Vertices: def __init__(self,x,y, volumePedido, valorPedido, qtdPacotes): self.volumePedido = volumePedido self.valorPedido = valorPedido self.qtdPacotes = qtdPacotes self.x = x self.y = y def __str__(self): return str(self.v) + " " + str(sel...
LuisFelypeFioravanti/TrabalhoGrafos
classes.py
classes.py
py
736
python
pt
code
0
github-code
6
36721611160
import torch from torch import nn from modules import ConvSC, Inception # stride를 만들어내는 모듈.. def stride_generator(N, reverse=False): strides = [1, 2]*10 if reverse: return list(reversed(strides[:N])) else: return strides[:N] # N_S개 만큼 Stride를 생성한 후, ConvSC 생성해서 # 총 N_S의 깊이를 가진 Encoder 모듈 생성. class Encoder...
J-PARK11/Video_Prediction_using_SimVP
model.py
model.py
py
4,304
python
en
code
0
github-code
6
42442738126
from django.shortcuts import render from .models import Twit,Company import datetime from django.contrib.auth.mixins import LoginRequiredMixin from django.views import View from django.http import HttpResponse,HttpResponseRedirect,Http404 import jdatetime from django.db.models import Q # new import datetime # Create y...
mhsharifi96/sursiz_ir
backend/bors/views.py
views.py
py
5,221
python
en
code
3
github-code
6
39556012979
# -*- coding: utf-8 -*- """ Created on Sun Aug 12 10:37:33 2018 @author: Gerardo Cervantes """ import xml.etree.cElementTree as ET from src.coordinates import Coordinates from src.hotkeys import Hotkeys class SharedPreferences(): COORDINATES_TAG = 'coordinates' SPLIT_TAG = 'split_key' RESET_TAG = '...
gcervantes8/Star-Classifier-For-Mario-64
src/shared_preferences.py
shared_preferences.py
py
3,050
python
en
code
8
github-code
6
111612310
import json f = open('dados.json') Dados = json.load(f) Dados = [x for x in Dados if x['valor'] > 0] menor = float("inf") #menor faturamento diário for x in Dados: atual = x['valor'] if(menor > atual): menor = atual print('O menor valor de faturamento ocorrido em um dia do mês foi de ', menor) #maior fatu...
CaioPyro/Target_Sistemas
Faturamento/main.py
main.py
py
890
python
pt
code
0
github-code
6
6742136861
import numpy as np import cv2 cap = cv2.VideoCapture(0) faceCascade = cv2.CascadeClassifier("face.xml") while(True): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here gray = frame # find face # Detect faces in the image faces = faceCascade.detectMu...
khanab85/FaceDetectors
start.py
start.py
py
866
python
en
code
0
github-code
6