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
9457059118
""" 1679. Max Number of K-Sum Pairs You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array. Example 1: Input: nums = [1,2,3,4], k = 5 Outpu...
juliazakharik/ML_algorithms
algorithms/WEEK5/Max Number of K-Sum Pairs.py
Max Number of K-Sum Pairs.py
py
1,261
python
en
code
1
github-code
36
26697753222
# INPUTS items_total = int(input("Enter the amount of items you are paying for: ")) first_item = 10.95 remaining_item = (items_total - 1 ) * 2.95 if items_total == 1 : print("You have purchased 1 item and the shipping fee for this item is $" , first_item , ".") elif items_total > 1 : print("You have purchase...
ehan77/Wave-3
shipping calculator.py
shipping calculator.py
py
484
python
en
code
0
github-code
36
9791587429
from django.shortcuts import render, redirect from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from task.models import Task, TaskImage from apiApp.serializers import TaskSerializer, TaskImageSerializer from rest_framewo...
osmangony01/DJango_task_RestAPI
apiApp/views.py
views.py
py
2,133
python
en
code
0
github-code
36
42683425330
from flask import Flask, Response, render_template import os from record_sound import RecordingVoice import json import pyaudio from array import array import time import shutil import numpy as np from datetime import datetime WAVE_PATH = 'data/waves' app = Flask(__name__) if not os.path.isdir(WAVE_PATH): os.mak...
Maryia-M/MSI_Project
app.py
app.py
py
2,460
python
en
code
0
github-code
36
8192799474
# -*- utf-8 -*- ######################################## # PSF license aggrement for wsgiapp.py # Developed by Ivan Rybko # WSGIApp ######################################## import queue from operator import concat class WSGIApp: def __init__(self, env, callback): self.getqueue = queue.Queue() ...
irybko/pyclasses
wsgiapp.py
wsgiapp.py
py
5,134
python
en
code
0
github-code
36
33168623479
from numpy import * import pandas as pd def stumpClassify(dataMatrix,dimen,threshVal,threshIneq): #按列数创造一个类别估计数组,初始值为1 retArr=ones((shape(dataMatrix)[0],1)) #第dimen列的值小于/大于threshVal置-1,分类准则 if threshIneq == 'lt': retArr[dataMatrix[:,dimen]<=threshVal] = -1.0 else: retArr...
Kwrrwytin/machine_learning_assignment
main.py
main.py
py
10,564
python
en
code
0
github-code
36
20250127196
# -*- coding: utf-8 -*- # Не работали русские буквы import sys sys.path.append("/Users/a18826700/Library/Python/3.9/lib/python/site-packages") import requests import time import datetime from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager import math import random import telebot from...
sashka0264/data-science
00_PYTHON/pynder.py
pynder.py
py
7,214
python
en
code
1
github-code
36
27022624529
import re from itertools import zip_longest from parso.python import tree from jedi import debug from jedi.inference.utils import PushBackIterator from jedi.inference import analysis from jedi.inference.lazy_value import LazyKnownValue, LazyKnownValues, \ LazyTreeValue, get_merged_lazy_value from jedi.inference.n...
davidhalter/jedi
jedi/inference/arguments.py
arguments.py
py
12,218
python
en
code
5,554
github-code
36
74307652262
import numpy as np import pandas as pd import sklearn as skl import matplotlib.pyplot as plt plt.close('all') import warnings warnings.filterwarnings('ignore') from sklearn.model_selection import train_test_split from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import cross_val_predict f...
elizabethwyss/EECS731MajorLeagues
src/src.py
src.py
py
2,127
python
en
code
0
github-code
36
30981798805
#!/usr/bin/env python # <bitbar.title>Countdown</bitbar.title> # <bitbar.version>v2.0</bitbar.version> # <bitbar.author>Pere Albujer</bitbar.author> # <bitbar.author.github>P4R</bitbar.author.github> # <bitbar.desc>Shows countdown of established date.</bitbar.desc> # <bitbar.image>https://cloud.githubusercontent.com/a...
damncabbage/dotfiles
macOS/BitBar/Plugins/Time/countdown.1s.py
countdown.1s.py
py
3,243
python
en
code
3
github-code
36
24065781906
import pytest from tests.utils import asyncio_patch, AsyncioMagicMock from gns3server.controller.gns3vm import GNS3VM from gns3server.controller.gns3vm.gns3_vm_error import GNS3VMError @pytest.fixture def dummy_engine(): engine = AsyncioMagicMock() engine.running = False engine.ip_address = "vm.local" ...
vieyahn/docker-cisco-lab
gns3server/tests/controller/test_gns3vm.py
test_gns3vm.py
py
2,760
python
en
code
0
github-code
36
12626750581
# Python standard library import sys sys.path.append('./../pyqtgraph') # Scipy import matplotlib.backends.backend_qt4agg import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.patches import Polygon from mpl_toolkits.basemap import Basemap import numpy as np # PyQt import PyQt4.QtCore import PyQt4...
tphinkle/sea_ice
qt_app/view/view.py
view.py
py
14,067
python
en
code
0
github-code
36
34216650238
# -*- coding: utf-8 -*- """ Created on Wed Jan 13 10:33:10 2021 @author: Administrator """ import numpy as np def find_bad_chans(SS): if SS['bad_EMG_elecs'].size > 0: SS['bad_EMG_chans'] = (np.any(np.transpose(SS['EMG_diff_matrix'])[SS['bad_EMG_elecs'],:], axis=0) .nonzero(...
uuneuralengineeringlab/XipppyServer
COB_Python/feedbackdecode/find_bad_chans.py
find_bad_chans.py
py
491
python
en
code
4
github-code
36
37405394997
from regression_tests import * class TestUpxshit(Test): settings = TestSettings( tool='unpacker', input=[ 'fact_rec.ex', 'pbmsrch_max.ex' ] ) def test_scrambler_upxshit(self): assert self.unpacker.succeeded assert self.unpacker.output.contain...
avast/retdec-regression-tests
tools/unpacker/upx/scramblers/upxshit/test.py
test.py
py
344
python
en
code
11
github-code
36
6172596021
from Token import Token from TokenType import TokenType import re token_type_dictionary = { 'KEY_WORD': TokenType('KEY_WORD', 'Var'), 'CONST': TokenType('CONST', '[0-9]*'), 'IDENTIFIER': TokenType('IDENTIFIER', '[a-zA-Z]*'), 'SEMICOLON': TokenType('SEMICOLON', ';'), 'COMMA': TokenType('COMMA', ',')...
qwertyjack12/python_translator_CS
Lexer.py
Lexer.py
py
1,627
python
en
code
0
github-code
36
24377656
mod = 1000000007 def pow(n, a): if a == 1: return n % mod if a % 2 == 1: b = pow(n, a//2) return (b*b*n) % mod b = pow(n, a//2) return b*b n, a = map(int, input().split()) b = pow(n, a+1) c = pow(n-1, a) ans = (n-2)*(b-c*n)+b ans %= mod print(ans)
kmgyu/baekJoonPractice
2023 DPC Open Contest/F.py
F.py
py
289
python
es
code
0
github-code
36
31324284158
#!/usr/bin/python3 import sqlite3 from itertools import chain conn = sqlite3.connect('vexdb.db') curs = conn.cursor() sql = 'INSERT INTO IRType(id, btype, nbits) VALUES (?,?,?)' first=True value=0; with open('irtypes.lst') as f: for line in f: line = line.rstrip() if first: # Ity_INV...
EmmetCaulfield/valgrind
arinx/hacking/insert-irtypes.py
insert-irtypes.py
py
664
python
en
code
0
github-code
36
4254763114
""" Problem Statement Given an array of unsorted numbers and a target number, find a triplet in the array whose sum is as close to the target number as possible, return the sum of the triplet. If there are more than one such triplet, return the sum of the triplet with the smallest sum. Example 1: Input: [-2, 0, 1, 2]...
blhwong/algos_py
grokking/two_pointers/triplet_sum_close_to_target/main.py
main.py
py
1,307
python
en
code
0
github-code
36
11519350312
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from functools import wraps import logging from numbers import Number from time import time from types import FunctionType from lab import B from plum import Dispatcher, Self, Referentiable __all__ = [] _dispatch = Dispatcher(...
pb593/stheno
stheno/util.py
util.py
py
1,175
python
en
code
null
github-code
36
27551438109
#!/usr/bin/env python3 import argparse import dgl import numpy as np import pandas as pd import pickle as pkl import torch import torch.nn.functional as F import ipdb from gnn.link_prediction import LinkPredictor, compute_lp_loss from gnn.node_classification import NodeClassifier, NodeClassifierConv # if torch.cuda...
EpistasisLab/qsar-gnn
main.py
main.py
py
13,805
python
en
code
2
github-code
36
32006328277
import Chat import nltk from nltk.corpus import wordnet as wn #nltk.download() #!/usr/bin/python def getSynonyms(words): synonyms = [] for word in words: for s in wn.synsets(word): for l in s.lemmas(): synonyms.append(l.name()) return set(synonyms) # findPersonKeywo...
Ryanlys/310_A2
PersonOrLocation.py
PersonOrLocation.py
py
4,273
python
en
code
1
github-code
36
42229482357
import torch import torchvision.ops as tv input_tensor = torch.rand(1000, 4) scores = torch.rand(1000, 59) #print(input_tensor) #print(scores[1]) def NMS_cal(input_tensor, scores): NMS_group = [] for i in range(59): confidscore, _ = torch.max(scores, dim=1) catargmax = torch.argmax(scores, di...
RasmusNylander/guacamole
filter_for_mAP.py
filter_for_mAP.py
py
605
python
en
code
0
github-code
36
36156312492
# coding:utf-8 """ @author:hanmy @file:ParaEsti_N.py @time:2019/04/24 """ import numpy as np import matplotlib.pyplot as plt from gmm import GMM # 计算steps次参数估计的权重值的均值和方差 def pi_N(N, pi, mean_1, cov_1, mean_2, cov_2, steps): gmm = GMM(N, pi, mean_1, cov_1, mean_2, cov_2) pi_steps = np.zeros(shape=steps) # ...
hanmy1021/NLP
gmm/ParaEsti_N.py
ParaEsti_N.py
py
2,130
python
en
code
6
github-code
36
75186130022
import argparse import logging import multiprocessing as mp import os import pytz import shutil from datetime import datetime from lego_prover.env.chromas import ChromaBridge from lego_prover.evolver import Evolver from lego_prover.prover import Prover import lego_prover.utils as U from openai_key import * parser = a...
wiio12/LEGO-Prover
run_multiprocess.py
run_multiprocess.py
py
6,373
python
en
code
9
github-code
36
949939402
pkgname = "fluidsynth" pkgver = "2.3.4" pkgrel = 0 build_style = "cmake" configure_args = [ "-DLIB_SUFFIX=", "-DDEFAULT_SOUNDFONT=/usr/share/soundfonts/default.sf2", ] make_check_target = "check" hostmakedepends = ["cmake", "ninja", "pkgconf"] makedepends = [ "glib-devel", "pipewire-devel", "pipewir...
chimera-linux/cports
main/fluidsynth/template.py
template.py
py
1,025
python
en
code
119
github-code
36
14312689350
from django.urls import path from .views import * urlpatterns = [ path('test/', test, name="test"), # HttpResponse-------------------------------------------------------------------- path('test-1/', TestViewClass_1.as_view(), name="TestViewClass_1"), path('test-2/', TestViewClass_2.as_view(), name="Tes...
rakib1515hassan/Class-Base-View-Project
viewtest/urls.py
urls.py
py
3,041
python
en
code
0
github-code
36
9145766841
import os import mysql.connector as mariadb class dbConn(object): """description of class""" ID_READY = 'Ready' ID_READY_COD = '0' ID_RUNNING = 'Running' ID_RUNNING_COD = '1' ID_PAUSED = 'Paused' ID_PAUSED_COD = '2' ID_FINISHED = 'Finished' ...
rchavesr/Bioinformatics
db.py
db.py
py
4,017
python
en
code
0
github-code
36
29466618583
#!/usr/bin/env python # -*- encoding: utf-8 -*- from pron91pkg import httputil from bs4 import BeautifulSoup from pron91pkg import disk import requests import shutil import os import time from pron91pkg.FakeHeader import FakeHeader # 1.get title #2.get html5 m3u8 #3.download ts files from m3u8 #4.merge m3u8 to one fil...
Crazyalllife/pron91
yezmw/yezmw.py
yezmw.py
py
5,298
python
en
code
1
github-code
36
15476948155
from __future__ import division, print_function, absolute_import import pytest from faker.providers import BaseProvider from hypothesis import given from hypothesis.strategytests import strategy_test_suite from hypothesis.internal.debug import minimal from hypothesis.extra.fakefactory import fake_factory class Kitt...
LyleH/hypothesis-python_1
tests/fakefactory/test_fake_factory.py
test_fake_factory.py
py
2,163
python
en
code
1
github-code
36
41249727801
#!/usr/bin/env python3 #-*- encoding: UTF-8 -*- def main(): preco = float(input("Informe o preço da mercadoria: R$ ")) desconto = float(input("Percentual de desconto: ")) print("Preço original: R$ %.2f" %preco) print("Desconto: R$ %.2f" %(preco * (desconto / 100))) print("Preço final: R$ %.2f" %(pr...
luizfelipe1914/python4zumbis
Lista01/Q05.py
Q05.py
py
397
python
pt
code
0
github-code
36
40885437398
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf # pylint: disable=no-name-in-module from tensorflow.python.framework import tensor_shape from tensorflow.python.keras.layers import Wrapper from tensorflow.python.layers.convolutional im...
IntelLabs/nlp-architect
nlp_architect/models/temporal_convolutional_network.py
temporal_convolutional_network.py
py
16,647
python
en
code
2,921
github-code
36
72692460583
#!/usr/bin/env python3 # pyre-strict import asyncio import logging import sys from typing import Any, Union import click __version__ = "0.6.9" LOG: logging.Logger = logging.getLogger(__name__) def _handle_debug( ctx: Union[click.core.Context, None], param: Union[click.core.Option, click.core.Parameter, No...
cooperlees/base_clis
py/base_cli.py
base_cli.py
py
1,315
python
en
code
2
github-code
36
18761978779
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: def iter(l1, l2, remain): if l1 ==...
ToddIsland/Leetcode_JS
1-10/2. Add Two Numbers.py
2. Add Two Numbers.py
py
664
python
en
code
0
github-code
36
33902538934
#!/usr/bin/python # -*- coding: utf-8 -*- """ @brief Precision and Recall @ref https://en.wikipedia.org/wiki/Precision_and_recall Modified from https://github.com/lyst/lightfm and https://github.com/jfkirk/tensorrec @author <ariel kalingking> akalingking@gmail.com """ import numpy as np import p...
akalingking/RecSys
metrics.py
metrics.py
py
1,793
python
en
code
1
github-code
36
13448911430
import logging import cv2 import numpy from inquire.detection.ButtonState import ButtonState from inquire.detection.RecognizedElement import RecognizedElement try: from robot.api.logger import info robot_logger = True except ImportError: robot_logger = False logging.basicConfig(level=logging.INFO) ...
Diyomee/Inquire
src/inquire/detection/TextElement.py
TextElement.py
py
3,930
python
en
code
0
github-code
36
34095148316
from selectivesearch import selective_search as ss def selective_search(image): """A wrapper for the selective_search function in the selectivesearch library with fixed parameters. Returns a set of tuples (x, y, w, h) corresponding to candidate locations of objects in the input image. """ reg...
jamesjiang52/Aperture
data/selective_search.py
selective_search.py
py
677
python
en
code
0
github-code
36
74579468262
from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import landing_page.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( landing_page.routing.websoc...
gitsh1t/vetrina_test
sitotest/routing.py
routing.py
py
422
python
en
code
0
github-code
36
40086649970
import os import bpy from mathutils import Vector import numpy as np import sys sys.path.append('.') from blender import BlenderWrapper class BlenderHelper(BlenderWrapper): def __init__(self): super().__init__() self.set_transparent_background() self.set_image_size(1800, 1090) ##...
luca-morreale/blender_rendering3d
source/blender_helper.py
blender_helper.py
py
5,728
python
en
code
0
github-code
36
34036888232
# Задание №7 import json with open("lesson_5_hw_77.json", "w") as j_file: with open("lesson_5_hw_7.txt", "r") as f_o: subjects = {} middle = {} k, o = 0, 0 line = f_o.read().split("\n") for i in line: i = i.split() profit = int(i[2]) - int(i[3]) ...
TBidnik/python
practicum.py
practicum.py
py
556
python
en
code
0
github-code
36
31371943053
def plot_heat_tree(heatmap_file, tree_file, output_file=None): ''' Plot heatmap next to a tree. The order of the heatmap **MUST** be the same, as order of the leafs on the tree. The tree must be in the Newick format. If *output_file* is specified, then heat-tree will be rendered as a PNG, otherwise...
voidabhi/python-scripts
heat-map.py
heat-map.py
py
2,563
python
en
code
1
github-code
36
74050045544
from parlai.core.params import ParlaiParser from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.worlds import create_task from parlai.utils.conversations import Conversations from parlai.utils.misc import TimeLogger import random import tempfile def setup_args(): """ Set up c...
facebookresearch/ParlAI
parlai/crowdsourcing/tasks/acute_eval/dump_task_to_acute_format.py
dump_task_to_acute_format.py
py
3,809
python
en
code
10,365
github-code
36
21365549144
import torch import numpy as np from dptb.dataprocess.processor import Processor from dptb.nnet.nntb import NNTB from dptb.nnsktb.sknet import SKNet from dptb.sktb.skIntegrals import SKIntegrals from dptb.sktb.struct_skhs import SKHSLists from dptb.hamiltonian.hamil_eig_sk_crt import HamilEig from dptb.utils.constants...
deepmodeling/DeePTB
dptb/nnops/nnapi.py
nnapi.py
py
12,168
python
en
code
21
github-code
36
11944953948
# -*- coding: utf-8 -*- """ Created on Mon May 09 08:58:28 2016 @author: Jonatan """ from __future__ import division from spider_plot_2 import * def p2h_spider(): """ Make a spider plot where the different scenarios are compared for different scenarios. """ d = Drawing(400, 400) sp = SpiderC...
GersHub/P2HSweden
Power2Heat/Python/Modules/Plot/plot_spider_2.py
plot_spider_2.py
py
708
python
en
code
0
github-code
36
30333812871
import cv2 import numpy as np img1 = cv2.imread('pratica02/cameraman.tif', cv2.IMREAD_UNCHANGED) img2 = cv2.imread('pratica02/morangos.tif', cv2.IMREAD_UNCHANGED) imgCinza = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) # python exibe em BGR => B=0 G=1 R=2 red2 = (img2[:, :, 2]) blue2 = (img2[:, :, 0]) green2 = (img2[:, :,...
Vicinius/digital-image-processing
pratica02/rgb-to-grayscale.py
rgb-to-grayscale.py
py
1,072
python
en
code
0
github-code
36
31705158569
from hx711 import HX711 from time import sleep, strftime from datetime import datetime, timedelta from datetime import timezone from output import Output import numpy import os import logging fileRW = Output() logger = logging.getLogger(__name__) class sensor: def __init__(self): # Sets up scales ...
tech4nature/HogPi
app/weight.py
weight.py
py
4,254
python
en
code
0
github-code
36
6273669923
import os from tests.e2e.terraform.alicloud.testing import _test_template root = os.path.dirname(os.path.abspath(__file__)) tf_plan_path = os.path.join(root, "main.tfplan") tpl = { "ROSTemplateFormatVersion": "2015-09-01", "Resources": { "alicloud_ecs_activation.example": { "Type": "ALIYU...
aliyun/alibabacloud-ros-tool-transformer
tests/e2e/terraform/alicloud/ecs_activation/test_template.py
test_template.py
py
718
python
en
code
16
github-code
36
22041191064
from matplotlib import pyplot as plt import scipy.stats as spstats from loomio import * from socialchoice import * from timeseries import * legend_fontsize = 7 formats = ['.-', 's-'] markersizes = [9, 5] class NetDelib(object): def __init__(self): self.plot_mean = False def plot_errorbar(s...
elplatt/Exp-Net-Delib
experiments/NetDelib-002/analysis/netdelib.py
netdelib.py
py
9,150
python
en
code
0
github-code
36
42154810648
# 무인도 여행 BFS from collections import deque dirs = [(0, 1), (0, -1), (-1, 0), (1, 0)] score = 0 def bfs(maps, visited, x, y): global score queue = deque() queue.append((x, y)) visited[x][y] = 0 score = int(maps[x][y]) while queue: x, y = queue.popleft() for d in dirs: ...
FeelingXD/algorithm
programers/154540-2.py
154540-2.py
py
1,279
python
en
code
2
github-code
36
17093369252
import itertools N, M = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) if (M != 0): cd = [list(map(int, input().split())) for _ in range(M)] else: cd = list(list()) groups = list(list()) for i in range(1, N + 1): conn_list = [item for item in cd if item[0...
kmdkuk/myAtCoder
acr106/b/main.py
main.py
py
1,414
python
en
code
0
github-code
36
13495728190
from flask import Flask from flask_restful import Api from helpers.crossdomain import * from messenger_webhook import MessengerWebhook application = Flask(__name__, template_folder='template', static_url_path='/static') application.config.from_object(__name__) application.config['SECRET_KEY'] = '1ex13eu103me91i-sdf' a...
joshwolff1/cs238-final-project
application.py
application.py
py
717
python
en
code
0
github-code
36
37360523175
import glob import re import traceback from pathlib import Path from typing import List, Union import fitz import utils from constants import cmd_output_path from loguru import logger def convert_to_image_pdf(doc_path: Union[str, List[str]], dpi: int = 300, page_range: str = "all", output_path: str = None): try: ...
kevin2li/PDF-Guru
thirdparty/convert.py
convert.py
py
11,219
python
en
code
941
github-code
36
73577908903
import ROOT from array import array def buildMedianProfile(h): """build the median profile""" medianGr = ROOT.TGraphAsymmErrors() medianGr.SetName('{}_medianprof'.format(h.GetName())) medianGr.SetLineWidth(2) medianGr.SetMarkerStyle(20) #median and 1 sigma quantiles xq = array('d', [0.16,0...
bfonta/HGCal
HGCalMaskResolutionAna/python/RootTools.py
RootTools.py
py
782
python
en
code
0
github-code
36
16486914039
# 라이브러리 import sys print(sys.argv) sys.exit() print(sys.path) print(sys.path.append("C:/Users/user/Desktop/python/chap05")) import pickle f = open("test.txt", 'wb') data = {1: 'python', 2: 'you need'} pickle.dump(data, f) f.close() import pickle f = open("test.txt", 'rb') data = pickle.load(f) print(data) import...
polkmn222/python
chap05/exam11.py
exam11.py
py
554
python
en
code
0
github-code
36
468491372
import torch from torch import nn from torch.utils.data import Dataset, DataLoader from ...base import device class RandomDataset(Dataset): def __init__(self, size, length): self.len = length self.data = torch.randn(length, size) def __getitem__(self, index): return self.data[index] ...
cdgyp/sparsity
codes/scripts/distributed/toy.py
toy.py
py
1,620
python
en
code
0
github-code
36
70118450985
from tkinter import Tk, StringVar, Label def set_keysym(event): keysym.set(event.keysym) root = Tk() root.bind('<Key>', set_keysym) keysym = StringVar() label = Label(root) label.configure(textvariable=keysym) label.pack() root.mainloop()
david-fong/tetris
keysym.py
keysym.py
py
250
python
en
code
3
github-code
36
70727262185
import boto3 import logging import os logger = logging.getLogger() logger.setLevel(logging.INFO) def str2bool(value): return value.lower() in ("True",True,"False",False) def lambda_handler(event, context): torun = event['torun'] if torun == "true": awsregion = os.environ['AWS_REGION'] ...
AlphaITSystems/dbrefresh
awssoldb-orchestrator-pkg-cloudformation/functions/awssoldb-CreateInstance.py
awssoldb-CreateInstance.py
py
7,794
python
en
code
0
github-code
36
19477973385
from student import Student from course import Course from teacher import Teacher import bisect import pickle # Opening students.dat to populate students[] -- if this throws an error for you, run initialize_data.py to fix it with open("students.dat", "rb") as fp: students = pickle.load(fp) # Opening teachers.dat ...
nguyenk98/Software-Engineering-Project
testStudents.py
testStudents.py
py
2,036
python
en
code
0
github-code
36
32468298278
from django.conf.urls import url from django.views.decorators.csrf import csrf_exempt from rest_framework.routers import DefaultRouter from users import views from .views import UserViewSet, custom_auth_token router = DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = router.urls urlpatterns += [ ...
faradzh/medilix
medilix/users/urls.py
urls.py
py
1,545
python
en
code
0
github-code
36
8195744930
#!/usr/bin/env python from time import gmtime, strftime import platform #import checks TMP_DIR = 'tmp' SMTP_TO = 'your@address.here' SMTP_FROM = platform.node() TIME = strftime('%Y-%m-%d %H:%M:%S', gmtime()) SUBJECT = dict() SUBJECT['socket'] = 'ERROR connecting to %s:%s' SUBJECT['url'] = 'ERROR getting URL %s' SUBJ...
lsgd/me
snoopmon/config.py
config.py
py
883
python
en
code
1
github-code
36
18891935528
porcentajealto=0 porcentajeintermedio=0 porcentajebajo=0 precio_boleta=100 contador=0 while contador <10: edad=float(input("Digite su edad: ")) if edad<5: print("No puede entrar") elif edad>=5 and edad <= 14: print("Tienes un 35% de descuento") descuento=0.35 porc...
ProfesionalKillr/Python
TallerQuiz/ejercicio5.py
ejercicio5.py
py
1,135
python
es
code
0
github-code
36
43701305099
from tkinter import * from errorMessage import ErrorMessage from asignarMedico import AsignarMedico import connection as con import customtkinter as ct class IngresoMedico: def __init__(self, parent): self.parent = parent self.win = Toplevel(parent) self.win.title("Ingreso Medico") ...
angelcast2002/proyecto2_BD_python
ingresoMedico.py
ingresoMedico.py
py
3,148
python
es
code
0
github-code
36
11671695671
import argparse class CommonArgParser(argparse.ArgumentParser): def __init__(self): super(CommonArgParser, self).__init__() self.add_argument('--model_name', default='TransE', choices=['TransE', 'TransE_l1', 'TransE_l2', 'TransR', 'RESCAL...
menjarleev/dgl-ke
python/dglke/util/argparser/common_argparser.py
common_argparser.py
py
11,343
python
en
code
null
github-code
36
75075550182
import torch import numpy as np from ..utils.decode import _nms, _topk, _topk_channel, _transpose_and_gather_feat def multi_pose_decode(heat, wh, kps, reg=None, hm_hp=None, hp_offset=None, K=100): batch, cat, height, width = heat.size() num_joints = kps.shape[1] // 2 # heat = torch.sigmoid(heat) # pe...
tteepe/CenterNet-pytorch-lightning
CenterNet/decode/multi_pose.py
multi_pose.py
py
4,647
python
en
code
58
github-code
36
18652487774
#!/usr/bin/python3 def exo6(): response = int(input("Please enter your number: ")) while response < 10 and response < 20: print("ok") if response < 10: print("« Plus petit ! »") elif response > 20: print("« Plus grand ! »") #exo6() def exo10(): age = int(...
Blakimy/poei-python
semaine_python/script.py
script.py
py
620
python
en
code
0
github-code
36
73118965864
import os import shutil import time def delete(path): if os.path.exists(path): while True: for d_path, d_names, f_names in os.walk(path): for f_name in f_names: f_path = os.path.join(d_path, f_name) if time.time() - os.path.getctime(f_pat...
IlyaOrlov/PythonCourse2.0_September23
Practice/platonova/lec_9.3.py
lec_9.3.py
py
764
python
en
code
2
github-code
36
72404328104
class EqRelation: def __init__(self, edges=()): self.vertices = {} self.count = 0 for a, b in edges: self.add_edge(a, b) def _query(self, key): if key not in self.vertices: self.vertices[key] = key self.count += 1 return key ...
jorendorff/advent-of-code
2018/25/part1.py
part1.py
py
2,123
python
en
code
3
github-code
36
16472178151
import argparse import hashlib import logging import time import spacy import config logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) class MEDLINESpacySents: def __init__(self, medline_abstracts, output_fname): self.medli...
IBM/aihn-ucsd
amil/preprocess/_2_spacy_sents.py
_2_spacy_sents.py
py
1,808
python
en
code
18
github-code
36
74494760743
# -*- coding: utf-8 -*- from selenium import webdriver from lxml import etree from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from urllib.parse import quote driver = webdriver.Chrome() def get_list_pa...
xieys/webSpider
bossSpider/crawler.py
crawler.py
py
2,342
python
en
code
0
github-code
36
28520967907
# Opus/UrbanSim urban simulation software. # Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from urbansim.functions import attribute_label from variable_functions import my_attribute_label ...
psrc/urbansim
urbansim/gridcell/number_of_households.py
number_of_households.py
py
1,751
python
en
code
4
github-code
36
10828915920
import heapq # 가장 낮은 스코빌지수가 K보다 크거나 같은 경우는 True def check(h,K): tmp = h[0] if tmp >= K: return True return False def solution(scoville, K): answer = 0 h = [] for i in scoville: heapq.heappush(h,i) while check(h,K) == False: # 모든 지수를 스코빌지수로 만들기위해 반복 수행 if...
choijaehoon1/programmers_level
src/test25.py
test25.py
py
836
python
ko
code
0
github-code
36
39930557336
class Stack: def __init__(self): self.l = [] self.min = [] def Push(self, x): self.l.append(x) if len(self.min) == 0: self.min.append(x) else: r = self.min[-1] self.min.append(min(x, r)) ...
sociallyencrypted/CSE101
Labs/Lab 11/MinimumStack.py
MinimumStack.py
py
1,015
python
en
code
0
github-code
36
38904370760
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from sklearn import metrics import math from helpers import one_hot_embedding, get_device from MutualInformation import MutualInformation def relu_evidence(y): return F.relu(y) def calc_ece_softmax(softmax, label, bi...
Tom-Liii/PostNet-ESD
metrics.py
metrics.py
py
5,593
python
en
code
0
github-code
36
70268090023
import cv2 # import opencv from PIL import Image,ImageFilter from PIL import ImageEnhance import matplotlib.image as mp import os, sys import http.client import json import ssl import urllib.parse from os.path import expanduser #获取图片清晰度 def getImageVar(imgPath): image = cv2.imread(imgPath); img2gray = cv2.cvtCo...
YukiXueyan/faceUP
testPhoto.py
testPhoto.py
py
3,156
python
en
code
0
github-code
36
11043698970
import pytest from RiceClassifier.config.configuration import ( ConfigurationManager, YAMLConfigReader, FilesystemDirectoryCreator ) from RiceClassifier.components.prepare_base_model import ( BaseModelLoader, BaseModelUpdater, FullModelPreparer ) from RiceClassifier.logger import logger from RiceClassifier.pipe...
nasserml/End-To-End_Rice-Classification-Project
tests/test_RiceClassifier/test_pipeline/test_stage_02_prepare_base_model.py
test_stage_02_prepare_base_model.py
py
2,303
python
en
code
0
github-code
36
74198666023
"""Example: Message instance conversion.""" from __future__ import annotations import importlib from typing import TYPE_CHECKING import numpy if TYPE_CHECKING: from typing import Any NATIVE_CLASSES: dict[str, Any] = {} def to_native(msg: Any) -> Any: # noqa: ANN401 """Convert rosbags message to native m...
cmrobotics/rosbags
docs/examples/use_with_native.py
use_with_native.py
py
1,573
python
en
code
0
github-code
36
18913918053
import string class Solution: def minDeletions(self, s: str) -> int: result = 0 seen = {0} for x in string.ascii_lowercase: count = s.count(x) while count and count in seen: count -= 1 result += 1 seen.add(count) ...
lancelote/leetcode
src/minimum_deletions_to_make_character_frequencies_unique.py
minimum_deletions_to_make_character_frequencies_unique.py
py
337
python
en
code
3
github-code
36
37900995282
# -*- coding: utf-8 -*- import scrapy import re from copy import deepcopy from biquge.items import BiqugeIndexItem, BiqugeDetailsItem class BookspiderSpider(scrapy.Spider): name = 'bookspider' allowed_domains = ['biquge.com.cn'] start_urls = [ 'http://www.biquge.com.cn/xuanhuan/', 'http://w...
silenterofsea/silenter_read_story
9999_some_tiny_program/biquge/biquge/spiders/bookspider.py
bookspider.py
py
7,200
python
en
code
0
github-code
36
38450874328
import numpy as np import scipy from scipy.linalg import expm, norm def rotx(t): """Rotation about the y-axis.""" c = np.cos(t) s = np.sin(t) return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) def roty(t): """Rotation about the y-axis.""" c = np.cos...
MerveKarali/3d-object-part-segmentation-with-simclr
augmentations/augmentations.py
augmentations.py
py
11,460
python
en
code
null
github-code
36
3383316091
class ListNode: def __init__(self, key=-1, val=-1, next=None): self.key = key self.val = val self.next = next class MyHashMap: def __init__(self): self.map = [ListNode() for i in range(1000)] def hashcode(self, key): return key % len(self.map) def put(s...
neetcode-gh/leetcode
python/0706-design-hashmap.py
0706-design-hashmap.py
py
1,031
python
en
code
4,208
github-code
36
39603770665
""" Module containing various functions I have found useful in assembling the feature vector. """ import numpy as np def combine_as_max(vector1, vector2): """ Combine two vectors and return a vector that has the maximum values from each vector compared pairwise. :param vector1: First list to compare ...
jeffharwell/viewpointdiversity
src/viewpointdiversitydetection/feature_vector_creation_utilities.py
feature_vector_creation_utilities.py
py
6,076
python
en
code
0
github-code
36
72167501223
#!/usr/bin/env python3 import sys import subprocess from pathlib import Path from cv19 import CV19ROOT def run_pylint(): """ Run the Pylint test on the module and some other files in the repository. Automatically ran on every pull request via GitHub actions. """ # Messages/warnings/errors to ena...
Queens-Physics/quaboom
test/linters/pylint.py
pylint.py
py
1,985
python
en
code
4
github-code
36
16032798991
from modeling.resnet import resnet50 import torch.nn as nn import torch.nn.functional as F import torch class fpn_module(nn.Module): def __init__(self, numClass): super(fpn_module, self).__init__() # Top layer self.toplayer = nn.Conv2d(2048, 256, kernel_size=1, stride=1, padding=0) # Reduc...
ShenZheng2000/Semantic-Guided-Low-Light-Image-Enhancement
modeling/fpn.py
fpn.py
py
5,489
python
en
code
76
github-code
36
15953309425
import os from typing import Dict from aiohttp_retry import Any from flask import Flask, request from langchain import PromptTemplate from twilio.twiml.messaging_response import MessagingResponse import json from langchain.llms import OpenAI from langchain.memory import ConversationSummaryBufferMemory from supabase i...
joseph-mcallister/motivate
flask-app/application.py
application.py
py
2,603
python
en
code
0
github-code
36
7557787218
import sys import io import os import copy def Run(input, output): readline = io.BytesIO( os.read( input, os.fstat(input).st_size ) ).readline N = int(readline()) grass = [None for _ in range(N)] for i in range(N): grass[i] = [int(i) for i in readline().split()] prefi...
chenant2017/USACO
Silver/2021 Feb/green.py
green.py
py
1,137
python
en
code
2
github-code
36
18665423985
""" Calculate L and T velocities from LL and LT backwalls. Raises ------ IndefiniteVelocityError Output ------ conf.d/30_block_velocities.yaml velocity_L.png velocity_T.png """ import logging import numpy as np import matplotlib.pyplot as plt import arim import arim.ray from arim.im.das import lanczos_interpolation...
nbud/arimtoolkit
arimtoolkit/measure_velocities_from_timetraces.py
measure_velocities_from_timetraces.py
py
6,801
python
en
code
0
github-code
36
27519507809
from flask import Flask,render_template,request,redirect,url_for import urllib import urllib.request from bs4 import BeautifulSoup import os import json import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') app = Flask(__name__) app.secret_key="flash message" @app.route('/') d...
mousaa32/web-scrapping
expat-coinAfrique.py
expat-coinAfrique.py
py
9,320
python
en
code
0
github-code
36
7024088458
import customtkinter class infoPage: def __init__(self, frame, mainColor, secondColor, thirdColor, fourthColor, textColor, openConvertPage): self.openConvertPage = openConvertPage self.create_page(frame, mainColor, secondColor, thirdColor, fourthColor, textColor) def create_page(self, frame, m...
LukaszButurla/xml-compiler-tkinter
ui/infoPage.py
infoPage.py
py
1,717
python
en
code
0
github-code
36
12487239210
""" Lists Advanced - Exercise Check your code: https://judge.softuni.bg/Contests/Practice/Index/1731#1 SUPyF2 Lists-Advanced-Exercise - 02. Big Numbers Lover Problem: You really like big numbers, so you always find a way to form one from numbers given to you You will receive a single line containing numbers s...
SimeonTsvetanov/Coding-Lessons
SoftUni Lessons/Python Development/Python Fundamentals September 2019/Problems And Files/16 EXERCISE LISTS ADVANCED - Дата 18-ти октомври, 1430 - 1730/02. Big Numbers Lover.py
02. Big Numbers Lover.py
py
685
python
en
code
9
github-code
36
43043002916
import cv2 import numpy as np import face_recognition cap = cv2.VideoCapture(0) success,imgUser = cap.read() imgUser = cv2.cvtColor(imgUser, cv2.COLOR_BGR2RGB) encodeUser = face_recognition.face_encodings(imgUser) cap = cv2.VideoCapture(0) while True: success,img = cap.read() imgS = cv2.resize(i...
SRA-V/Exam-Cheater
Cheater.py
Cheater.py
py
1,623
python
en
code
1
github-code
36
21881706345
""" Demonstrate a way to create URIs for tags in TiddlyWeb. At the moment this only allows for GET. """ import urllib from tiddlyweb.web.sendtiddlers import send_tiddlers from tiddlyweb.model.bag import Bag from tiddlyweb import control def init(config_in): config_in['selector'].add('/bags/{bag_name}/tags', GET...
tiddlyweb/tiddlyweb-plugins
tagview/tagview.py
tagview.py
py
1,807
python
en
code
12
github-code
36
28613148826
from PySide import QtCore, QtGui, QtNetwork class FortuneThread(QtCore.QThread): newFortune = QtCore.Signal(str) error = QtCore.Signal(int, str) def __init__(self, parent=None): super(FortuneThread, self).__init__(parent) self.quit = False self.hostName = '' self.cond = ...
pyside/Examples
examples/network/blockingfortuneclient.py
blockingfortuneclient.py
py
5,953
python
en
code
357
github-code
36
3522846328
""" 希尔排序: 希尔排序是基于插入排序的。插入排序对于前面部分已经有序的复杂度很低,如果全是乱序的则性能差。 1. 以一定的间隔进行比较,交换 2. 缩小间隔继续比较,直到间隔为1.执行完结束 """ def shell_sort(nums): length = len(nums) gap = length // 2 while gap: for i in range(gap, length): j = i while j >= gap and nums[j-gap] > nums[j]: nums[j-g...
CGdeepvoice/notes
算法与数据结构/排序/shell_sort.py
shell_sort.py
py
638
python
zh
code
0
github-code
36
39124528339
import datetime class Comment: def __init__(self,game,userName,description): self.userName = userName self.game = game self.date = str(datetime.datetime.now()) self.description = description def dump(self): return { 'name': self.userName, 'game': ...
eduardomep/SpartanStore-Server
Comment.py
Comment.py
py
416
python
en
code
0
github-code
36
37350115657
import numpy as np import pytest from ase.build import bulk from gpaw import GPAW, PW, Mixer from gpaw.mpi import world @pytest.mark.stress def test_pw_si_stress(in_tmp_dir): xc = 'PBE' si = bulk('Si') si.calc = GPAW(mode=PW(200), mixer=Mixer(0.7, 5, 50.0), xc=xc, ...
f-fathurrahman/ffr-learns-gpaw
my_gpaw/test/pw/test_si_stress.py
test_si_stress.py
py
1,105
python
en
code
0
github-code
36
1922570776
from problem_000 import * from prime import next_prime class Problem_007(Problem): def __init__(self): self.problem_nr = 7 self.input_format = (InputType.NUMBER_INT, 1, 1000000) self.default_input = 10001 self.description_str ='''By listing the first six prime numbers: 2, 3, 5, 7, ...
Kwasniok/ProjectEuler-Solver
src/problem_007.py
problem_007.py
py
628
python
en
code
1
github-code
36
8248770144
"""Provides basic utilities to check status of Discord bot ping() pings the bot and checks Discord latency, message latency and database latency source() gets information on where to find source files and feedback server clearMessages() deletes messages from the last 14 days from a channel setAutoNicknames() true or f...
JoelLucaAdams/aberlink
src/AberLinkDiscord/cogs/utilities.py
utilities.py
py
6,872
python
en
code
0
github-code
36
495566217
import os import time import pytest from dagster.core.engine.child_process_executor import ( ChildProcessCommand, ChildProcessCrashException, ChildProcessDoneEvent, ChildProcessEvent, ChildProcessStartEvent, ChildProcessSystemErrorEvent, execute_child_process_command, ) class DoubleAStri...
helloworld/continuous-dagster
deploy/dagster_modules/dagster/dagster_tests/core_tests/engine_tests/test_child_process_executor.py
test_child_process_executor.py
py
2,339
python
en
code
2
github-code
36
27916689067
""" File: draw_line Name:黃稚程 mike ------------------------- This program uses gobject in campy to draw lines on window. """ from campy.graphics.gobjects import GOval, GLine from campy.graphics.gwindow import GWindow from campy.gui.events.mouse import onmouseclicked # window is the canvas used to draw line ...
HuangChihCheng/stanCodeProjects
draw_line.py
draw_line.py
py
2,159
python
en
code
0
github-code
36
36916000678
import sys import random import osmnx as ox from time import sleep from direct.gui.DirectGui import DirectButton, DirectFrame from direct.showbase.ShowBase import ShowBase from direct.showbase.ShowBase import ShowBase from panda3d.core import Geom, GeomNode, GeomVertexFormat, GeomVertexData, GeomTriangles, GeomLines...
stressatoo/OpenPandaMap
main.py
main.py
py
12,224
python
en
code
0
github-code
36
25621121167
# SOLUTION ONE def is_pangram(s): abc = list("abcdefghijklmnopqrstuvwxyz") res = [] for c in abc: res.append(s.lower().find(c)) return all(n != -1 for n in res) # SOLUTION TWO def is_pangram(s): for c in "abcdefghijklmnopqrstuvwxyz": if c not in s.lower(): return False...
kyle-pazdel/codewars
Python/detect_pangram.py
detect_pangram.py
py
521
python
en
code
0
github-code
36