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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
14498906066 | from toontown.toonbase.ToonBaseGlobal import *
from panda3d.core import *
from toontown.toonbase.ToontownGlobals import *
import random
from direct.distributed import DistributedObject
from direct.directnotify import DirectNotifyGlobal
import ToonInteriorColors
from toontown.dna.DNADoor import DNADoor
from toontown.hoo... | TTOFFLINE-LEAK/ttoffline | v2.5.7/toontown/building/DistributedLabInterior.py | DistributedLabInterior.py | py | 5,140 | python | en | code | 3 | github-code | 90 |
38381764488 | import urllib.request
import requests
from settings import *
import json
class Platform():
def get_auth_token(self, grant_type, domain, username, password):
params = {
"grant_type": grant_type,
"domain": domain,
"username": username,
"password": password
... | tam1t/ps | 3pl-integration/platform.py | platform.py | py | 4,521 | python | en | code | 0 | github-code | 90 |
22131945238 | from django import forms
from django.forms import ModelForm
from studenci.models import Uczelnia, Miasto
class UserLoginForm(forms.Form):
login = forms.CharField(
label="Twój login",
max_length=20,
widget=forms.TextInput()
)
class UczelniaForm(forms.Form):
nazwa = forms.CharField(... | Bananek96/djangoapp | studenci/forms.py | forms.py | py | 899 | python | pl | code | 0 | github-code | 90 |
33557674429 | #!/usr/bin/env python
# Here we set up a Twisted Web server and then launch a slave tor
# with a configured hidden service directed at the Web server we set
# up. This uses serverFromString to translate the "onion" endpoint descriptor
# into a TCPHiddenServiceEndpoint object...
from __future__ import print_function
... | meejah/txtorcon | examples/launch_tor_endpoint2.py | launch_tor_endpoint2.py | py | 1,426 | python | en | code | 245 | github-code | 90 |
416869129 | from __future__ import annotations
import logging
from typing import List, Dict, Tuple, TYPE_CHECKING
import bpy
import bpy.types as T # noqa
from mixer.blender_data.datablock_proxy import DatablockProxy
from mixer.blender_data.filter import SynchronizedProperties, skip_bpy_data_item
from mixer.blender_data.proxy i... | ubisoft/mixer | mixer/blender_data/diff.py | diff.py | py | 7,420 | python | en | code | 1,311 | github-code | 90 |
18429249009 | n = int(input())
b = list(map(int, input().split()))
fl = [False] * n
q = []
while len(b) != 0:
ptr = -1
for i in range(len(b)):
if b[i] == i+1:
ptr = i
if ptr == -1:
break
_b = []
for i in range(len(b)):
if i == ptr:
q.append(b[i])
else:
... | Aasthaengg/IBMdataset | Python_codes/p03089/s323939748.py | s323939748.py | py | 445 | python | en | code | 0 | github-code | 90 |
30355463456 | #!/usr/bin/env python3
##############
# Get all the modules needed
# System:
import os
import subprocess
# Directory:
#os.chdir('/Users/antoniob/Documents/quickstart_projects/data/external/MR_data/parsa_flow_cytometry')
def create_symlinks(file_to_read, path, var1, var2):
'''
Create symlinks for Parsa files ... | antoniojbt/pipeline_MR | legacy/symlinks_traits_to_keep.py | symlinks_traits_to_keep.py | py | 1,257 | python | en | code | 1 | github-code | 90 |
26245455496 | import argparse
from simulation import simulate
def main():
parser = argparse.ArgumentParser()
parser.add_argument('seed', type=int)
parser.add_argument('--remotemem', '-r', action='store_true',
help='enable remote memory')
parser.add_argument('--num_servers','-n', type=int, hel... | clusterfarmem/clustersim | simulation_one_time.py | simulation_one_time.py | py | 2,538 | python | en | code | 10 | github-code | 90 |
73077246696 | #当我们拿到一个对象的引用时,如何知道这个对象是什么类型、有哪些方法呢?
#基本类型都可以用type()判断:
type(123)
type('str')
type(None)
#如果一个变量指向函数或者类,也可以用type()判断:
type(abs)
#type(a)
#但是type()函数返回的是什么类型呢?它返回对应的Class类型。如果我们要在if语句中判断,就需要比较两个变量的type类型是否相同:
#判断基本数据类型可以直接写int,str等,
# 但如果要判断一个对象是否是函数怎么办?可以使用types模块中定义的常量:
import types
def fn():
pass
type(f... | HeatDeath/LearnPythonWithLiao | 9-面向对象编程(over)/9-4获取对象信息.py | 9-4获取对象信息.py | py | 2,894 | python | zh | code | 0 | github-code | 90 |
24115900862 | directions = ('north', 'south', 'east', 'west')
verbs = ('go', 'kill', 'eat')
stops = ('the', 'in', 'of')
nouns = ('bear', 'princess')
# lower() Returns a copy of the characters; in lowercase
def get_tuple(word):
test_word = word.lower()
if test_word in directions:
return ('direction', word)
... | chmcphoy/LPTHW | projects/ex48/ex48/lexicon.py | lexicon.py | py | 872 | python | en | code | 0 | github-code | 90 |
6936864144 | from __future__ import annotations
import numpy as np
def modular_inverse(a: int, N: int) -> int:
"""Return the inverse of `a` modulo `N`.
Args:
a: The number to invert.
N: The modulus. Must be > 1.
Returns:
The inverse of `a` modulo `N`.
Raises:
ValueError: if `N` ... | kevinddchen/Cirq-PrimeFactorization | factor/utils_math.py | utils_math.py | py | 3,024 | python | en | code | 0 | github-code | 90 |
18275442879 | #import sys
#import numpy as np
#import sys
#import numpy as np
import math
#from fractions import Fraction
import itertools
from collections import deque
from collections import Counter
#import heapq
#from fractions import gcd
#input=sys.stdin.readline
import bisect
n=input()
k=int(input())
if k==1:
a=int(n[0])
... | Aasthaengg/IBMdataset | Python_codes/p02781/s750827966.py | s750827966.py | py | 1,138 | python | en | code | 0 | github-code | 90 |
27792982908 | from collections import Counter
my_dict={
'a':50,
'b':58,
'c':56,
'd':40,
'e':100,
'f':20
}
b=[]
k=Counter(my_dict)
high=k.most_common(3)
for i in high:
b.append(i[1])
print(b)
# print("Dictionary with 3 highest values:")
# print("keys:values")
# highest=max(my_dict.values())
... | Purnima124/Dictionnary | Question no.11.py | Question no.11.py | py | 364 | python | en | code | 0 | github-code | 90 |
11870942775 | class User:
def __init__(self, name, email_address):
self.name = name
self.email = email_address
self.account_balance = 0
def make_deposit(self, deposit):
self.account_balance += deposit
def make_withdrawal(self, withdrawal):
self.account_balance -= withdrawal
rod... | xrodbeex/users | users.py | users.py | py | 1,204 | python | en | code | 0 | github-code | 90 |
18522236929 | # coding: utf-8
import sys
import numpy as np
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
D, N = lr()
if N == 100:
N += 1
answer = 100 ** D * N
print(answer)
| Aasthaengg/IBMdataset | Python_codes/p03324/s510113118.py | s510113118.py | py | 228 | python | en | code | 0 | github-code | 90 |
36861946765 | from unittest import result
class Q1:
print("\nQ1.")
def calculate(min, max, step):
# 请用你的程式补完这个函式的区块
total=0
for i in range(min, max+1, step): #第三格表示每次循环递加的值
if i<=max+1:
total=total+i
print("印出 "+str(total))
calculate(1, 3, 1) # 你的程式要能够计算 1+2+3,最后印... | jamieyu0914/WeHelp-Bootcamp | WeHelp-Stage1/week-2/py.py | py.py | py | 4,045 | python | zh | code | 0 | github-code | 90 |
7756797594 | import os
import random
from app.constants import *
from app.states.components.button import Button
from app.states.state import State
class CardPickupScreen(State):
def __init__(self, game, player, enemies):
super().__init__(game)
self.game = game
self.player = player
self.enemie... | onecrazygenius/cursedmage | app/states/card_pickup.py | card_pickup.py | py | 3,206 | python | en | code | 3 | github-code | 90 |
19013057015 | class Solution:
def __helper (self, i, n, k, temp_ans):
while (i <= n):
temp_ans.append(i)
if ((k - 1) == 0): self.res.append(list(temp_ans))
else: self.__helper(i + 1, n + 1, k - 1, temp_ans)
temp_ans.pop()
i += 1
def combine (self, n: int, k... | Tejas07PSK/fraz-leetcode-hot-250 | Recursion/combinations.py | combinations.py | py | 430 | python | en | code | 1 | github-code | 90 |
11150133134 | import string
from typing import List, Dict
ALPHABET = string.digits + string.ascii_letters
class NumeralSystem:
"""
A numeral system used to represent integers.
"""
_symbols: str
_base: int
_chunksize: int
_pow_base: int
_cache: List[str]
_reverse: Dict[str, int]
__slots__ ... | JozsefKutas/project-euler-math | project_euler_math/numeralsystem.py | numeralsystem.py | py | 2,750 | python | en | code | 0 | github-code | 90 |
34585822020 | '''
描述
任意输入一个字符,判断其ASCII是否是奇数,若是,输出YES,否则,输出NO
例如,字符A的ASCII值是65,则输出YES,若输入字符B(ASCII值是66),则输出NO
输入
输入一个字符
输出
如果其ASCII值为奇数,则输出YES,否则,输出NO
'''
s=input()
if ord(s)%2==1:
print("YES")
else:
print("NO")
| gxmls/Python_NOI | RE/NOI1-4-04.py | NOI1-4-04.py | py | 387 | python | zh | code | 0 | github-code | 90 |
35247032165 | import colorManagement
from typing import List, Tuple
import time
class colorCycle:
def __init__(self, colors: List, cycleTime: int = 1, width: int = 1, step: int = 1, brightness:float = 1) -> None:
self.__colorList = colorManagement.listToRGBList(colors)
self.cycleTime = cycleTime
self._... | MagePhenix/piZeroRGB | Keyboard Controled Leds/colorCycle.py | colorCycle.py | py | 3,457 | python | en | code | 0 | github-code | 90 |
18119718779 | import math
while(True):
if input() == '0':
break
a = list(map(int, input().split()))
m = sum(a) / len(a)
b = 0
for i in a:
b += (i - m) ** 2.0
stddev = math.sqrt(b / len(a))
print(stddev)
| Aasthaengg/IBMdataset | Python_codes/p02381/s730711561.py | s730711561.py | py | 233 | python | en | code | 0 | github-code | 90 |
74922511656 | import os
import warnings
import pandas as pd
# Supress warnings
warnings.filterwarnings("ignore")
# SPECIFY PATHS HERE
PATH_TO_CLEAN_DATA_FOLDER = '../data/combined_labels/cleaned_data_full'
PATH_TO_SAVE = '../data/combined_labels/combined_full.csv'
filenames = os.listdir(PATH_TO_CLEAN_DATA_FOLDER)
df = pd.DataFra... | austenjs/UnderwaterIdentification | data_cleaning/combine_data.py | combine_data.py | py | 524 | python | en | code | 0 | github-code | 90 |
37733681539 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 26 08:20:10 2017
@author: cristinamenghini
"""
import os
import json
import threading
import time
from sys import argv
from ParseInfoscience import *
# When you want to run that file you need to insert the path of the folder which contains the html sources
script, path... | CriMenghini/modERN | DataCleaning.py | DataCleaning.py | py | 3,845 | python | en | code | 1 | github-code | 90 |
7018432946 |
from Garedami.Src.Annouce import *
from Garedami.Src.Problem import LittleCmd, Problem
from Garedami.Src import Config
from subprocess import Popen, PIPE, STDOUT
from os import path
import os
from time import sleep
def IsFloat(content: str):
try:
content = float(content)
return content
exc... | Nepumi-Jr/Garedami | Src/Run.py | Run.py | py | 4,748 | python | en | code | 0 | github-code | 90 |
34647627381 | from functools import partial
from bluesky.utils import short_uid
import bluesky.plan_stubs as bps
import bluesky.preprocessors as bpp
def future_count(detectors, num=1, delay=None, *, per_shot=None, md=None):
"""
Take one or more readings from detectors.
Parameters
----------
detectors : list
... | NSLS-II-PDF/profile_collection | startup/98-jog_scans.py | 98-jog_scans.py | py | 3,741 | python | en | code | 0 | github-code | 90 |
15294815276 | import os
import subprocess
import glob
import shutil
import sqlite3
from tabnanny import verbose
from re import search
sScriptPath = os.path.dirname(os.path.realpath(__file__)) + "/"
sConfigPath = sScriptPath + "config.py"
sDatabasePath = sScriptPath + "contents.db"
sRootPath = '' # to be defined for first time in f... | kyle-mckay/ffmpeg-py | ffmpeg.py | ffmpeg.py | py | 22,044 | python | en | code | 0 | github-code | 90 |
15954228277 | import os
import re
from typing import List
from cachetools import TTLCache, cached
from flask_sqlalchemy_session import current_session
from sqlalchemy import String, or_
from sqlalchemy.orm import load_only
from sqlalchemy.sql.functions import func
from sqlalchemy.sql.expression import cast
from billparser.db.model... | Congress-Dev/congress-dev | backend/congress_api/db/chamber_queries.py | chamber_queries.py | py | 8,888 | python | en | code | 11 | github-code | 90 |
25426740547 | from django.shortcuts import render
from django.views.generic import ListView
from django.views.generic.detail import DetailView
from .models import Document, News, Tariff
class NewsDetailView(DetailView):
model = News
template_name = "news/detail.html"
class NewsListView(ListView):
model = News
te... | NikitaGrishchenko/homeowners-association | reference/views.py | views.py | py | 920 | python | en | code | 0 | github-code | 90 |
74367190697 | import sys
prec = {'(': 0, '|': 1, '·': 2, '*': 3}
# Add the concatenation operator · to the regexp, make an empty string explicit
def augment(src):
if not src:
return 'ϵ'
dst = []
for i in range(len(src)):
if i > 0 and not (src[i] in '|)*' or src[i - 1] in '(|'):
dst.append('... | c0stya/brzozowski | match.py | match.py | py | 3,882 | python | en | code | 77 | github-code | 90 |
17413397253 |
import numpy as np
def evaluate_metrics(y_true, y_pred, num_of_classes=2): # num_of_classes: 1) 'background' and 2) 'marked ROI'
class_wise_iou_coeff = []
class_wise_dice_score = []
y_true = np.around(y_true)
y_pred = np.around(y_pred)
tol_val = 0.00001 # Define tolerance val
for i... | mabdulkareem/lav_volume_with_qc | 2_Image_Segmentation/compute_metrics_seg.py | compute_metrics_seg.py | py | 862 | python | en | code | 0 | github-code | 90 |
40581923556 | """
129. Sum Root to Leaf Numbers
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
Example:
Inp... | venkatsvpr/Problems_Solved | LC_Sum_root_to_leaf_numbers.py | LC_Sum_root_to_leaf_numbers.py | py | 1,665 | python | en | code | 3 | github-code | 90 |
3850089226 | from django.forms import *
from .models import Review
class ReviewForm(ModelForm):
class Meta:
model = Review
fields = ['anonymous', 'rating', 'comment']
widgets = {
'anonymous': CheckboxInput(attrs={'class': 'form-check-input'}),
'rating': Select(attrs={'class': 'f... | cen4010/geek-text-webapp | webapp/book_details/forms.py | forms.py | py | 667 | python | en | code | 1 | github-code | 90 |
18493203759 | first = str(input())
second = str(input())
"""
def cycleis(start, dici, seen):
curr = start
#print("Curr: {}".format(curr))
while seen[curr] != 1:
#print("Bent Curr: {}".format(curr))
seen[curr] = 1
curr = dici[curr]
if curr not in seen:
return True
if curr =... | Aasthaengg/IBMdataset | Python_codes/p03252/s518945725.py | s518945725.py | py | 1,551 | python | en | code | 0 | github-code | 90 |
40593595315 | L = ['banana','leite','maca','ovo','pao','uva','biscoito','suco']
pos = -1
x = input("Digite um item que deseja buscar na lista :")
for i in range(len(L)) :
if x == L[i]:
pos = i
print("Posição do item '"+ x +"' é : ", pos)
if pos == -1 :
print("Non foundei):") | fernandamserra/IC-Nivelamento | Lista 3/quesito1.py | quesito1.py | py | 291 | python | pt | code | 0 | github-code | 90 |
23411363041 | import io
import sys
class SearchTreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def add_child_node(self, node):
if node.value < self.value:
if self.left == None:
self.left = node
else:
self.left.add_child_node(node)
else:
if self.right == No... | Bearmarshal/advent-of-code-2020 | Dag 1/day1.py | day1.py | py | 3,237 | python | en | code | 0 | github-code | 90 |
31499178908 | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from matplotlib import rcParams
#rcParams['font.family'] = "Linux Libertine O"
rcParams['text.usetex'] = True
rcParams['text.latex.unicode'] = True
"""ex10.a"""
def Dconv(var, t):
x1, x2 = var
return [x1**2 - x2**2, 2*x1*x2]
... | nvasilas/gct | ps2/src/ex1.py | ex1.py | py | 762 | python | en | code | 0 | github-code | 90 |
31597414866 | # coding:utf-8
__author__ = 'cluo'
import fasttext
import jieba
import argparse
import pymysql
import os
def add_company_name():
conn = pymysql.connect(host='localhost', port=3306, user='geek', passwd='tomcat', db='infoadmin', charset='utf8')
cursor = conn.cursor()
sql = "select company_name,company_full_... | luckycluo/fastTextCategory | py2.7/src/fastText/fastText.py | fastText.py | py | 2,482 | python | en | code | 0 | github-code | 90 |
4803852940 | # get GC content with default 1000bp sliding windows.
# usage:
# python3 get_ref_genome_GC.py ref_genome.fasta output_filename
# input:
# ref: reference genome in fasta format
# out: output file name
# output:
# a dataframe, which has CHR, Start_Position and GC columns
def computeGC(seq):
try:
gc ... | avallonking/ForestQC | ForestQC/get_ref_genome_GC.py | get_ref_genome_GC.py | py | 1,349 | python | en | code | 21 | github-code | 90 |
23959902462 | def pluralize(x):
"May not always be accurate. Add exceptions as you find them. See https://www.grammarly.com/blog/plural-nouns/"
# Add to this
exceptions = {
"bus": "buses",
"gas": "gasses",
"roof": "roofs",
"halo": "halos",
"fish": "fish",
"belief... | ericl16384/old-python-projects | plurals.py | plurals.py | py | 1,842 | python | en | code | 0 | github-code | 90 |
71315842218 | #注意输入输出格式怎么搞
#键值互换
'''
a_dict={'a':11,'b':22,'c':33}
b_dict={}
for i in a_dict:
b_dict[a_dict[i]]=i
print(b_dict)
'''
#统计单词出现次数
sentence = input("请输入一串字符:")
# 将所有单词转换为小写,避免大小写造成的重复计算
sentence = sentence.lower()
# 分割单词
words = sentence.split()
# 创建一个空字典,用于存储每个单词出现的次数
word_count = {}
# 遍历单词列表,统计每个单词出现的次数
for wo... | GP-Bullet/daily-life | Python/book/1.py | 1.py | py | 896 | python | zh | code | 2 | github-code | 90 |
24703789674 | import simplejson as json # outside library renamed as json
import os
# Creating a new file (tmp until written)
newfile =open("newfile.txt", "w+")
# some basic content to write
string = "This will be the content of the txt file."
# write the string to the file and create it
newfile.write(string)
'''
tr... | insanepoet/PythonLearningPlayground | WorkingWithFiles/main.py | main.py | py | 1,007 | python | en | code | 1 | github-code | 90 |
21211513165 | from torch.utils import data
#from einops import rearrange
from yacs.config import CfgNode as CN
from utils.brain_data import *
from utils.transforms import to_tensor, random_flip_rotate
class Dataset(data.Dataset):
def __init__(self, img, label, transform=None):
self.img = img
self.label =... | huqian999/UDA-MIMA | build_adadataset.py | build_adadataset.py | py | 7,794 | python | en | code | 1 | github-code | 90 |
22541793561 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" Usage:
textgrid_import.py wav_file textgrid_file
This script will import a wav file and a textgrid file into MySQL database
"""
import tgt
import os
import glob
import configparser
import mysql.connector
from shutil import copyfile
import sys
MEDIAPATH='/opt... | chainwu/lang-tools | tdb/textgrid_import.py | textgrid_import.py | py | 2,463 | python | en | code | 0 | github-code | 90 |
18344933649 | #!/usr/bin python3
# -*- coding: utf-8 -*-
def main():
N, K = map(int, input().split())
S = input()
ret = 0
for i in range(1,N-1):
if (S[i]=='L' and S[i-1]=='L') or (S[i]=='R' and S[i+1]=='R'):
ret += 1
if S[0]=='R' and S[1]=='R':
ret += 1
if S[N-1]=='L' and S[N-2]==... | Aasthaengg/IBMdataset | Python_codes/p02918/s856330812.py | s856330812.py | py | 409 | python | en | code | 0 | github-code | 90 |
69794241577 | from __future__ import annotations
from typing import Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[Li... | kkmax1015/LeetCode | bin/app/python/21_Merge_Two_Sorted_Lists.py | 21_Merge_Two_Sorted_Lists.py | py | 1,140 | python | ja | code | 0 | github-code | 90 |
73562706535 | import csv, os
from nltk import sent_tokenize
def write_to_csv(text_dict: dict, filename: str) -> None:
# real labelled as 1, fake labelled as 0
fieldnames = ["index", "text", "label"]
with open(file=filename, mode='w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)... | debashishc/classification-real-fake-text | CreateFiles.py | CreateFiles.py | py | 1,377 | python | en | code | 1 | github-code | 90 |
12315430303 | from django.shortcuts import render
from server.models import server, session
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, Http404
from django.utils import simplejson
from server.forms import ServerForm
def home(request):
s = server.objects.all().order_by('status'... | adambratt/MineHound | server/views.py | views.py | py | 1,618 | python | en | code | 1 | github-code | 90 |
11202235677 | from alembic import op
import sqlalchemy as sa
# Revision identifiers, used by Alembic. Do not change.
revision = '872a895b8e8'
down_revision = '1d2eddc43366'
def upgrade():
"""Fix server defaults for DATETIME columns, because
0 ("0000-00-00 00:00:00") is deprecated as default for those colum types
as ... | htm-community/skeleton-htmengine-app | repository/migrations/versions/002_872a895b8e8_fix_datetime_and_timestamp_defaults.py | 002_872a895b8e8_fix_datetime_and_timestamp_defaults.py | py | 673 | python | en | code | 18 | github-code | 90 |
23174642957 | import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.styles import NamedStyle, Font, PatternFill, Border, Side
class ColumnsConvert:
def __init__(self, writer, sheet):
# self.file_path = file_path
# self.wb = openpyxl.load_workbook(file_path)
# self.ws = self.wb.active... | Lincon04/salesGenerateReports | rows_convert.py | rows_convert.py | py | 2,867 | python | pt | code | 0 | github-code | 90 |
18384094518 | from __future__ import annotations
import datetime
import logging
import json
import os
from abc import abstractmethod
from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional, Protocol, runtime_checkable
from ..errors import MissingExtraRequire
from ..utils import copy_doc, MISSING
try:
impo... | TheMaster3558/toppy | toppy/webhook/cache.py | cache.py | py | 8,567 | python | en | code | 2 | github-code | 90 |
21199658411 | # leetcode 21. Merge Two Sorted Lists
# author: ender
# https://leetcode.com/problems/merge-two-sorted-lists/
#Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
from typing import Optional
class Solution:
def mergeTwoList... | endermeihl/ender.github.io | leetcode2023/L21.py | L21.py | py | 1,156 | python | en | code | 0 | github-code | 90 |
22821892425 | # -*- coding: utf-8 -*-
import json
import re
from decimal import Decimal
from adminsortable.fields import SortableForeignKey
from adminsortable.models import SortableMixin
from ckeditor_uploader.fields import RichTextUploadingField
from colorful.fields import RGBColorField
from django.core.exceptions import Validatio... | kebasyaty/django-editor-ymaps | djeym/models.py | models.py | py | 61,072 | python | en | code | 21 | github-code | 90 |
17977971919 | from collections import deque
import sys
input = sys.stdin.readline
n = int(input())
edges = [[] for i in range(n)]
for _ in range(n-1):
a, b = map(int, input().split())
edges[a-1].append(b-1)
edges[b-1].append(a-1)
todo = deque([(0, 1), (n-1, 2)])
colors = [0] * n
colors[0] = 1
colors[-1] = 2
while t... | Aasthaengg/IBMdataset | Python_codes/p03660/s285308334.py | s285308334.py | py | 617 | python | en | code | 0 | github-code | 90 |
18211958879 | import sys
import math
stdin = sys.stdin
def ni(): return int(ns())
def na(): return list(map(int, stdin.readline().split()))
def ns(): return stdin.readline().rstrip() # ignore trailing spaces
N = ni()
AB_array = [na() for _ in range(N)]
# print(AB_array)
plus_dic = {}
minus_dic = {}
ans = 1
fish_count =... | Aasthaengg/IBMdataset | Python_codes/p02679/s055504467.py | s055504467.py | py | 1,495 | python | en | code | 0 | github-code | 90 |
24643159772 | #!/usr/bin/env python3
"""
The Linux filesystem abbreviator such that
there is no ambiguity for each directory
when pressing TAB
The program assumes that the input folder is valid
"""
from typing import Dict, List
import os
def path_join(path: List[str])->str:
"""
Joins all directories in `path`
`path` is... | Pegasust/linux_tricks | scripts/short_cwd_display/abbreviator.py | abbreviator.py | py | 2,383 | python | en | code | 0 | github-code | 90 |
70667671018 | import os
import sqlite3
import pandas as pd
from grandexchange.wiki_api import (
get_1h_history,
get_all_dates,
get_item_mapping
)
class GrandExchangeDB:
def __init__(self, update_data: bool = True):
self.all_dates = get_all_dates()
self.db_file = '../data/osrs_ge.sqlite'
se... | jdidcote/osrs-ge-prices | grandexchange/database.py | database.py | py | 3,553 | python | en | code | 0 | github-code | 90 |
5003058201 | DB_USER = 'postgres'
DB_DB = 'postgres'
DB_PORT = 5432
TAG_CSV_FILE = 'src/db/QueryResults.csv'
NO_COMPANY_EMAILS = [
'gmail',
'hotmail',
'yahoo',
'outlook'
]
NEXMO_SENDER = 'Unstuck'
__all__ = [
'DB_USER',
'DB_DB',
'DB_PORT',
'TAG_CSV_FILE',
'NO_COMPANY_EMAILS',
'NEXMO_SEND... | felixarpa/unstuckoverflow | api/src/__init__.py | __init__.py | py | 326 | python | en | code | 8 | github-code | 90 |
14053877852 | from newsapi.newsapi_client import NewsApiClient
from textblob import TextBlob
# Init
def newsapi(stock):
# newsapi_symbol = input("Enter a symbol")
newsapi = NewsApiClient(api_key='861ff0ffbaaa4eaa9571ce516cc5e088')
all_articles = newsapi.get_everything(q=stock,
... | harmitsampat96/Stock-Market-Forecasting | newsSentimentAnalysis.py | newsSentimentAnalysis.py | py | 2,452 | python | en | code | 0 | github-code | 90 |
29794151995 | import google.protobuf.compiler.plugin_pb2 as plugin_pb2
import google.protobuf.descriptor_pb2 as descriptor_pb2
import io
import sys
from . import options_pb2
import jinja2
#loader = jinja2.FileSystemLoader('.')
jinja2_env = jinja2.Environment(
#loader = loader,
loader = jinja2.PackageLoader('protonium'),
... | zyp/protonium | protonium/generator.py | generator.py | py | 7,923 | python | en | code | 1 | github-code | 90 |
34057573263 | # Write a function that removes all occurrences of a given letter from a string.
def letterRemove(string , letter):
"""Removes all instances of given letter from given string"""
result = ""
for chr in string:
if chr != letter:
result = result + chr
return result
print(letterRe... | sentrygun/bark | stringstest7.py | stringstest7.py | py | 339 | python | en | code | 0 | github-code | 90 |
72483731818 | import math
import torch
from torch.optim.optimizer import Optimizer
class AdamG(Optimizer):
"""
General version of Adam-SRT that works for different normalization layer
if specific channel options (channel_dims, channel_wise, channel_gloabal)
are given.
It should be used on parameters that are s... | ymontmarin/adamsrt | adamsrt/optimizers/adam_g.py | adam_g.py | py | 7,207 | python | en | code | 8 | github-code | 90 |
7491560900 | from django.urls import path
from . import views
urlpatterns = [
path('home/', views.home, name='blog-home'),
path('about/', views.about, name='blog-about'),
path('new/', views.newTransaction , name = 'new-transaction'),
path('new/grouptransaction/<int:g_id>', views.newgroupTransaction , name = 'newgr... | harsh760/django-splitme | splitme/blog/urls.py | urls.py | py | 1,137 | python | en | code | 0 | github-code | 90 |
18541026579 | import sys
from collections import Counter
input = sys.stdin.readline
def main():
N = int(input())
A = list(map(int, input().split()))
S = [0] * (N+1)
for i in range(N):
S[i+1] = S[i] + A[i]
c = Counter(S)
ans = 0
for v in c.values():
ans += v*(v-1)//2
print(ans)
i... | Aasthaengg/IBMdataset | Python_codes/p03363/s838770027.py | s838770027.py | py | 357 | python | en | code | 0 | github-code | 90 |
41077628532 | import cv2
# Đường dẫn tới hình ảnh
image_path = "anh1.jpg"
# Đọc hình ảnh
image = cv2.imread(image_path)
# Tọa độ của bounding box (x, y, width, height)
bounding_box1 = (235, 225, 347, 494)
bounding_box2 = (239,236 , 347, 494)
# Tạo một hình chữ nhật để vẽ bounding box
# x, y, width, height = bounding_box
# cv2.rec... | Dinhtobi/abc | YOLOdudoan.py | YOLOdudoan.py | py | 1,642 | python | vi | code | 0 | github-code | 90 |
32535928968 | import tempfile
import auto_archive
from loguru import logger
from configs import Config
from storages import Storage
def main():
c = Config()
c.parse()
logger.info(f'Opening document {c.sheet} to look for sheet names to archive')
gc = c.gsheets_client
sh = gc.open(c.sheet)
wks = sh.get_work... | marklindsey11/Archiver-Belingcat | auto_auto_archive.py | auto_auto_archive.py | py | 695 | python | en | code | 0 | github-code | 90 |
4297110588 | from statistics import mean
import pandas as pd
from matplotlib import pyplot
from numba import jit
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import KFold, cross_val_score, LeaveOneOut
@jit
def kFolds():
for k in folds:
# define the test condition
cv = KFold(n... | Kinga-Jaworska/Project_Klawiatura_Flask | keyTest.py | keyTest.py | py | 2,606 | python | en | code | 0 | github-code | 90 |
41836668600 | def get_optimizer(optimizer_name, params, learning_rate, l2_weight_decay):
if optimizer_name == 'SGD':
from torch.optim import SGD
optimizer = SGD(params=params, lr=learning_rate, weight_decay=l2_weight_decay)
elif optimizer_name == 'Adam':
from torch.optim import Adam
optimizer... | 96jhwei/Genetic-U-Net | code/train/util/get_optimizer.py | get_optimizer.py | py | 926 | python | en | code | 14 | github-code | 90 |
20585071344 | import os
from dotenv import load_dotenv
load_dotenv()
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = os.getenv('SECRET_KEY', default='None')
DEBUG = False
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.con... | aleksospishev/foodgram-project-react | backend/foodgram/foodgram/settings.py | settings.py | py | 4,094 | python | en | code | 0 | github-code | 90 |
31538560427 | from load_voxels import Voxels
import json
import os
import sys
import numpy as np
import itertools
directory = os.path.join(sys.path[0], 'srg_components')
meta_name = 'meta.json'
files = ['srg_components_r/*.voxels']
voxels_per_unit = 25.4
with open(os.path.join(directory, meta_name), 'r') as f:
meta_from_json =... | thomas-schweich/CADPotential | voxel/construct.py | construct.py | py | 2,083 | python | en | code | 3 | github-code | 90 |
25444499857 | import tkinter
from tkinter.font import Font
from pprint import pprint
from demo61_counter import Counter, c1
# class Counter:
# def __init__(self, value):
# self.value = value
#
#
# c1 = Counter(0)
top = tkinter.Tk()
selector1 = tkinter.IntVar()
selector1.set(1)
x1 = 0
x2 = [0]
def notifier():
def... | viviyin/bdpy | demo60_tk1.py | demo60_tk1.py | py | 3,584 | python | en | code | 0 | github-code | 90 |
74946851495 | # -*- coding: utf-8 -*-
"""
Problem 174 - Counting the number of "hollow" square laminae that can form one,
two, three, ... distinct arrangements
We shall define a square lamina to be a square outline with a square "hole" so
that the shape possesses vertical and horizontal symmetry.
Given 8 tiles it is ... | yred/euler | python/problem_174.py | problem_174.py | py | 1,252 | python | en | code | 1 | github-code | 90 |
27637659694 | import time
import sys
if len(sys.argv) < 2:
print("Please Provide VCF to filter")
print("usage python3 Mu;tiallelicIndelFilter NameofVcfFile")
sys.exit(1)
vcf_file= sys.argv[1]
def MultiallelicVariantCoverageeliminator(vcf_file):
print("Parsing VCF file...")
variants=0
start_ti... | vinaydeep26/ASE_Pipeline_SCSU | MultialleleicIndelFilter.py | MultialleleicIndelFilter.py | py | 1,767 | python | en | code | 0 | github-code | 90 |
14841803059 | from flask import Flask,request,render_template
from datetime import date
import subprocess
import pandas as pd
import joblib
import xgboost as xgb
import numpy as np
import knnclass
import knnstop
from sklearn.impute import KNNImputer
model = joblib.load('C:/Users/sangh/Downloads/Comding/BTP2/Prediction/x/flight_xgb... | yASH-2025/Flight-Price-Prediction | app.py | app.py | py | 8,122 | python | en | code | 3 | github-code | 90 |
6187793302 | import json
import boto3
import uuid
def lambda_handler(event, context):
print(event)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('ducks')
body = json.loads(event["body"])
duck = {"uuid": str(uuid.uuid4()),"name": body["name"], "age": body["age"], "color": body["color"].upper()}
... | EpiTobby/DuckAPI | terraform/plateform_3/lambda/create_duck.py | create_duck.py | py | 670 | python | en | code | 0 | github-code | 90 |
7354169308 | import re
import os
import subprocess
import xml.etree.ElementTree as ET
import StringIO
from collections import deque, Counter
from sys import argv
ET.register_namespace('', 'http://www.w3.org/1998/Math/MathML')
class MathML:
"""
List of ecognized tags
"""
math = '{http://www.w3.org/1998/Math/MathML}... | shamim8888/tangent | tangent/symboltree.py | symboltree.py | py | 15,710 | python | en | code | null | github-code | 90 |
408145458 | # imports
import sys
# ======================================= ceaser_decryption ======================================= #
#function: ceaser_decryption
# parameters: 2, str_encrypted_text(string), int_shift(integer)
# return: 1, plain_text(string)
# functionality: decrypts the input encryption text with the shif... | NadaElokaily/Encryption-cli-app | app/src/ceaser/ceaser_decryption.py | ceaser_decryption.py | py | 1,454 | python | en | code | 0 | github-code | 90 |
18237653759 | import sys
from collections import defaultdict, Counter, namedtuple, deque
import itertools
import functools
import bisect
import heapq
import math
MOD = 10 ** 9 + 7
# MOD = 998244353
# sys.setrecursionlimit(10**8)
n = int(input())
A = list(map(int, input().split()))
if n % 2 == 0:
dp = [[-float("inf")] * 2 for i... | Aasthaengg/IBMdataset | Python_codes/p02716/s905759837.py | s905759837.py | py | 1,050 | python | en | code | 0 | github-code | 90 |
41992131768 | n=int(input())
a=list(map(int,input().split()))
a.sort()
middle=n//2
before=n//2
after=n//2
while before>0 and a[middle]==a[before-1]:
before-=1
while after<n-1 and a[middle]==a[after+1]:
after+=1
if(before==(n-1-after)):
print(a[middle])
else:
print(-1) | kuzma-long/ccf | codes/ccf 201612-1.py | ccf 201612-1.py | py | 270 | python | en | code | 0 | github-code | 90 |
9004917398 | """
Program: Chess
av: Olof Svedvall
version 0.3
"""
import sys
from chessboard import Chessboard
class Program():
def __init__(self):
self.chessboard = Chessboard()
self.message = ''
def play(self):
while self.message != 'q':
try:
self.message = input('>... | Androm517/python-games | Chess/chess.py | chess.py | py | 607 | python | en | code | 0 | github-code | 90 |
9934247682 | import logging
import argparse
import sys
import os
from azure.kusto.data import KustoConnectionStringBuilder, DataFormat
from azure.kusto.ingest import QueuedIngestClient, IngestionProperties, FileDescriptor
class KustoIngest:
CONFIG_FILE_NAME = "config-kusto.json"
CONFIG_BLOB_PATH = "config-kusto.json"
... | jithinjosepkl/mpi-perf | kusto_ingest.py | kusto_ingest.py | py | 2,158 | python | en | code | 0 | github-code | 90 |
39390917833 | from collections import defaultdict, deque
from pathlib import Path
def read_input(file: str) -> list:
with open(Path(file)) as file:
return [line.strip() for line in file]
def parse_data(input_data) -> dict:
parents = defaultdict(list)
for line in input_data:
words = line.split()
... | DankersW/advent_of_code | 2020/day_07/part1.py | part1.py | py | 1,120 | python | en | code | 0 | github-code | 90 |
22363400829 | import cv2
import numpy
import weather
from datetime import datetime
from datetime import timedelta
IMG = {"clear sky": "01d.png", "few clouds": "02d.png", "scattered clouds": "03d.png",
"broken clouds": "04d.png", "overcast clouds": "04d.png", "shower rain": "09d.png",
"light rain": "09d.png", "... | waitold/tenki-jouhou | src/img_edit.py | img_edit.py | py | 1,606 | python | en | code | 0 | github-code | 90 |
910344246 | import cv2
import logging
from os import path
class CachedFaceDetector(object):
_face_detector = None
_cache_manager = None
def __init__(self, face_detector, cache_factory):
self._face_detector = face_detector
self._cache_manager = cache_factory.manager('face_bounding_box',
... | vitoralbiero/drl_action_unit_detection | fexp/detector/cached_face_detector.py | cached_face_detector.py | py | 861 | python | en | code | 2 | github-code | 90 |
2706376394 | import torch
import torch.nn as nn
from torch.autograd import Variable
import pickle
import time
import argparse
import os
from utils.meter import AverageMeter
from torch.utils.data import DataLoader
from config import dataset as ds
from utils.log import log
from utils.metrics import getaccuracy
from utils.data import... | manoja328/RN | train.py | train.py | py | 8,925 | python | en | code | 0 | github-code | 90 |
21313800415 | import matplotlib
import random
import numpy as np
import multiprocessing as mp
import time
import sys
from scipy.integrate import dblquad
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from math import pi,sqrt,cos,sin,atan,e,log,exp
import os
from scipy.interpolate import interp1d #Beth 6/23... | grim137/quadrature | 2Dlist.py | 2Dlist.py | py | 2,273 | python | en | code | 0 | github-code | 90 |
678568317 |
import torch
def num_digits(n):
if n == 0:
return torch.tensor(1).long()
return torch.tensor(torch.floor(torch.log10(n)) + 1).long()
def tensor_to_int(input, device=torch.device('cuda')):
if device == torch.device('cpu'):
# Not as concerned with CPU performance.
if input.dim() ==... | arthurfeeney/ALSHConv | lsh/hash_utils.py | hash_utils.py | py | 1,191 | python | en | code | 1 | github-code | 90 |
8828065882 | from utils.utils_loader import *
from preprocess.filter.yying_non_event_filter import EffectCheck
base = "/home/nfs/cdong/tw/origin/"
files = fi.listchildren(base, fi.TYPE_FILE, concat=True)
file = files[571]
my_filter = EffectCheck()
twarr = fu.load_array(file)
print(len(twarr), '->', len(my_filter.filter(twarr, 0.4... | leeyanghaha/my_merge | preprocess/filter/test_filter.py | test_filter.py | py | 324 | python | en | code | 0 | github-code | 90 |
20253970157 | import math
# Простейшие арифметические операции (1)
# Написать функцию arithmetic, принимающую 3 аргумента: первые 2 - числа, третий - операция,
# которая должна быть произведена над ними. Если третий аргумент +,
# сложить их; если —, то вычесть; * — умножить; / — разделить (первое на второе).
# В остальных случаях ... | Bulgakoff/code_abbey | lesson04/tests_py.py | tests_py.py | py | 3,295 | python | ru | code | 0 | github-code | 90 |
32956467578 | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# --------------------------- FUNCTIONS -------------------------------
def get_file(file):
# Returns the full path, if the file is in the same folder as the main .py program.
return os.path.join(os.path.dirname(file), file)
de... | FrankMeijering/WB3575-Group-9 | tools.py | tools.py | py | 7,615 | python | en | code | 2 | github-code | 90 |
18016471199 | N = int(input())
A = list(map(int, input().split()))
A.sort()
def check(sz):
# print("check:", sz)
skp = False
cannot_eat = False
check = sz
for i in A:
if skp == False and sz == i:
skp = True
continue
if i > check * 2:
cannot_eat = True
... | Aasthaengg/IBMdataset | Python_codes/p03786/s952616219.py | s952616219.py | py | 618 | python | en | code | 0 | github-code | 90 |
17250751940 | from telebot import types
import telebot
from ipcamara import ipcamara
from contador_vehiculos import contador_vehiculos
from datetime import datetime
def estado_trafico():
umbral_med = 4
umbral_alto = 10
umbral_congestion = 20
lista_de_valores = []
promedio_fecha_hora = {}
resultad... | conterbot/conter-telegram | telegram_bot.py | telegram_bot.py | py | 3,682 | python | es | code | 2 | github-code | 90 |
23420460615 | from unittest import TestCase
from pysagepay.address import SagePayAddress
import ast
class TestAddress(TestCase):
def setUp(self):
self.address = SagePayAddress(address_type='billing')
self.test_dict = {
'BillingPostCode': None,
'BillingFirstnames': None,
'Billi... | RossLote/sagepy | tests/test_address.py | test_address.py | py | 7,425 | python | en | code | 0 | github-code | 90 |
18362690339 | N, K = [int(v) for v in input().split(' ')]
A = [int(v) for v in input().split(' ')]
sum_A = sum(A)
max_A = max(A)
def make_divisor(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n // i)
... | Aasthaengg/IBMdataset | Python_codes/p02955/s861820833.py | s861820833.py | py | 915 | python | en | code | 0 | github-code | 90 |
31349418386 | from stable_baselines3.common.callbacks import BaseCallback, EventCallback
from stable_baselines3.common.vec_env import VecEnv, DummyVecEnv, sync_envs_normalization
from stable_baselines3.common.evaluation import evaluate_policy
from typing import Any, Dict, Union, Optional
import warnings
import gym
import os
i... | sberg17/DSF-APC | utils/callbacks.py | callbacks.py | py | 7,275 | python | en | code | 0 | github-code | 90 |
33627859143 | from typing import Union
import torch
from torch.utils.data import Dataset
Tensor = torch.Tensor
class TrajectoryDataset(Dataset):
"""Stores trajectories and time grids.
Used to store trajectories `y` and the corresponding time grids `t`.
Each trajectory is assumed to have three dimensions:
(ti... | yakovlev31/msvi | msvi/dataset.py | dataset.py | py | 1,444 | python | en | code | 3 | github-code | 90 |
2302109745 | from tensorflow import keras
from Utils.metrics import jaccard_score, jaccard_score_true_class, dice_coef
from Utils.losses import weighted_jaccard_loss, jaccard_loss
import os
from pathlib import Path
from Utils.dataset import Dataset, Dataloder
from Utils.visuals import visualize_edges, visualize, denormalize
from Ut... | snorbi95/polyp_segmentation_project | Segmentation networks/Object-Edge ensemble/object_edge_ensemble.py | object_edge_ensemble.py | py | 7,219 | python | en | code | 0 | github-code | 90 |
12045287053 | import praw
import json
from datetime import datetime
with open("../../settings.json", "r") as f:
settings = json.loads(f.read())
reddit = praw.Reddit(client_id=settings["reddit"]["client_id"],
client_secret=settings["reddit"]["client_secret"],
user_agent=settings["reddit"]["user_agent"])
data = []
for s... | mdiller/MangoByte | resource/dev/showerthoughts_getter.py | showerthoughts_getter.py | py | 704 | python | en | code | 83 | github-code | 90 |
40340482610 | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import re
pd.options.mode.chained_assignment = None
# Parameters
global fig
global ax
first_digit_4 = [0, 0, 1, 1]
second_digit_4 = [0, 1, 0, 1]
first_digit_9 = [0, 0, 0, 1, 1, 1, 2, 2, 2]
second_digit_9 = [0, 1, 2, 0, 1, 2, 0, 1, 2]
first_digi... | Gigibeau/TWNBA_sweepplotter | TWNBA_sweepplotter.py | TWNBA_sweepplotter.py | py | 6,580 | python | en | code | 0 | github-code | 90 |
3018187902 |
"""Config YAML Tests"""
from torchlego.config import YAMLConfig, process_yaml_config
FILE_CONTENTS = '''
models:
- name: resnet50
download: https://artifactory/model-download-link
gpu: true
stages:
input: file
preprocess:
default: image_classification
- name: resnet50
downloa... | prabhuomkar/bitbeast | torchlego/tests/config/test_yaml.py | test_yaml.py | py | 1,046 | python | en | code | 19 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.