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
35255656510
## https://www.hackerrank.com/challenges/py-set-discard-remove-pop/problem n = int(input()) s = set(map(int, input().split())) for i in range(int(input())): c = str(input()).split() if c[0] == 'pop': s.pop() elif c[0] == 'remove': s.remove(int(c[1])) elif c[0] == 'discard': s.discard(int(c[1])) print(s...
abinesh1/pythonHackerRank
sets/prob30.py
prob30.py
py
488
python
en
code
0
github-code
13
41839937422
import os from Tkinter import * from tkMessageBox import * root=Tk() root.title("Indian Restaurant") root.geometry('1367x768') root.configure(background='Thistle') v1=IntVar() v2=IntVar() v3=IntVar() v4=IntVar() v5=IntVar() v6=IntVar() v7=IntVar() v8=IntVar() v9=IntVar() v10=IntVar() #=========...
sumiie24/Sumex-Plaza
Files/indian.py
indian.py
py
4,074
python
en
code
0
github-code
13
5213763415
#coding=utf-8 #Version: python3.6.0 #Tools: Pycharm 2017.3.2 _author_ = ' Hermione' m,n=map(int,input().split()) cnt=0 res=0 def is_primer(num): if num>1: for j in range(2,num): if num%j==0: return False else: return True else: return False for ...
Harryotter/zhedaPTApython
ZheDapython/z4/z4.2.py
z4.2.py
py
490
python
en
code
1
github-code
13
22232621574
from django.views.generic import TemplateView from django.contrib import admin from django.urls import include, path from drf_spectacular.views import ( SpectacularAPIView, SpectacularSwaggerView ) urlpatterns = [ path( 'admin/', admin.site.urls ), path( 'api/', include...
DmitriyEKonovalov/api_final_yatube
yatube_api/yatube_api/urls.py
urls.py
py
1,063
python
ru
code
0
github-code
13
31195569571
from pathlib import Path import os import pickle import numpy as np from refnx.reflect import SLD, Slab, ReflectModel, Motofit from refnx.dataset import ReflectDataset from numpy.testing import ( assert_equal, assert_, ) class Test__InteractiveModeller: def setup_method(self): self.pth = Path(_...
refnx/refnx
refnx/reflect/test/test__interactive_modeller.py
test__interactive_modeller.py
py
3,072
python
en
code
31
github-code
13
15523858223
from itertools import chain, tee def format_pdst(func): def wrapper(*args, **kwargs): output = func(*args, **kwargs) f_value = lambda x: f"{x:.05f}" f_line = lambda x: " ".join(map(f_value, x)) return "\n".join(map(f_line, output)) return wrapper @format_pdst def pdst(data):...
neumann-mlucas/rosalind
src/rosalind_pdst.py
rosalind_pdst.py
py
1,486
python
en
code
0
github-code
13
39068971110
from tns_glass.tests import TNSTestCase from django.core.urlresolvers import reverse from .models import * class WetmillTest(TNSTestCase): def test_unique_sms(self): self.login(self.admin) post_data = dict(country = self.rwanda.id, name = "Musha", ...
TechnoServe/SMSBookkeeping
tns_glass/wetmills/tests.py
tests.py
py
15,988
python
en
code
0
github-code
13
41767659810
import sys def reversebyte(dump,dumpout): c = len(dump) c -= 1 for i in range (len(dump)): dumpout[i] += dump[c] i += 1 c -= 1 return dumpout def openfile (s): sys.stderr.write(s + "\n") sys.stderr.write("Usage: %s <infile> <outfile>\n" % sys.argv[0]) sys.exit(1) if __name__...
DmitryMeD/Small_RE_tools
reversebyte.py
reversebyte.py
py
694
python
en
code
2
github-code
13
4415839575
from random import choice class MorphemeGeneratorMixin: def map_syll_to_structure(self, syll): if len(syll) == 2: return 'CV' elif len(syll) == 4: return 'CVCV' else: if syll[-1] in self.inventory['V']: return 'CVV' else: ...
swizzard/language_generator
morpheme_generator.py
morpheme_generator.py
py
1,684
python
en
code
1
github-code
13
34141178752
import pandas as pd import numpy as np import tensorflow as tf from simple_transformer import TransformerBlock, TokenEmbedding from biom import load_table from tensorflow import keras from keras.layers import MultiHeadAttention, LayerNormalization, Dropout, Layer from keras.layers import Embedding, Input, GlobalAverage...
kwcantrell/scale-16s
transformer/16s_wgs_unifrac_twin_transformer.py
16s_wgs_unifrac_twin_transformer.py
py
5,236
python
en
code
0
github-code
13
14803486985
# -*- coding: utf-8 -*- """ Created on Mon May 20 11:48:14 2019 @author: King23 """ """ Code Challenge Name: Space Seperated data Filename: space_numpy.py Problem Statement: You are given a 9 space separated numbers. Write a python code to convert it into a 3x3 NumPy array of integers. Inpu...
anuj378/ForskLabs
DAY 11 - Numpy & MatplotLib/MyCode/space_numpy.py
space_numpy.py
py
569
python
en
code
0
github-code
13
39814477630
# Python imports import unittest import geopandas as gpd import numpy as np import os import shutil import salem import oggm # Locals import oggm.cfg as cfg from oggm import tasks, utils, workflow from oggm.workflow import execute_entity_task from oggm.tests.funcs import get_test_dir from oggm.tests import RUN_BENCHMA...
Chris35Wills/oggm
oggm/tests/test_benchmarks.py
test_benchmarks.py
py
5,681
python
en
code
null
github-code
13
7706597277
import tornado.httpclient import redis from tornado.options import options import tornado.gen from tornado.log import logging import os r = redis.Redis(host=os.environ.get("REDIS_PORT_6379_TCP_ADDR", "localhost")) logger = logging.getLogger('fetcher') logger.setLevel(logging.DEBUG) @tornado.gen.coroutine def get_d...
cnssnewscenter/CNSS_mobile_news_center
fetcher.py
fetcher.py
py
1,524
python
en
code
0
github-code
13
11964687042
import requests from urllib.parse import urljoin, urlencode, urlparse, parse_qs import uuid import base64 import json import hashlib import hmac from datetime import datetime, timedelta from collections import namedtuple import enum import time GATEWAY_URL = 'https://kic.lgthinq.com:46030/api/common/gatewayUriList' AP...
callelonnberg/wideq
wideq.py
wideq.py
py
89,830
python
en
code
0
github-code
13
14230557337
import json from django.db import migrations from backend.util.json import json_dumps def init_aggregate_action(apps, schema_editor): AggregateAction = apps.get_model("action", "AggregateAction") aas = [] for agg_action in _default_aggregate_actions: aa = AggregateAction( system_id=...
TencentBlueKing/bk-iam-saas
saas/backend/apps/action/migrations/0002_auto_20200812_1159.py
0002_auto_20200812_1159.py
py
10,685
python
en
code
24
github-code
13
1951632795
import sqlite3 import pandas as pd import numpy as np import os.path import seaborn as sns import itertools import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics from s...
ShayEK34/SoccerProject-DataAnalysis-Python
MLmodel.py
MLmodel.py
py
33,581
python
en
code
0
github-code
13
9436842940
# coding=utf-8 import cv2 import dlib detector = dlib.get_frontal_face_detector() win = dlib.image_window() # cap = cv2.VideoCapture('E:\Python\PycharmProjects\ImgHash\Opencv\\1.mp4') cap = cv2.VideoCapture(0) while cap.isOpened(): ret, cv_img = cap.read() # OpenCV默认RGB图像,dlib BGR图像 img = cv2.cvtColor(...
swiich/face_recognize
recVideo.py
recVideo.py
py
713
python
en
code
0
github-code
13
4210600650
from typing import Optional class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def odd_even_list(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head: return None odd = head even = head.next ...
mhasan09/leetCode_M
odd_even_linkedlist.py
odd_even_linkedlist.py
py
906
python
en
code
0
github-code
13
32045601690
import numpy as np import pytest import arkouda as ak def gather_scatter(a): rev = ak.array(np.arange(len(a) - 1, -1, -1)) a2 = a[rev] res = ak.zeros(len(a), dtype=a.dtype) res[:] = a2 res[rev] = a2 return res class TestBigInt: @pytest.mark.parametrize("size", pytest.prob_size) def ...
Bears-R-Us/arkouda
PROTO_tests/tests/bigint_agg_test.py
bigint_agg_test.py
py
2,321
python
en
code
211
github-code
13
25556877755
""" Usage: inventory add <name> <description> <price> <date_added> <item_id> inventory remove <item_name> inventory list inventory check_out <item_id> inventory check_in <item_id> inventory item_view <item_id> inventory search_inventory <item_name> inventory assetvalue inventory list...
davidmukiibi/NewInventoryManagement
app.py
app.py
py
3,710
python
en
code
0
github-code
13
39154370351
import requests from bs4 import BeautifulSoup from urllib.request import urlopen as uReq import os save_dir='images/' if not os.path.exists(save_dir): os.mkdir(save_dir) query=input('enter object name to scrap') response=requests.get(f'https://www.google.com/search?q={query}&sca_esv=579625040&tbm=isch&source=h...
Chatserohan/image-scrapper
scrapper.py
scrapper.py
py
1,107
python
en
code
0
github-code
13
70852492178
from aocd import data, submit firstPolicyCount = 0 secondPolicyCount = 0 for line in data.splitlines(): policy, pwd = line.split(":") pwd = pwd.strip() limits, letter = policy.split(" ") lower, upper = limits.split("-") lower = int(lower) upper = int(upper) occurences = pwd.count(letter) ...
charvey/advent-of-code
2020/02.py
02.py
py
627
python
en
code
0
github-code
13
18712304463
# 单调栈 def dailyTemperatures(T: [int]) -> [int]: n = len(T) result = [0] * n stack = [] for i in range(n): while stack and T[stack[-1]] < T[i]: tmp = stack.pop() result[tmp] = i - tmp stack.append(i) return result if __name__ == "__main__": T = [73, 74, 7...
russellgao/algorithm
dailyQuestion/2020/2020-06/06-11/python/solution_stack.py
solution_stack.py
py
401
python
en
code
3
github-code
13
12181323596
import numpy as np def polygonValuesByID(ds, ids): uniqueids = np.unique(ids[~np.isnan(ids)]) polygonvalues = {} for polid in uniqueids: polygonvalues[polid] = ds[ids == polid][0] #1 #### <<<< ----- CHANGED ----- >>>> #### return polygonvalues def statsByID(ds, ids, stat='sum'): uniq...
mgeorgati/spDisag
SDis_Self-Training/utils/nputils.py
nputils.py
py
4,032
python
en
code
2
github-code
13
19935635760
# coding: utf-8 # Download a Modis Aqua scene from http://modis.gsfc.nasa.gov/data/dataprod/ # In[32]: from a212utils.download import download_file from IPython.display import Image import h5py import pandas as pd download = False if download: # # satelite data for day 127 of 2014 Modis Aqua level 3 clou...
phaustin/A212
notebooks/python/satellite_pandas.py
satellite_pandas.py
py
5,014
python
en
code
2
github-code
13
12801156083
from sys import stdin from collections import deque T = int(stdin.readline()) deltas = [(-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2)] for _ in range(T): l = int(stdin.readline()) startR, startC = map(int, stdin.readline().split()) endR, endC = map(int, stdin.readline().split()) ...
HyunjoonCho/problem_solving
baekjoon/rhs-algorithm/06-graph/7562.py
7562.py
py
900
python
en
code
0
github-code
13
9765762776
########## Configuration ########## # if set to True, a file with logs will be produced. produce_logs = False # if set to True, the process will load the conditions input from an SQLite file. # Otherwise, it will use ESSource. conditions_input_from_db = False # Input database. Used only if conditions_input_from_db ...
MatiXOfficial/pps-alignment-data
2017/phys-version-1/fill_6300/placeholder/run_distributions_cfg.py
run_distributions_cfg.py
py
3,528
python
en
code
0
github-code
13
2086947871
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2023/5/20 # @Author : chaocai import os from ebooklib import epub from zhconv import zhconv from service import config, log # 构造epub,方法有些长懒得拆先这样吧 def build_epub(book_data): try: path = config.read('epub_dir') + book_data.site + '/' + book_data.titl...
ilusrdbb/lightnovel-pydownloader
service/epub.py
epub.py
py
3,835
python
en
code
12
github-code
13
9075804676
#!/usr/bin/env python # -*- coding: UTF-8 -*- import sys import os import os.path import re import shutil import codecs import threading import string import tarfile import random import datetime import functools from flask import current_app, send_from_directory, Response from werkzeug.utils import cached_property f...
process-project/UC3-Portal_fork
browsepy/file.py
file.py
py
15,912
python
en
code
null
github-code
13
12798436491
import pprint pp = pprint.PrettyPrinter(indent=4) # APIC Login Data APIC_URL = "https://15.186.7.16/" APIC_USERNAME = "admin" APIC_PASSWORD = "password" # NOTE: Objects you don't want to create? Just mark them out # Common variables for both Fabric Access Policies and VM Networking # L2_INTERFACE_POLICIES = [ # {...
richa92/Jenkin_Regression_Testing
robo4.2/fusion/tests/wpst_crm/ci_fit/tools/aci/resources/5ME-CL10-APIC_multi_data_variable.py
5ME-CL10-APIC_multi_data_variable.py
py
14,197
python
en
code
0
github-code
13
73054672977
from pynput import keyboard import pandas as pd from win10toast import ToastNotifier def on_activate(): df = pd.read_clipboard() toster = ToastNotifier() toster.show_toast("title", df.columns[0], duration=5) with keyboard.GlobalHotKeys({ '<ctrl>': on_activate}) as h: h.join()
FlintyLemming/picManagementUtilities
duplicateCheck/main.py
main.py
py
315
python
en
code
0
github-code
13
19375055905
#!/usr/bin/python def beast(id): if id == 'Goblin Smuggler' or id == '1' or id == 'goblin': monster = {'name': 'Goblin Smuggler', 'hp': 5, 'max': 2, 'min': 1, 'def': 0, 'agi': 20, 'acc': 5, 'crit': 1, 'exp': 25} if id == 'Giant Rat' or id == '2' or id == 'rat': monster = {'name': 'Giant Rat', '...
deathkj/battle
beastiary.py
beastiary.py
py
2,123
python
en
code
0
github-code
13
18445803662
''' This model is to build a attention layer. ''' import torch import torch.nn as nn import torch.nn.functional as F __all__ = ['attention_layer', 'attention_layer_light'] class attention_layer(nn.Module): def __init__(self, in_dim, texture_dim): super(attention_layer, self).__init__() self.query...
liuch37/tanet-pytorch
models/attention_layer.py
attention_layer.py
py
3,899
python
en
code
0
github-code
13
17055240444
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class LabelFilter(object): def __init__(self): self._column_name = None self._op = None self._values = None @property def column_name(self): return self._column...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/LabelFilter.py
LabelFilter.py
py
2,089
python
en
code
241
github-code
13
11665042650
import plotly.offline as pyo import plotly.graph_objs as go import pandas as pd df=pd.read_csv('plotly\\Plotly-Dashboards-with-Dash-master\\Data\\2018WinterOlympics.csv') trace0=go.Bar(x=df['NOC'],y=df['Gold'],name='Gold',marker={'color':'#FFD700'}) trace1=go.Bar(x=df['NOC'],y=df['Silver'],name='Silver',mark...
jyothsnashaji/plotly-dash
barchart.py
barchart.py
py
578
python
en
code
0
github-code
13
3750508320
from calendar import month_name from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.db.models import Q from django.http import JsonResponse, Http404, HttpResponseBadRequest from django.shortcuts import render, get_object_or_404,...
umairkhan987/Job-Boards
freelancers/views.py
views.py
py
9,162
python
en
code
0
github-code
13
27470947255
from django.shortcuts import render from django.core.files.storage import FileSystemStorage from .models import Video from django.http import HttpResponse from django.http import HttpResponseForbidden from django.contrib.auth.decorators import login_required import os from hc.settings import BASE_DIR def index(reques...
andela/dashiki-healthchecks
hc/help_videos/views.py
views.py
py
2,440
python
en
code
1
github-code
13
327009991
import re from jamo import h2j, j2hcj from cached_property import cached_property from pathlib import Path import pandas as pd """a list of vowels""" korean_vowel = ['ㅏ','ㅑ', 'ㅓ', 'ㅕ', 'ㅗ', 'ㅛ', 'ㅜ', 'ㅠ', 'ㅡ','ㅣ','ㅒ', 'ㅐ','ㅔ', 'ㅖ', 'ㅟ', 'ㅚ', 'ㅙ', 'ㅞ'] """a string to a list""" def make_list(words): ...
storidient/Act2Emo_baseline
utils.py
utils.py
py
1,684
python
en
code
0
github-code
13
41604769366
#-*- coding: utf-8 -*- import csv import gzip import time from jinja2 import Environment, FileSystemLoader from libs import * from config import * class Data(dict): def __getattr__(self, name): try: return self[name] except KeyError: raise AttributeError(name) def __setattr__(self, name, val): self[na...
lmdu/krait
src/utils.py
utils.py
py
9,659
python
en
code
34
github-code
13
8343869036
n = int(input()) arr = [] for i in range(1, n+1): st = str(int(input())) cnt = 0 cur = "0" for j in st: if j != cur: cnt += 1 cur = j print('#%d %d' %(i, cnt))
rohujin97/Algorithm_Study
swea/Solution_SWEA_1289_원재의메모리복구하기_D3_노유진_161ms.py
Solution_SWEA_1289_원재의메모리복구하기_D3_노유진_161ms.py
py
211
python
en
code
0
github-code
13
72514154898
from rpy2deseq.rpy2utils import ( _importr, _r_to_list, _r_to_numpy, _pandas_to_r, _numpy_to_r ) import numpy as _np import pandas as _pd # Import stats _stats = _importr('stats') _hclust_converts = { 'merge': _r_to_numpy, 'height': _r_to_list, 'order': lambda x: _np.array(_r_to_list(x...
GreshamLab/rpy2deseq
rpy2deseq/hclust.py
hclust.py
py
1,476
python
en
code
0
github-code
13
7100066840
booked = [ 1, 3, 9, 12, 13, 18, 26, 27, 28, 29 ] travel = [ 4, 5, 15, 16, 21, 22 ] study = [] month = range(1, 31) Busy = booked + travel for day in month: if day not in Busy: study.append(day) study = [day for day in month if day not in booked + travel] print(study)
naina-yoganathan/pythonp
days_to_study.py
days_to_study.py
py
292
python
en
code
0
github-code
13
74229111378
import os import googlemaps from datetime import datetime from classes import Point class GoogleMapsHelper: def __init__(self): self.client = googlemaps.Client(key=os.environ['GOOGLE_API_KEY']) def time_between_points(self, origin, destination, unit='hours'): now = datetime.now() dir...
iaacosta/ics3213-g25
services/GoogleMaps.py
GoogleMaps.py
py
777
python
en
code
0
github-code
13
11874553115
from rest_framework import serializers from order.models import Order from scan.models import ScanTable, ScanDetailsTable class ScanTableSerializer(serializers.Serializer): order_id = serializers.IntegerField() title = serializers.CharField() scanImageRaw = serializers.ImageField(allow_null=True, allow_em...
prettypanda0720-ww/Interior-Room-Design-Website-Django-and-React
scan/serializers.py
serializers.py
py
2,104
python
en
code
0
github-code
13
40724859601
#!/usr/bin/env python3 """TLG NDE Python | LAncheta | Lists, Input, Print, Variables""" def main(): wordbank= ["indentation", "spaces"] wordbank_append(4) print(wordbank) tlgstudents= ["Aaron", "Andy", "Asif", "Brent", "Cedric", "Chris", "Cory", "Ebrima", "Franco...
GaiusOctopus/mycode
challenge/listchallenge01.py
listchallenge01.py
py
467
python
en
code
0
github-code
13
31267040182
import os from utils import euler_lib def main(): t = [] supplemental_dir = os.path.join( os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "supplemental") filepath = os.path.join(supplemental_dir, "p67_triangle.txt") with open(filepath, encoding='utf-8') as f: ...
stephendwillson/ProjectEuler
solutions/python/problem_67.py
problem_67.py
py
706
python
en
code
0
github-code
13
40678801529
# -*- coding: utf-8 -*- """AnyPyTools library.""" import sys import platform import logging from anypytools.abcutils import AnyPyProcess, execute_anybodycon from anypytools.macroutils import AnyMacro from anypytools import macro_commands logger = logging.getLogger('abt.anypytools') logger.addHandler(logging.NullHan...
sebastianskejoe/AnyPyTools
anypytools/__init__.py
__init__.py
py
1,286
python
en
code
null
github-code
13
24150317194
""" Ещё раз рассмотрим Flask endpoint, принимающий код на питоне и исполняющий его. 1. Напишите для него Flask error handler, который будет перехватывать OSError и писать в log файл exec.log соответствую ошибку с помощью logger.exception 2. Добавьте отдельный exception handler 3. Сделайте так, что в случае непу...
ilnrzakirov/Python_advanced
module_06_debugging_begin/hw/hw_2_execute_code_from_form.py
hw_2_execute_code_from_form.py
py
2,703
python
ru
code
0
github-code
13
24147646024
def fibonachi(num_pos, chek=2, start=0, res=1): # , Предлагаю упростить решение. # Нужен только 1 параметр функции =) # Нам необходимо просто вернуть сумму чисел предыдущего числа и предпредыдущего =) if num_pos == 1: # , если 2, тоже необходимо выйти из рекурсии return 1 if chek == num_p...
ilnrzakirov/Python_basic
Module21/03_fibonacci/main.py
main.py
py
883
python
ru
code
0
github-code
13
10310267190
# --*-- coding:utf-8 --*-- # @Time : 2020/12/8 14:52 # @Author : 啊。懋勋 # @version: Python 3.7 # @File : zhihu_question.py from selenium import webdriver import time from lxml import etree import pymysql import os conn = pymysql.connect('localhost', 'root', 'root', 'zhuhu_question') # 连接数据库 cursor = conn.cursor() #...
sing-zzj/pycharm
zhihu_question.py
zhihu_question.py
py
1,800
python
en
code
0
github-code
13
21731197412
import tempfile import unittest from unittest.mock import call, patch from deploy.config import new_config from deploy.deploy_updated_job import create_job_from_savepoint from deploy.deploy_updated_job import stop_job, update_existing_job # Creates a Dict in a similar form as we'd expect from Flink's REST API. def jo...
promotedai/openmetrics
pipeline/scripts/tests/deploy/test_deploy_updated_job.py
test_deploy_updated_job.py
py
4,694
python
en
code
5
github-code
13
74080596176
from pathlib import Path from PIL import Image import numpy as np # Search for pyNeRFRenderCore in build/Debug/ import sys path_to_PyTurboNeRF = Path(__file__).parent.parent / "build" / "Debug" print("Searching for TurboNeRF in", path_to_PyTurboNeRF) sys.path.append(str(path_to_PyTurboNeRF)) import PyTurboNeRF as t...
JamesPerlman/TurboNeRF
examples/train-all.py
train-all.py
py
4,235
python
en
code
296
github-code
13
17035737944
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlarmInfo(object): def __init__(self): self._ad_code = None self._content = None self._level = None self._out_id = None self._time = None self._tit...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/AlarmInfo.py
AlarmInfo.py
py
3,389
python
en
code
241
github-code
13
16765879640
import sys def checkCol(col, board): for row in board: if row[col] != -1: return False return True def checkRow(row, board): for col in board[row]: if col != -1: return False return True def checkBoard(num, board): done = False for i in range(len(board)...
rbangamm/aoc-2021
aoc-2021-python/aoc4.py
aoc4.py
py
2,380
python
en
code
0
github-code
13
6329648143
class Solution: def searchInsert(self, nums: list[int], target: int): if target in nums: return nums.index(target) if target < nums[0]: return 0 if target > nums[len(nums)-1]: return len(nums) for i in range(len(nums)): if nums[i] < tar...
N1kMA/Leetcode
search_insert_position.py
search_insert_position.py
py
502
python
en
code
0
github-code
13
15549483355
from pwn import * from pwn import p64,u64 debug = 0 gdb_is = 0 # context(arch='i386',os = 'linux') context(arch='amd64',os = 'linux', log_level='DEBUG') if debug: context.terminal = ['/mnt/c/Users/sagiriking/AppData/Local/Microsoft/WindowsApps/wt.exe','nt','Ubuntu','-c'] r = process("./pwn") els...
Sagiring/Sagiring_pwn
MoeCTF2023/PIE_enabled/pwn_exp.py
pwn_exp.py
py
937
python
en
code
1
github-code
13
41398002620
import json import glob def create_category_json(path: str = "questions/questions.json") -> None: """ for each category we will create a list of the question ids and json file in a dict. we will store result in questions/questions.json """ categories: dict = {} question_part_count: int = len(g...
Bnux256/TheoryHelper
lib/count_category.py
count_category.py
py
1,783
python
en
code
3
github-code
13
8004194558
""" Clone of 2048 game. http://www.codeskulptor.org/#user40_dSvByRSsOh3253F.py """ import poc_2048_gui import random # Directions, DO NOT MODIFY UP = 1 DOWN = 2 LEFT = 3 RIGHT = 4 # Offsets for computing tile indices in each direction. # DO NOT MODIFY this dictionary. OFFSETS = {UP: (1, 0), DOWN: (-1, 0),...
chickenoverrice/python_game
python_game2048.py
python_game2048.py
py
4,444
python
en
code
0
github-code
13
38227794476
#!/usr/bin/env/python3 # -*- coding: utf-8 -*- __author__='drawnkid@gmail.com' import sys import os from optparse import OptionParser parser = OptionParser() parser.add_option("-a", "--append",dest = "append",action = "store_true",default = False,help = "append the string") options, args = parser.parse_args() if not le...
BaliStarDUT/hello-world
code/python/IO/tee_2.py
tee_2.py
py
915
python
en
code
4
github-code
13
19158535215
# Given a knapsack with maximum capacity W, and a set S consisting of n items # Each item i has some weight wi and benefit value bi (all wi, bi and W are integer values) # Problem: How to pack the knapsack to achieve maximum total value of packed items? # Example: # values = [60, 100, 120] # weights = [10, 20, 30] # W...
phamtamlinh/coding-challenges
basic/dynamic-programming/0-1-knapsack-problem.py
0-1-knapsack-problem.py
py
1,092
python
en
code
0
github-code
13
30140726420
import argparse from data_converter import utils def convert(input_file, to_format): """Convert input_file into another format Raises: FileNotFoundError & UserWarning: from the function `_check_input_file` ValueError Returns: str: Absolute file path of output file """ if...
xtream1101/data-converter
data_converter/__init__.py
__init__.py
py
1,424
python
en
code
2
github-code
13
12089083303
# 练习2:为sum_data,增加打印函数执行时间的功能. # ​ 函数执行时间公式: 执行后时间 - 执行前时间 import time # 装饰器函数 def exeture_time(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) times = time.time() - start_time print('原函数执行的时间:', times) return result retur...
15149295552/Code
Month01/Day15/exercise03.py
exercise03.py
py
812
python
zh
code
1
github-code
13
36265574162
def close(session, models=None): ''' Close models. Parameters ---------- models : list of models These models and any submodels are closed. If models is none all models are closed. ''' m = session.models if models is None: models = m.list() # Avoid closing grouping...
HamineOliveira/ChimeraX
src/bundles/std_commands/src/close.py
close.py
py
1,549
python
en
code
null
github-code
13
20032798567
#!/usr/bin/python3 """ Minimum Operations """ def minOperations(n): """ method that calculates the fewest number of operations needed to result in exactly n H characters in a file resoluton method: look at the output for the first n = 15 strings observe that if n is prime number, num_op = n i...
dacastanogo/holbertonschool-interview
0x03-minimum_operations/0-minoperations.py
0-minoperations.py
py
643
python
en
code
0
github-code
13
31190579625
from pyrogram import filters from pyrogram.types import Message from strings import get_command from AasthaMusicBot import app from AasthaMusicBot.misc import SUDOERS from AasthaMusicBot.utils.database import add_off, add_on from AasthaMusicBot.utils.decorators.language import language # Commands MAINTENANCE_COMMAND ...
Ozlembener/AasthaTGMusicBot
AasthaMusicBot/plugins/sudo/maintenance.py
maintenance.py
py
988
python
en
code
1
github-code
13
21414347697
from unittest import TextTestResult import subprocess import yaml class TextTestResultWithSuccesses(TextTestResult): """ This class extends TextTestResult so that successful tests get reported in `self.successes`. """ def __init__(self, *args, **kwargs): super(TextTestResultWithSuccesses, self...
AlassaneNdiaye/test-containers
test_containers/utils.py
utils.py
py
1,267
python
en
code
0
github-code
13
32954770392
import base64 import importlib import io from datetime import datetime from typing import Dict, TypedDict import cv2 import numpy from cv2 import Mat, imencode, imread class Images(TypedDict): original: Mat before: Mat after: Mat Paths = Dict[str, Images] class ImageManager: images: Paths = dict...
TheColorRed/image-editor
image-processor/Source/utils/image.py
image.py
py
3,424
python
en
code
0
github-code
13
13944276872
################# model_tiny.py from tensorflow.keras.layers import Conv2D, MaxPooling2D, \ Flatten, Dense, Reshape, LeakyReLU, BatchNormalization # from tensorflow.keras.layers.normalization import from tensorflow.keras.regularizers import l2 # from tensorflow.keras.engine.topology import Layer from tensorflow...
G0rav/yolov1
yolov1_complete.py
yolov1_complete.py
py
13,946
python
en
code
0
github-code
13
11527812303
#install pillow package, pip3 install pillow import sys import os from PIL import Image input1=sys.argv[1] output=sys.argv[2] print(input1) # create Path if not (os.path.exists(output)): os.makedirs('output') #open and save files for item in os.listdir(input1): asd=os.path.splitext(item)[0] image1=Image.op...
raghav914/Image-Converter
jpg.py
jpg.py
py
410
python
en
code
0
github-code
13
25951363465
from tkinter import * import time import math # ---------------------------- CONSTANTS ------------------------------- # PINK = "#e2979c" RED = "#e7305b" GREEN = "#9bdeac" YELLOW = "#f7f5dd" FONT_NAME = "Courier" WORK_MIN = 25 SHORT_BREAK_MIN = 5 LONG_BREAK_MIN = 20 reps = 0 timer = None # ---------------------------...
ckzard/100days
day28/main.py
main.py
py
4,482
python
en
code
0
github-code
13
29696279244
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: s = set() deleted = set() cur = head whil...
xincheng-cao/loser_fruit
hash/82. Remove Duplicates from Sorted List II.py
82. Remove Duplicates from Sorted List II.py
py
992
python
en
code
0
github-code
13
73658168658
from pwn import * p = process("./faker", env={"LD_PRELOAD": "./libc.so.6"}) elf = ELF("faker") libc = ELF("libc.so.6") def new(size): p.sendlineafter("> ", "1") p.sendlineafter(":\n", str(size)) return int(p.recvregex("at index (\d+)")[0]) def edit(index, data): p.sendlineafter("> ", "2") p.sendli...
D4mianWayne/PwnLand
CTFs/3kCTF2020/faker/faker.py
faker.py
py
4,332
python
en
code
43
github-code
13
24346068490
#!/usr/bin/env python # coding: utf-8 # In[1]: import os import pandas as pd # In[3]: # file paths IMGFOLDER = 'myprac/' COLORMASKFOLDER = 'myprac/color_masks/' BIMASKFOLDER = 'myprac/bi_coded_masks/' CSVFILE = 'myprac/bbox.csv' IMGOUT = 'myprac/imgs/' FINALMASKOUT = 'myprac/masks/' # In[4]: # setup # cur...
thebabellibrarybot/prep_fasterRCNN_anno
mask_config.py
mask_config.py
py
1,216
python
en
code
1
github-code
13
31374392804
# Takes a long string formatted as a repetition of [sender] => [receiver] £[amount] [datetime] # and converts it into a list of tuples in the format [(sender, receiver, amount, datetime), ...]. def read_ledger(s): l = [] if len(s) < 29: return l #less than the minimum amount of characters returns an ...
JoFGD/ReadLedger
read_ledger.py
read_ledger.py
py
710
python
en
code
0
github-code
13
15726670967
def collatz(number): if number%2 == 0: result = number // 2 print(str(number) + ' // 2 = ' + str(result)) else: result = 3 * number + 1 print('3 * ' + str(number) + ' + 1 = ' + str(result)) print('Please! Enter number: ') collatz(int(input()))
tmhung-nt/PythonPractise
Tien/Chapter3/The_Collatz_Sequence.py
The_Collatz_Sequence.py
py
262
python
en
code
0
github-code
13
26811824623
import random import turtle from turtle import Turtle, Screen tim = Turtle() turtle.colormode(255) def random_color(): r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) colors = (r, g, b) return colors tim.speed("fast") tim.pensize(10) directions = [0, 90, 180, 27...
nilayhangarge/100-Days-of-Code-Challenge
Project/Day-18 Turtle Graphics/Day-18 Turtle Challenges/Version 18.4/main.py
main.py
py
537
python
en
code
0
github-code
13
33301433385
from django.shortcuts import render from django.http import HttpResponse from app.models import * # Create your views here. def form(request): if request.method=='POST': username=request.POST['un'] password=request.POST['pw'] print(username) print(password) return HttpRes...
oppalaa/sample
app/views.py
views.py
py
1,999
python
en
code
0
github-code
13
3645175993
import argparse from hvarma import Data, ArmaParam, run_model, write_results, plot_hvratio def select_parameters_from_args(args): """ Filter out ArmaParam attributes from commandline arguments """ args_dict = {} for arg in vars(args): if arg in ArmaParam.get_fields_list(): if getattr(a...
asleix/hvarma
examples/run.py
run.py
py
2,921
python
en
code
0
github-code
13
71202979859
#!/usr/bin/env python import sys from os.path import expanduser import os sys.path.append(os.path.join(expanduser("~"), "src/anki")) from anki import Collection from sqlite3 import OperationalError from termcolor import colored from argparse import ArgumentParser import re import random import sys parser = Argument...
jarv/anki-prompt
anki-prompt.py
anki-prompt.py
py
1,853
python
en
code
0
github-code
13
17700482583
# we use googletrans API new name is google_trans_new # pip command ; pip install google_trans_new from google_trans_new import google_translator import streamlit as st translator = google_translator() st.title("Language Translator") text = st.text_input("Enter a text") translate = translator.translate(text, lang_tgt=...
cinalimaster/ariftanis
Python/project_library/interactive_language_translator.py
interactive_language_translator.py
py
502
python
en
code
0
github-code
13
2295560053
import datetime import json import math import threading import tkinter import urllib.request import requests from PIL import Image, ImageTk prev_lat, prev_long, prev_time, prev_speed = 0, 0, 0, 0 def distance_on_unit_sphere(lat1, long1, lat2, long2): # Convert latitude and longitude to # spherical coordin...
bsoyka/iss-tracker
iss_tracker/__init__.py
__init__.py
py
2,745
python
en
code
3
github-code
13
17930590562
from marshmallow import fields, pre_load from .flapp.extension import db, ma from .model.ublog import Note, Person from .model.library import Book, Quote # Custom validator def must_not_be_blank(data): if not data: raise ValidationError("Data not provided.") class NoteSchema(ma.SQLAlchemyAutoSchema): ...
thinknot/connx-alembic
src/schema.py
schema.py
py
2,130
python
en
code
0
github-code
13
3108184746
""" The program receives from the USER a STRING and returns (ignoring spaces and punctuation marks), whether or not it is a PALINDROME. """ # START Definition of FUNCTION def checkWord(string): string = string.upper() index_sx = 0 # left index index_dx = len(string)-1 # right i...
aleattene/python-workbook
chap_03/exe_076_multiple_word_palindromes.py
exe_076_multiple_word_palindromes.py
py
1,857
python
en
code
1
github-code
13
38259646951
import tensorflow as tf node1 = tf.constant(3.0, tf.float32) node2 = tf.constant(4.0) node3 = tf.add(node1, node2) sess = tf.Session() a = tf.placeholder(tf.float32) b = tf.placeholder(tf.float32) adder_node = a + b # feed_dict >> placeholder 에 반드시 따라온다 # 텐서머신의 그래프 역할을 하는듯? 함수같이? print(sess.run(adder_node, feed_di...
dongjaeseo/study
tf114/tf04_1_placeholder.py
tf04_1_placeholder.py
py
541
python
en
code
2
github-code
13
29730853815
#!/bin/python3 # -*- coding: utf-8 -*- """Parameter search (2020 Line recruit test) This is code for 2020 line recruit test problem B. Author: Bae Jiun, Maybe """ from typing import Tuple import sys import argparse from multiprocessing import Pool, cpu_count from itertools import product from pathlib import Path impo...
leejseo/2020-line-recruit
scripts/parameter_search.py
parameter_search.py
py
4,807
python
en
code
0
github-code
13
4791896088
#!/usr/bin/python # -*- coding: utf-8 -*- import pandas as pd import numpy as np from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.feature_extraction import DictVectorizer # 计算多个树,然后取多数为真 from sklearn.ensemble import RandomForestClassifier data = pd.read_csv(r"learning\机器学习\自...
LeroyK111/BasicAlgorithmSet
集成学习算法/随机森林.py
随机森林.py
py
1,288
python
en
code
1
github-code
13
26854883355
# from pytorch_pretrained_bert import BertTokenizer import copy from transformers import BertTokenizer from tcn_test_7.data_tcn import * from torchtext.vocab import build_vocab_from_iterator, Vocab import pandas as pd from sklearn.model_selection import KFold from tcn_test_7.model import CpsTcnModel tokenizer = BertT...
xiaoyuerova/CPSProject
tcn_test_7/utils.py
utils.py
py
2,532
python
en
code
0
github-code
13
23727083350
# %% from typing import List class Solution: def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int: res = -1 minn = float("inf") for i, point in enumerate(points): x_, y_ = point if x_ == x and minn > abs(y_ - y): minn = abs(y_ ...
HXLH50K/Leetcode
1779.py
1779.py
py
474
python
en
code
0
github-code
13
72630150417
# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement # flake8: noqa: F401 # --- Do not remove these libs --- import numpy as np # noqa import pandas as pd # noqa from pandas import DataFrame from functools import reduce from freqtrade.strategy import (BooleanParameter, CategoricalPar...
ken2190/MyTradingStrategy
DoubleBollingerStrategy.py
DoubleBollingerStrategy.py
py
6,364
python
en
code
0
github-code
13
14645694375
from sqlalchemy import Column, ForeignKey, Identity, Integer, String, Table from . import metadata GelatoIdNumberReportJson = Table( "gelato_id_number_reportjson", metadata, Column( "dob", GelatoDataIdNumberReportDate, ForeignKey("GelatoDataIdNumberReportDate"), comment="Da...
offscale/stripe-sql
stripe_openapi/gelato_id_number_report.py
gelato_id_number_report.py
py
1,079
python
en
code
1
github-code
13
10796414751
from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.sites.models import Site from structure.models import Organization, Team, User, Contract, ContractOrganization, ContractTeam from django.utils.translation import ugettext_lazy as _ class TeamAdmin(admin.ModelAdmin): l...
RocknRoot/LIIT
structure/admin.py
admin.py
py
1,753
python
en
code
1
github-code
13
36458003126
from __future__ import unicode_literals import frappe, os, json from frappe import _ from frappe.utils import cint, today, formatdate, get_timestamp from frappe.utils.nestedset import NestedSet, get_root_of from frappe.model.document import Document import frappe.defaults from frappe.cache_manager import clear_defaults...
fderyckel/ifitwala_ed
ifitwala_ed/school_settings/doctype/school/school.py
school.py
py
8,359
python
en
code
18
github-code
13
14906880013
from micropython import const import uos as os import utime as time import machine import ustruct import i2c_bus, module M5GO_WHEEL_ADDR = const(0x56) MOTOR_CTRL_ADDR = const(0x00) ENCODER_ADDR = const(0x04) motor1_pwm = 0 motor2_pwm = 0 def dead_area(amt, low, low_up, high, high_up): if amt > low_up and amt < ...
BradenM/micropy-stubs
packages/m5flowui/v1.4.0/generic/frozen/flowlib/modules/_lego.py
_lego.py
py
4,451
python
en
code
26
github-code
13
40597601185
import yaml from os import path rdir = path.dirname(path.realpath(__file__)) + '/' refs = yaml.load(open(rdir + 'BH76_ref_energies.yaml','r'), Loader=yaml.Loader) ts_d = {} for ibh, abh in enumerate(refs): for asys in refs[abh]['Stoich']: if refs[abh]['Stoich'][asys] > 0: if asys not in ts_d: ...
esoteric-ephemera/BH76-PySCF-PyFLOSIC
get_s_squared.py
get_s_squared.py
py
1,885
python
en
code
0
github-code
13
14739419445
#Uses python3 import sys from multiprocessing import Queue import queue import math import heapq class PriorityQueue(Queue): def _put(self, item): data, priority = item self._insort_right((priority,data)) def _get(self): return self.queue.pop(0) def _insort_right(self, x): ...
price-dj/Algorithms_On_Graphs
Week4/pset4/dijkstrav6.py
dijkstrav6.py
py
1,963
python
en
code
0
github-code
13
19253451866
import sqlite3 import json from sqlacodegen.codegen import CodeGenerator from sqlalchemy import create_engine, MetaData import sqlalchemy_utils import pandas as pd import pickle import numpy as np import re import unittest def trim_trim(trim): trimming = re.findall(r'\b[A-Za-z]+\b', trim) trimming = [x.upper() for ...
Chilledfish/icar-Project
icar_database.py
icar_database.py
py
8,242
python
en
code
0
github-code
13
10524006333
MOTION_SERVICE_UUID = "00030000-78fc-48fe-8e23-433b3a1942d0" STEP_COUNT_UUID = "00030001-78fc-48fe-8e23-433b3a1942d0" RAW_XYZ_UUID = "00030002-78fc-48fe-8e23-433b3a1942d0" HEART_RATE_UUID = "00002a37-0000-1000-8000-00805f9b34fb" MODEL_NBR_UUID = "00002a24-0000-1000-8000-00805f9b34fb" """ import asyncio from bleak im...
Sussex-Neuroscience/many_pinetime_heartbeats
legacy/new.py
new.py
py
2,107
python
en
code
0
github-code
13
37562353138
# The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? def prime_check(x): for i in range(2,int(x ** 0.5) + 1): if x%i ==0: return False return True biggest_prime = 1 for i in range(2,int(600851475143 ** 0.5)): if (6...
mertsengil/Project_Euler_with_Python
Problem_3.py
Problem_3.py
py
414
python
en
code
0
github-code
13
18414787771
from project.software.software import Software class Hardware: def __init__(self, name, type, capacity, memory): self.name = name self.type = type # NOTE Test both types of hardware ("Heavy" or "Power") self.capacity = capacity # NOTE Test both capacity types of hardware ("Heavy" or "Pow...
MiroVatov/Python-SoftUni
PYTHON OOP/Previous Exams/Exam Prep 16 August 2020 Version 2/project/hardware/hardware.py
hardware.py
py
1,262
python
en
code
0
github-code
13
38605594320
# -*- coding: utf-8 -*- import tweepy import requests from access import * import argparse class Api(object): def __init__(self): super(Api, self).__init__() try: auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET) ...
agusmdev/clone-twitter-account
clone_profile.py
clone_profile.py
py
5,461
python
en
code
7
github-code
13