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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
39793721281 | # Binary Search
# Given Given: Two positive integers n≤105 and m≤105, a sorted array A[1..n] of integers from −105 to 105 and a list of m integers −105≤k1,k2,…,km≤105.
# Return: For each ki, output an index 1≤j≤n s.t. A[j]=ki or "-1" if there is no such index.
def Bsearch(A,k):
m = int(len(A)/2)
right = le... | suxian06/rosalind | BINS.py | BINS.py | py | 837 | python | en | code | 0 | github-code | 90 |
43939810126 | class Maze:
def __init__(self):
# Open the file:
fh = open("maze1.txt", "r")
content = fh.readlines()
# maze_array is a two-dimensional array with the entire maze (integers):
maze_array = []
# Fill maze_array with numbers from file:
for... | BornaMD/Exam-Assignment-CP4EOR-18 | robot_class.py | robot_class.py | py | 2,984 | python | en | code | 1 | github-code | 90 |
18236012859 | # -*- conding: utf-8 -*-
import math
N = int(input())
S = input()
count_R = 0
count_G = 0
count_B = 0
for s in S:
if s == "R":
count_R += 1
elif s == "G":
count_G += 1
else:
count_B += 1
count = 0
for i in range(N-2):
for j in range(i+1, (N+1+i)//2):
if S[i] != S[j] and S[i] != S[j+(j-i)] and ... | Aasthaengg/IBMdataset | Python_codes/p02714/s870884423.py | s870884423.py | py | 400 | python | en | code | 0 | github-code | 90 |
15588896685 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 2 15:29:56 2022
@author: Dell
"""
from tkinter import*
from PIL import ImageTk,Image
from tkinter import filedialog
import os
import webbrowser
import tkinter.messagebox as msg
root = Tk()
root.minsize(700,700)
root.maxsize(700,700)
open_img = ImageT... | RuhaanKalla/project-c-160-162 | untitled8.py | untitled8.py | py | 2,077 | python | en | code | 0 | github-code | 90 |
41184443211 | import pymongo
import os
MONGODB_URI = os.getenv("MONGO_URI")
DBS_NAME = "macTestDB"
COLLECTION_NAME = "macDB"
def mongo_connect(url):
try:
conn = pymongo.MongoClient(url)
print("Mongo is connected!")
return conn
except pymongo.errors.ConnectionFailure as e:
print("Could not co... | MACmidiDEV/MongoDB | mongoUpdate.py | mongoUpdate.py | py | 678 | python | en | code | 0 | github-code | 90 |
10602750500 | # import required libraries
from colorama import Fore as Colour
import colorama
import requests
import random
import threading
import time
import json
import os
# colours for windows
if os.name != "posix":
colorama.init(convert=True)
# load payload
files = os.listdir()
for f in files.copy():
if not f.endswith(".jso... | jibstack64/dogdown | dogdown.py | dogdown.py | py | 2,298 | python | en | code | 2 | github-code | 90 |
42268330204 | import sys
sys.stdin = open('hws/algorithm/0922/input.txt', 'r')
T = int(input())
for t in range(1, T+1):
N, M = map(int, input().split())
containers = sorted(list(map(int, input().split())), reverse=True) # 오름차순 정렬
trucks = sorted(list(map(int, input().split()))) # 내림차순 정렬
total ... | junhong625/TIL | Algorithm/SWEA/D3/5201_컨테이너 운반.py | 5201_컨테이너 운반.py | py | 897 | python | ko | code | 2 | github-code | 90 |
5101046828 | n=int(input())
d={}
for i in range(n):
si=''.join(list(sorted(input())))
d[si]=d.get(si, 0)+1
ans=0
for v in d.values():
if(v>1):
ans+=v*(v-1)//2
print(ans) | WAT36/procon_work | procon_python/src/atcoder/virtual/ABC137-C.py | ABC137-C.py | py | 177 | python | de | code | 1 | github-code | 90 |
19017638085 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __flattenHelper (self, root):
if (root == None): return None
head, tail = root, root
... | Tejas07PSK/lb_dsa_cracker | Binary Search Trees/Flatten BST to sorted list/solution1.py | solution1.py | py | 1,139 | python | en | code | 2 | github-code | 90 |
18262084339 | n,m = map(int,input().split())
rule = [list(map(int,input().split())) for i in range(m)]
jj = 0
if n == 1:
for i in range(0,10**n):
jud = 0
for j in range(m):
if int(str(i)[rule[j][0]-1]) != rule[j][1]:
jud =1
if jud == 0:
print(i)
jj = 1
... | Aasthaengg/IBMdataset | Python_codes/p02761/s163586577.py | s163586577.py | py | 607 | python | en | code | 0 | github-code | 90 |
15653090998 | from flask_wtf import FlaskForm
from wtforms import SubmitField,StringField,PasswordField
from wtforms.validators import DataRequired,ValidationError
from app.models import Users
class LoginForm(FlaskForm):
admin = StringField(
label="管理员账号",
validators=[
DataRequired("账号不能为空!")
... | liwg1995/NiceCatMonitor | app/forms.py | forms.py | py | 1,148 | python | en | code | 0 | github-code | 90 |
39224885651 | import requests
from relevanceai import config
from relevanceai.auth import Auth
from relevanceai._request import handle_response
from relevanceai.steps.vector_search import VectorSimilaritySearch
from typing import Any, Dict, List, Optional, Union
class Dataset:
def __init__(
self,
id: str,
... | RelevanceAI/relevanceai | relevanceai/datasets.py | datasets.py | py | 3,288 | python | en | code | 75 | github-code | 90 |
36700570824 | import numpy as np
import math
from python_qt_binding.QtCore import Qt, QMetaType, QDataStream, QVariant, pyqtSignal
from python_qt_binding import loadUi
from rqt_gui_py.plugin import Plugin
from python_qt_binding.QtWidgets import QWidget, QTreeWidget, QTreeWidgetItem, QListWidgetItem, \
QSlider, QGroupBox, QVBoxLa... | MosHumanoid/bitbots_thmos_meta | bitbots_misc/bitbots_live_tool_rqt/scripts/quarter_field.py | quarter_field.py | py | 19,241 | python | en | code | 3 | github-code | 90 |
8970237836 | # simple dictionary with famous dog names and their associated breed
pets = {
'lassie': 'rough collie',
'poe': 'labradoodle',
'toto': 'cairn terrier',
'tinkerbelle': 'chihuahua',
'sophie': 'cocker spaniel',
'bo': 'labradoodle'
}
# loop through a sorted dictionary
for name, breed in sorted(pets.... | rynsnz/python_work | matthes/06 - Dictionaries/day12_100.py | day12_100.py | py | 531 | python | en | code | 0 | github-code | 90 |
7159749401 | from __future__ import print_function
import numpy as np
import cv2
import smbus
import time
import sys
import sgbm
import pickle
# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)
# This is the address we setup in the Arduino Program
address = 0x04
def send2uno(direction,num):
data = directio... | wunianchen/Collector-Tivan | stereo/cv2_tracking_camshift_rot.py | cv2_tracking_camshift_rot.py | py | 8,757 | python | en | code | 0 | github-code | 90 |
7700608878 | import random
# Створюємо словник з 20 випадковими числами
random_dict = {}
for i in range(21):
random_dict[i] = random.randint(0, 100)
# Обчислюємо добуток всіх значень словника
product = 1
for value in random_dict.values():
product *= value
# Виводимо словник та результат множення
print("Згенеро... | tolstopiatova/hilel_homework | 7th_lesson_2.py | 7th_lesson_2.py | py | 560 | python | uk | code | 0 | github-code | 90 |
28887323257 | # kaggle submit functionality
import sys
import numpy as np
import pandas as pd
import itertools as it
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.experimental import PeepholeLSTMCell
from tensorflow.keras.layers import TimeDistributed
from tensorflow.keras.layers import RepeatVect... | pedroMoya/M5_kaggle_accuracy_KAGGLE_M5_A_share | 8_SUBMISSION_DIR/kaggle_submit_module.py | kaggle_submit_module.py | py | 16,127 | python | en | code | 2 | github-code | 90 |
32087613560 | n = int(input())
a = []
for i in range(n):
a.append(list(map(int,input().split())))
for i in a:
rank = 1
for j in a:
if i[0] < j[0] and i[1] < j[1]:
rank += 1
print(rank,end = ' ') | denmark-dangnagui/baekjoon | 7568.py | 7568.py | py | 217 | python | en | code | 0 | github-code | 90 |
12742150542 | import curses
from pprint import pprint
import textwrap
from typing import List
from dotenv import dotenv_values
from dashboard.config_file import ConfigFile
accepted_protocols = ["http", "https", "ws", "wss", "peer"]
env_config = dotenv_values('.env')
def generate_config_screen(stdscr):
row = 5
column = 1... | mvadari/xrpl-node-detective | dashboard/config.py | config.py | py | 5,058 | python | en | code | 0 | github-code | 90 |
14303313474 | # User info wrapper object
import logging
class User(object):
"""
Wrapper object around an entry in users.json. Behaves like a read-only dictionary if
asked, but adds some useful logic to decouple the front end from the JSON structure.
"""
_NAME_KEYS = ["display_name", "real_name"]
_DEFAULT_IM... | hfaran/slack-export-viewer | slackviewer/user.py | user.py | py | 2,188 | python | en | code | 807 | github-code | 90 |
27929099597 | import functools
import operator
import random
from os import urandom
from crypto_commons.generic import xor, long_to_bytes
def encrypt(key, data, mask):
state_len = len(key)
keystream = key_extend(len(data), key, mask, state_len)
data = "".join([bin(ord(c))[2:].zfill(8) for c in data])
result = xor(... | arty-hlr/CTF-writeups | 2019/CONFidence_finals/lfsr/for_players/challenge.py | challenge.py | py | 1,391 | python | en | code | 1 | github-code | 90 |
4597965722 | """
A small tool to figure what is really going on within a sanely formatted RDF/owl file.
In my case, was to parse a BioPax lvl3 owl file containing the data from Reactome.org database
"""
import xml.etree.ElementTree as ET
# Updating the readability Dict with what is required for expected functionning if the applica... | chiffa/XmlDoctor | rdfDoctor.py | rdfDoctor.py | py | 6,387 | python | en | code | 0 | github-code | 90 |
26528941073 | import simpy
import random
class Station:
def __init__(self, env, id, ap, cwmin=16, cwmax=1024):
self.env = env
self.id = id
self.ap = ap
self.cwmin = cwmin
self.cwmax = cwmax
self.backoff = 0
def transmit(self):
print(f"Station {self.id} is trying to tr... | fullcircle/MACLayerSimulation | main.py | main.py | py | 2,460 | python | en | code | 0 | github-code | 90 |
24214406051 | # 숨바꼼질3
import sys
from collections import deque
def BFS(N, K):
queue = deque()
queue.append(N) # 위치, 시간
while queue:
X = queue.popleft()
if X == K:
return visited[X]
# 수빈이가 이동할 수 있는 방법은 3가지
for next_x in (X-1, X+1, X*2):
if 0 <= next_x < 10... | WebProject-STT/Algorithm | prev/baekjoon/9주차/13549/13549_jy.py | 13549_jy.py | py | 2,196 | python | en | code | 0 | github-code | 90 |
72024517736 | "Сервис работы с объектами, обнаруженными в логах"
from __future__ import annotations
from typing import Any, List, Dict, Set
import logging
from core import EventsEmitter, Atype0, Atype1, Atype2, Atype3, Atype5, Atype6, Atype7, Atype9, \
Atype10, Atype11, Atype12, Atype16, Atype17, Atype18
from configs import Co... | lastick1/rexpert | services/objects_service.py | objects_service.py | py | 9,161 | python | en | code | 1 | github-code | 90 |
729118946 | # methods from content_based_recsys.ipynb
import random
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
def drop_duplicates(df):
"""
Drop duplicate songs
"""
df['artists_song'] = df.apply(lambda row: row['artist_name'] + row['track_name'], axis=1)
return df.drop_duplica... | marja-w/mms-project-23 | recommender_model/scripts/data_handling.py | data_handling.py | py | 4,754 | python | en | code | 0 | github-code | 90 |
10433568177 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
import pandas as pd
def main():
filepath = sys.argv[1] #filepath to yelp yelp-dataset
# Load jsonl file
# tips_dataset = []
# with open(filepath+'/tip.json', encoding='utf8') as json_file:
# yelp_dataset = list(json_file)
... | clrpoon/EECS-396-Introduction-to-the-Datascience-Pipeline | submission1/part1.py | part1.py | py | 2,306 | python | en | code | 1 | github-code | 90 |
18114771869 | memo = {}
def solve(p, t):
key = "{}:{}".format(p, t)
if key in memo: return memo[key]
if p >= len(A): return False
if t == A[p]: return True
if t <= 0: return False
#print("({}, {})".format(p, t))
if solve(p + 1, t):
memo["{}:{}".format(p + 1, t)] = True
return True
else:
memo["{}:{}".form... | Aasthaengg/IBMdataset | Python_codes/p02271/s608419647.py | s608419647.py | py | 546 | python | en | code | 0 | github-code | 90 |
16040964705 | import datetime
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# 私有属性 以两个_开始
self.__money = 1000
def test(self):
self.__money += 10 # 在这里可以访问私有属性
def get_money(self):
print("{}查询了余额".format(datetime.datetime.now()))
r... | EricWord/PythonStudy | 15-oop/oop_demo11.py | oop_demo11.py | py | 1,286 | python | zh | code | 0 | github-code | 90 |
18379596989 | def ApplePie():
N, L = input().split()
N = int(N)
L = int(L)
flavors = []
for i in range(N):
flavors.append(L+i)
if 0 in flavors:
flavors.remove(0)
result = 0
for i in flavors:
result = result + i
print(result)
exit()
elif L >=... | Aasthaengg/IBMdataset | Python_codes/p02994/s789780387.py | s789780387.py | py | 628 | python | en | code | 0 | github-code | 90 |
18556265429 | from collections import defaultdict
import sys
sys.setrecursionlimit(10**7)
def dfs(v,t,f,used):
if v==t:
return f
used[v]=True
for nv,cap in G[v].items():
if not used[nv] and cap>0:
d=dfs(nv,t,min(f,cap),used)
if d>0:
G[v][nv]-=d
G[nv]... | Aasthaengg/IBMdataset | Python_codes/p03409/s648399368.py | s648399368.py | py | 976 | python | en | code | 0 | github-code | 90 |
41458360378 | import sys
from dataclasses import dataclass
from pathlib import Path
import numpy as np
import pytest
from icecream import ic
EXAMPLE = """R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2"""
# --> Puzzle solution
@dataclass
class Position:
row: int = 0
col: int = 0
def log(self, trail):
trail[(self.row, self.... | j-carson/advent_2022 | days/09/part1.py | part1.py | py | 2,818 | python | en | code | 0 | github-code | 90 |
19165410548 | '''
Description: simple
Author: young
Date: 2022-08-19 10:07:04
LastEditTime: 2022-08-19 10:13:57
FilePath: \young_leetcode\数组\1.数组的遍历\1450.在既定时间做作业的学生人数.py
'''
'''
给定两个整数数组,分别表示第i个同学做作业的开始时间和结束时间
给定一个查询时间queryTime,返回该时刻正在做作业的学生的人数
'''
def busyStudent(startTime, endTime, queryTime):
# 直接对endtime进行遍历
#... | JNUYoung/Leetcode-Record | 数组/1.数组的遍历/1450.在既定时间做作业的学生人数.py | 1450.在既定时间做作业的学生人数.py | py | 1,295 | python | zh | code | 0 | github-code | 90 |
37591961503 | import os
import random
from torch.utils.data import Dataset
from PIL import Image
import numpy as np
from datasets.data_io import get_transform, read_all_lines
import torch
class MultiLabelDataset(Dataset):
def __init__(self, list_filename, training):
self.training = training
self.data =... | binwangh/MyNetworks | datasets/multilabel_dataset.py | multilabel_dataset.py | py | 1,221 | python | en | code | 0 | github-code | 90 |
12879087523 | import argparse
import torch
import sys
import os
sys.path.insert(0, os.path.abspath('./utils'))
import tracker_utils
import network_utils
import video_stream_utils
import model_utils
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--confidence_score",
type=float,
default=0.9... | urs-waldmann/i-muppet | muppet.py | muppet.py | py | 5,446 | python | en | code | 4 | github-code | 90 |
70809082538 | def test():
expression = input()
count = 0
for char in expression:
if char == '(':
count += 1
elif char == ')':
if count == 0:
print('incorrect')
return
count -= 1
if count == 0:
print('correct')
else:
... | Dsbaule/INE5452 | Lista 2 - Ad-Hoc e ordenação e Estrutura de Dados/09 - Parenthesis Balance I.py | 09 - Parenthesis Balance I.py | py | 410 | python | en | code | 0 | github-code | 90 |
28946971464 | path = "input.csv"
csvreader = open(path, mode='r', encoding='UTF8')
txtwriter = open("00_buy_package_new.txt", mode='w', encoding='utf-8-sig')
c_line = csvreader.readline()[:-1]
popneed = c_line.split(',')
while True:
c_line = csvreader.readline()[:-1]
if not c_line:
print("작업 완료")
... | MAPPON6766/Vic-3-buy-package-generator | main.py | main.py | py | 902 | python | en | code | 1 | github-code | 90 |
19490569528 | from django.urls import path
from . import views
app_name='product'
urlpatterns = [
path('get-price/', views.getprice, name='getprice'),
path('wishlist/', views.mywishlist, name='wishlist'),
path('mycart/', views.mycart, name='mycart'),
path('newsletter/', views.newsletter, name='newsletter'),
... | ashwinthorali/zincronia | product/urls.py | urls.py | py | 1,666 | python | en | code | 0 | github-code | 90 |
13564163351 | """
Test Cases for Counter Web Service
Create a service that can keep a track of multiple counters
- API must be RESTful - see the status.py file. Following these guidelines, you can make assumptions about
how to call the web service and assert what it should return.
- The endpoint should be called /counters
- When cr... | danielogen/CS-472-672-2023-CI-LAB | tests/test_counter.py | test_counter.py | py | 2,157 | python | en | code | 0 | github-code | 90 |
11043557953 | import logging
import numpy as np
from neuralprophet.plot_model_parameters_matplotlib import plot_custom_season, plot_daily, plot_weekly, plot_yearly
from neuralprophet.plot_utils import set_y_as_percent
log = logging.getLogger("NP.plotting")
try:
from matplotlib import pyplot as plt
from matplotlib.dates i... | ourownstory/neural_prophet | neuralprophet/plot_forecast_matplotlib.py | plot_forecast_matplotlib.py | py | 18,867 | python | en | code | 3,415 | github-code | 90 |
10627008763 | import os
import cv2
import sys
import json
import time
import numpy as np
import tensorflow as tf
from pprint import pprint
from darkflow.defaults import argHandler
from helpers.FileVideoStream import FileVideoStream
FLAGS = argHandler()
FLAGS.setEnvDefaults()
FLAGS.parseArgs(sys.argv)
if FLAGS.yolo:
from yolo.... | Dmitriy-Fedorov/env_detector | video2json_0.2.2.py | video2json_0.2.2.py | py | 2,033 | python | en | code | 0 | github-code | 90 |
24180264489 | import random
from copy import deepcopy
# Othello - 4 x 4 board version
########################### ボックス #####################################
class Box:
def __init__(self, empty):
self.empty = empty
self.marker = empty
def empty_box(self):
return self.marker == self.empty
def... | ksawada1/ksawada-school-projects | OthelloAI/othello_random.py | othello_random.py | py | 8,287 | python | en | code | 0 | github-code | 90 |
23260558790 | from wsgiref import validate
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from todoApp.models import List, User
from .serializers import ListSerializer, UserSerializer
from rest_framew... | PhilipK-webdev/ToDo | todoApp/views.py | views.py | py | 1,878 | python | en | code | 0 | github-code | 90 |
43121598207 | from django.contrib import admin
from .models import Librarys, LibrarysStorage, Librarian, LibrarysInLibrarian
'''list_display - какие атрибуты будут выводится на экран
list_display_links - какие атрибуты будут ссылками
search_fields - по каким полям будет происходить поиск
list_editable - какие поля можно изменить в ... | IgorCurukalo/first1 | first/app/librarys/admin.py | admin.py | py | 2,756 | python | en | code | 0 | github-code | 90 |
18327150059 | import math
n = int(input())
ans = n-1
x = int(math.ceil(math.sqrt(n)))
for i in range(1, x+1):
if n%i == 0:
ans = int(min(ans, i+n/i-2))
print(ans)
| Aasthaengg/IBMdataset | Python_codes/p02881/s790906658.py | s790906658.py | py | 164 | python | en | code | 0 | github-code | 90 |
30950889660 | import trio
from kabomu.abstractions import IQuasiHttpConnection,\
QuasiHttpProcessingOptions, DefaultTimeoutResult
from kabomu import quasi_http_utils
class SocketConnection(IQuasiHttpConnection):
def __init__(self,
socket,
client_port_or_path,
processing_op... | aaronicsubstances/kabomu-python | examples/shared/SocketConnection.py | SocketConnection.py | py | 1,844 | python | en | code | 0 | github-code | 90 |
35223989629 | import warnings
import copy
import inspect
import threading
import numpy as np
import Orange.data
from Orange.base import ReprableWithPreprocessors
from Orange.data.util import SharedComputeValue, get_unique_names
from Orange.misc.wrapper_meta import WrapperMeta
from Orange.preprocess import RemoveNaNRows
from Orang... | biolab/orange3 | Orange/projection/base.py | base.py | py | 10,259 | python | en | code | 4,360 | github-code | 90 |
1929504551 | # -*- coding: utf-8 -*-
"""
Created on Mon May 20 09:02:03 2019
@author: Clement LAGNEAU
"""
import numpy as np
"""
-1: sortie
0 : libre
2 : mur
"""
def baground(n):
t=np.zeros((n,n),int)
for x in range(n):
t[0,x]=2
t[x,0]=2
t[n-1,x]=2
t[x,n-1]=2
return(t)
def baground_t... | clementlagneau/TIPE-2019 | TIPE/numpy/ba_num_v0.py | ba_num_v0.py | py | 483 | python | en | code | 0 | github-code | 90 |
38813119287 | n=0
YBandera=0
while True:
try:
partNum1 = ""
partNum2 = ""
watPart = 0
a = input()
for i in range(len(a)):
if a[i]==" ":
watPart = 1
elif watPart==0:
partNum1 = partNum1 + a[i]
elif watPart==1:
partNum2 = partNum2 + a[i]
a = int(partNum1)
b = int(partNum2)
aAux = a;
bAux = b;
... | josnez/ProgramasC | GrupoGUMP/3nmas1.py | 3nmas1.py | py | 726 | python | en | code | 0 | github-code | 90 |
5136153937 | from typing import Optional, Union
from .node import Node
from .size_node import SizeNode
NodeType = Union[Node, SizeNode]
def build_bst(items) -> NodeType:
if not items:
return None
root = Node(items.pop(0))
for item in items:
insert(root, item)
return root
def node_factory(NodeCo... | kyleaisho/dsa | dsa/trees/binary_tree/binary_tree_utils.py | binary_tree_utils.py | py | 3,039 | python | en | code | 0 | github-code | 90 |
40370793447 | import torch
import torch.nn as nn
class LossNegSampling(nn.Module):
def __init__(self, vocab_size, emb_dim):
super(LossNegSampling, self).__init__()
self.embedding_u = nn.Embedding(vocab_size, emb_dim) # embedding u
self.logsigmoid = nn.LogSigmoid()
... | fatemehsrz/SiHet | loss.py | loss.py | py | 1,574 | python | en | code | 0 | github-code | 90 |
18374001789 | def getN():
return int(input())
def getNM():
return map(int, input().split())
def getList():
return list(map(int, input().split()))
def getArray(intn):
return [int(input()) for i in range(intn)]
def input():
return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
return random.randint(ran1,... | Aasthaengg/IBMdataset | Python_codes/p02985/s832120930.py | s832120930.py | py | 2,355 | python | en | code | 0 | github-code | 90 |
17932042859 | #!/usr/bin/env python3
import sys
def solve(H: int, W: int, c: "List[List[int]]", A: "List[List[int]]"):
#print(*c, sep='\n')
for k in range(10):
for i in range(10):
for j in range(10):
c[i][j] = min(c[i][j], c[i][k]+c[k][j])
#print(*c, sep='\n')
cost = 0
for a ... | Aasthaengg/IBMdataset | Python_codes/p03546/s311547142.py | s311547142.py | py | 1,090 | python | en | code | 0 | github-code | 90 |
19152428454 | # Private variable names
# Variable naming - PEP8
# module names = all_lower_case
# class and exception names = CamelCase
# global and local name = all_lower_case
# function names = all_lower_case
# constants = ALL_CAPS
# variable naming with public and private
# public attributes/variables = regular_lower_case
# priv... | Otumian-empire/python-oop-blaikie | 05. Advanced Features/0504.py | 0504.py | py | 984 | python | en | code | 0 | github-code | 90 |
418961865 | from typing import Any, Dict, List, Type, TypeVar, Union
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
T = TypeVar("T", bound="AgentConfiguration")
@_attrs_define
class AgentConfiguration:
"""The agent configuration describes the attestation ... | smallstep/smallstep-python | smallstep/api_client/models/agent_configuration.py | agent_configuration.py | py | 3,295 | python | en | code | 2 | github-code | 90 |
70098241897 | from datetime import datetime
from operator import itemgetter
from random import sample
from .models import *
from django.contrib.sessions.models import Session
from django.core.mail import send_mail
from django.conf import settings
from django.template.loader import render_to_string
def get_customer_session(reques... | Emmelien1508/oleadabeads_temp | webshop/utils.py | utils.py | py | 10,247 | python | en | code | 0 | github-code | 90 |
20906561392 | from __future__ import print_function
from __future__ import division
import json
import base64
import os
import numpy as np
import gzip
import six
import functools
import paddle.fluid as fluid
from reader.batching import pad_feature_data, pad_batch_data
class ClassifyReader(object):
"""ClassifyReader"""
def... | PaddlePaddle/Research | NLP/UNIMO/src/reader/visual_entailment_reader.py | visual_entailment_reader.py | py | 8,928 | python | en | code | 1,671 | github-code | 90 |
16465691493 | from typing import List
from moco_wrapper.util.endpoint import Endpoint
from moco_wrapper.models import objector_models as om
from moco_wrapper.models.base import MWRAPBase
from enum import Enum
class CompanyType(str, Enum):
"""
Enumeration of the type of companies that exist. Can be used to supply the ``co... | sommalia/moco-wrapper | moco_wrapper/models/company.py | company.py | py | 14,199 | python | en | code | 2 | github-code | 90 |
18146591879 | text = ''
key= input().lower()
while True:
s = input()
if s.find("END_OF_TEXT") >= 0: break
try:
text += s + ' '
except:
break
print([x.lower() for x in text.split(" ")].count(key) ) | Aasthaengg/IBMdataset | Python_codes/p02419/s055470319.py | s055470319.py | py | 216 | python | en | code | 0 | github-code | 90 |
19957408335 | from typing import Callable
def do_stuff(end: int, op: Callable[[int], int]) -> int:
return op(end)
def mul_numbers(end: int) -> int:
total = 1
for i in range(1, end):
total *= i
return total
def sum_numbers(end: int) -> int:
total = 0
for i in range(end):
total += i
retur... | dariobig/Esercizietti | sum_numbers.py | sum_numbers.py | py | 1,187 | python | en | code | 0 | github-code | 90 |
16571072327 | """
从后向前遍历,用while
依次比较排序
不使用额外的控件,因为num1后面是空着的,所以优先从后向前排
"""
from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
size1 = m - 1
siz... | superggn/myleetcode | array/easy/88-merge-sorted-array-2.py | 88-merge-sorted-array-2.py | py | 1,156 | python | zh | code | 0 | github-code | 90 |
18309944819 | #import sys
#import numpy as np
import math
#import itertools
#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=int(input())
a=list(input())
a=list(map(int,a))
ans=0
for i i... | Aasthaengg/IBMdataset | Python_codes/p02844/s530918498.py | s530918498.py | py | 642 | python | en | code | 0 | github-code | 90 |
12831027981 | from __future__ import division
import argparse
import os
import itertools
import json
from functools import partial
from multiprocessing import Pool
import numpy as np
import numdifftools as nd
from scipy.optimize import bisect
import matplotlib.pyplot as plt
from displ.build.build import _get_work, band_path_labels
f... | tflovorn/displ | displ/kdotp/efield.py | efield.py | py | 21,828 | python | en | code | 6 | github-code | 90 |
1646072615 | import socket
import ssl
import sys
CERTIFICATE = sys.argv[1]
KEY = sys.argv[2]
HOST = "localhost"
PORT = 5003
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(CERTIFICATE, KEY)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADD... | louisleclair/Master | MA1/TCP:IP/Lab3/ex5/secure_pmu.py | secure_pmu.py | py | 903 | python | en | code | 0 | github-code | 90 |
18389808229 | N,M=map(int,input().split())
res = 0
flag = True
#任意の数Kに対してたどり着く通り数
INF = 100000000000
stepList = [INF]*(N+1)
stepList[0] = 1
stepList[1] = 1
def stepF(K):
if K == 0:
return stepList[0]
else:
for i in range(1,K+1):
if i == 1:
pass
else:
if stepList[i]==INF:
stepList[i]=... | Aasthaengg/IBMdataset | Python_codes/p03013/s448726996.py | s448726996.py | py | 828 | python | en | code | 0 | github-code | 90 |
382956219 | # -*- coding: utf-8 -*-
import scrapy
from scrapy.selector import Selector
from ..items import MovieItem
#<span class="other"> / 月黑高飞(港) / 刺激1995(台)</span>
#//*[@id="content"]/div/div[1]/ol/li[1]/div/div[2]/div[2]/p[1]
class MovieSpider(scrapy.Spider):
name = 'movie'
allowed_domains = ['movie.douba... | WhiteBrownBottle/Python- | DouBan/DouBan/spiders/movie.py | movie.py | py | 2,439 | python | en | code | 0 | github-code | 90 |
71145263018 | ###########################
# SERVER BASE FACTORY
###########################
from twisted.internet import reactor, protocol
from twisted.protocols.basic import LineReceiver
from twisted.internet.protocol import Factory
from twistedBase import TwistedBase
from const import EventTypes, EnvMapping, EVENT_HANDLER_SERVER... | tvoegt/generic-twisted-handler | serverBase.py | serverBase.py | py | 3,701 | python | en | code | 0 | github-code | 90 |
9197916827 | import collections
class Solution:
def minimumIncompatibility(self, nums, k):
n = len(nums)
m = 1 << n
if n == k: return 0
cnt = n // k
dp = [float('inf')] * m
value = collections.defaultdict()
for i in range(0, m):
visited = set()
flag... | TPIOS/LeetCode-cn-solutions | 1681_2.py | 1681_2.py | py | 1,265 | python | en | code | 0 | github-code | 90 |
12515819241 | import sys, pathlib, os, shlex, logging
import argh
from gi.repository import Gtk, Gdk, GdkPixbuf
class Images:
def __init__(self, directory):
self.images = [str(x) for x in pathlib.Path(directory).glob("*.jpg") if x.is_file()]
self.images += [str(x) for x in pathlib.Path(directory).glob("*.png") ... | dvolk/pyimgsort | main.py | main.py | py | 3,740 | python | en | code | 0 | github-code | 90 |
12591066533 | # pylint: disable=no-self-use
"""
ResInsight caf::PdmObject connection module
"""
from functools import partial, wraps
import grpc
import re
import builtins
import importlib
import inspect
import sys
import PdmObject_pb2
import PdmObject_pb2_grpc
import Commands_pb2
import Commands_pb2_grpc
from typing import Any, ... | OPM/ResInsight | GrpcInterface/Python/rips/pdmobject.py | pdmobject.py | py | 18,964 | python | en | code | 151 | github-code | 90 |
34655509158 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import random
import numpy as np
import cv2
import torch.utils.data as data
from MOC_utils.gaussian_hm import gaussian_radius, draw_umich_gaussian
from ACT_utils.ACT_aug import apply_distort, apply_e... | MCG-NJU/MOC-Detector | src/datasets/sample/sampler.py | sampler.py | py | 7,609 | python | en | code | 258 | github-code | 90 |
18165548309 | n = int(input())
a = list(map(int, input().split()))
result = 0
tmp = a[0]
for i in range(1, n):
if tmp >= a[i]:
result += tmp - a[i]
else:
tmp = a[i]
print(result) | Aasthaengg/IBMdataset | Python_codes/p02578/s541054805.py | s541054805.py | py | 182 | python | en | code | 0 | github-code | 90 |
75166867496 | import numpy as np
from sklearn.datasets import load_diabetes
dataset = load_diabetes()
x= dataset.data
y = dataset.target
print(x[:5])
print(y[:10])
print(x.shape, y.shape) #(442, 10) (442,)
print(np.max(x), np.min(y))
print(dataset.feature_names) # ['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']... | lynhyul/AIA | keras/keras46_MC_5_diabetes.py | keras46_MC_5_diabetes.py | py | 3,017 | python | en | code | 3 | github-code | 90 |
74457651817 | from baremetal import *
from cdc import slow_to_fast, slow_to_fast2
def max_adc(clk, adc_clk, command_ready, response_valid, response_channel, response_data):
#reading 10 channels at 500KHz means that each channel gets sampled at 50KHz
#channel sequence 8, 2, 5, 1, 3
#8 = mic
#2 = battery voltage
... | dawsonjon/OpenXcvr | firmware/max10adc.py | max10adc.py | py | 1,500 | python | en | code | 18 | github-code | 90 |
1390433776 | import ast
import re
import numpy as np
import pandas as pd
from nltk.parse.stanford import StanfordDependencyParser as sparse
pathmodelsjar = '~/stanford-english-corenlp-2016-01-10-models.jar'
pathjar = '~/stanford-parser/stanford-parser.jar'
depparse = sparse(path_to_jar=pathjar, path_to_models_jar=pathmodelsjar)
se... | zaqari/NLP17 | Rosen-Zachary-Assgn4/assgn4-depbuilder.py | assgn4-depbuilder.py | py | 6,739 | python | en | code | 0 | github-code | 90 |
18487282913 | class Solution:
def maxProfit(self, prices: list[int]) -> int:
maxNum = 0
for i in range(len(prices)):
for j in range(i, len(prices)):
maxNum = max(maxNum, prices[j] - prices[i])
return maxNum
print(Solution.maxProfit(Solution, prices=[7, 6, 4, 3, 1]))
| comeonboi/algorithm-practise | loong's code/leetcode/editor/cn/121.py | 121.py | py | 311 | python | en | code | 5 | github-code | 90 |
8433954139 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('website', '0002_auto_20151107_0945'),
]
operations = [
migrations.AddField(
model_n... | yinguohang/payjoy-server | PayJoy/website/migrations/0003_auto_20151107_1230.py | 0003_auto_20151107_1230.py | py | 694 | python | en | code | 1 | github-code | 90 |
11028316413 | import logging
from data.logs_model.combined_model import CombinedLogsModel
from data.logs_model.document_logs_model import DocumentLogsModel
from data.logs_model.splunk_logs_model import SplunkLogsModel
from data.logs_model.table_logs_model import TableLogsModel
logger = logging.getLogger(__name__)
def _transition... | quay/quay | data/logs_model/__init__.py | __init__.py | py | 2,066 | python | en | code | 2,281 | github-code | 90 |
38803954449 | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
#===============================================================================
# Filename : check_ssh_file_existence
# Author : Canux CHENG <canuxcheng@gmail.com>
# Description : Check on remote server if some files are present using SSH.
#---------------... | crazy-canux/zplugin | plugin/plugins/check-file-existence/src/check_ssh_file_existence.py | check_ssh_file_existence.py | py | 10,389 | python | en | code | 0 | github-code | 90 |
39729362870 | import matplotlib.pyplot as plt
# Data
gwei = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
nonzero_price = [0.00035, 0.00071, 0.00106, 0.00142, 0.00177, 0.00212, 0.00248, 0.00283, 0.00319, 0.00354]
zero_price = [0.00022,0.00044, 0.00066,0.00087, 0.00109, 0.00131,0.00153, 0.00175, 0.00197, 0.00218]
# Plot
plt.plo... | aaddobea/Data-Visualization-with-Python | Archive-mygraphs-main/IH-IoT.py | IH-IoT.py | py | 1,074 | python | en | code | 0 | github-code | 90 |
18654011878 | import datetime
from babel.numbers import format_currency, get_currency_symbol
from pycoingecko import CoinGeckoAPI
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
CallbackContext,
)
from telegram import Update
from datetime import timedelta
from apscheduler.schedulers.... | jkopka/bc-alert | main.py | main.py | py | 12,234 | python | en | code | 0 | github-code | 90 |
34919150605 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import re
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def find_version(fname):
'''Attempts to find the version number in the file names fname.
Raises RuntimeError if not found.
'''
v... | hernamesbarbara/bitlify | setup.py | setup.py | py | 1,155 | python | en | code | 0 | github-code | 90 |
18940469977 | from predictor.kmer import kmer_featurization
import pandas as pd
import numpy as np
#Tanimoto系数
def tanimoto_coeffcient(x1, x2):
return (x1 * x2).sum() / ((x1 * x1).sum() + (x2 * x2).sum() - (x1 * x2).sum())
def load_disease_sim(disease_sim_path):
disease_sim_graph_df = pd.read_csv(disease_sim_path, heade... | Hql1998/PSnoD_webserver | predictor/prepare.py | prepare.py | py | 3,921 | python | en | code | 0 | github-code | 90 |
16458619569 | # Built into Python
import logging
import datetime
import sqlite3
import requests
import json
import feedparser
# External
from wit import Wit
import arrow
from hackernews import HackerNews # pip install haxor
logging.basicConfig(filename='PiPiLog.txt', level=logging.DEBUG, format=' %(asctime)s - %(level... | bee-san/pipi | main_py_WO_discord.py | main_py_WO_discord.py | py | 10,059 | python | en | code | 1 | github-code | 90 |
25028507572 | #!/usr/bin/env python3
from eif import EIF
from quad import Quad
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
# ------------------------------------------------------------------
# Summary:
# Example of implementation of ekf class on a simple Two-Wheeled Robot system defined... | haydenm2/autonomous_systems_algorithms | extended_information_filter/eif_test.py | eif_test.py | py | 7,065 | python | en | code | 0 | github-code | 90 |
72559705896 | #!/usr/bin/env python3
# Trill test- Mike Cook December 2020
#Test to check trill_lib
from trill_lib import TrillLib
import time
def main():
print("Trill test")
#Uncomment just one of these depending on what type of sensor you have attached
#touchSensor = TrillLib(1, "bar", 0x20)
touchSensor = TrillLib... | Grumpy-Mike/Mikes-Pi-Bakery | Trill Part 1/Software/trill_test.py | trill_test.py | py | 1,702 | python | en | code | 71 | github-code | 90 |
37432541414 | import os, json
from corpus_process import Corpus
files = ['sensitive1.tsv', 'sensitive2.tsv', 'sensitive3.tsv']
tsv_path = [os.path.join(os.pardir, 'data', f) for f in files]
vocabulary_path = os.path.join(os.pardir, 'data', 'vocabulary_corpus.json')
corpus = Corpus(tsv_path)
x, _ = corpus.read_tsv()
vocabulary = ... | WrathXL/preferences_detection_from_text | scripts/corpus_vocabulary.py | corpus_vocabulary.py | py | 513 | python | en | code | 0 | github-code | 90 |
3335777288 | import os
import uuid
from datetime import datetime
from sso.ssh import SSH
from sso.util import run_parallel,log_important
SCYLLA_MONITORING_VERSION="3.6.3"
def download(env, props, iteration):
prometheus = Prometheus(env['prometheus_public_ip'][0],
props['prometheus_user'],
... | michoecho/scylla-stress-orchestrator | src/sso/prometheus.py | prometheus.py | py | 2,398 | python | en | code | null | github-code | 90 |
44806350516 | import random, time, sys
import matplotlib.pyplot as plt
plt.ion()
i_list = []
marks = []
for i in range(1000):
i_list.append(i)
PROBABILITY = i
TIME = 0.5
t1 = time.time()
t2 = t1 + TIME
rn = 0
count = 0
while True:
if time.time() < t2:
if random.randint(... | skuzzymiglet/old-projects | garbage.py | garbage.py | py | 574 | python | en | code | 0 | github-code | 90 |
7155695726 | import logging
import logging.config
import time
import datetime
from dateutil import tz
logger = logging.getLogger()
class MqttActions:
ADDED = "added"
UPDATED = "updated"
DELETED = "deleted"
def decodeBoolean(value):
value = value.decode()
assert value.lower() in ["true", "false"]
state =... | csanz91/IotCloud | python-modules2/source/utils.py | utils.py | py | 1,839 | python | en | code | 3 | github-code | 90 |
30751009123 | import matplotlib
matplotlib.use("Agg")
import numpy
import matplotlib.pyplot as plt
import os
from sys import path
my_home = os.popen("echo $MYWORK_DIR").readlines()[0][:-1]
path.append('%s/work/fourier_quad/'%my_home)
import time
from Fourier_Quad import Fourier_Quad
from sys import argv
from mpi4py import MPI
import... | hekunlie/astrophy-research | selection_bias/CFHT_simu/sym_mc_plot_cfht.py | sym_mc_plot_cfht.py | py | 9,344 | python | en | code | 2 | github-code | 90 |
386948104 | #!/usr/bin/env python3
"""
This is a set of custom CloudFormation resources to help make deployments
easier.
"""
# pylint: disable=C0103
from json import dumps as json_dumps
from logging import getLogger, DEBUG
from typing import Any, Dict
from uuid import uuid4
from cfntoolkit import apigateway, crypto, ec2, s3
impor... | dacut/cfn-toolkit | handler.py | handler.py | py | 2,462 | python | en | code | 1 | github-code | 90 |
9198019050 | r""" Unittest for module `xor.py` in `xorencrytion package`
Usage:
$ python tests\test_xor.py
"""
# import xorencryption package from src directory
import sys
import os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../src")
from xorencryption import XOREncryption
import random
import unittest
class... | AlvifSandana/xorencryption | tests/test_xor.py | test_xor.py | py | 2,430 | python | en | code | 2 | github-code | 90 |
3812294571 | import threading
import time
from collections import deque
import tensorflow as tf
from elasticdl.proto import elasticdl_pb2
from elasticdl.python.common.constants import TaskExecCounterKey
from elasticdl.python.common.log_utils import default_logger as logger
from elasticdl.python.data.reader.data_reader_factory imp... | Kelang-Tian/elasticdl | elasticdl/python/worker/task_data_service.py | task_data_service.py | py | 8,276 | python | en | code | null | github-code | 90 |
5242844798 | from django.core.exceptions import ValidationError
def validate_location(container):
"""
Validation function used to validate the location field of FacadeForm.
This function force the correctly use of commas between city, state and country.
It doesn't allow inputs like: 'city,, state country' or 'city,... | svhenrique/weather-project | core/validators.py | validators.py | py | 873 | python | pt | code | 0 | github-code | 90 |
8464768091 | #coding:utf-8
'''
Created on 2014-12-11
@author: harryhu
'''
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(sys.argv[0])))
from pc_client_protocol import pc_client_protocol_factory
#from twisted.internet.protocol import ClientCreator
from twisted.internet import reactor
class pc_client(object):... | 0814jimmy/devices_control | ctr_client/pc_client.py | pc_client.py | py | 775 | python | en | code | 0 | github-code | 90 |
12287680267 | import networkx as nx
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
def my_jaccard(G,from_id,to_id):
nbrs = list(G.neighbors(from_id))
nbrs_nbrs = []
for nbr in nbrs:
nbrs_nbrs = nbrs_nbrs + list(G.neighbors(nbr))
nbrs_nbrs_set = set(nbrs_nbrs)
try:
... | ninotreve/zhihu-network-mining | 边预测/link predict.py | link predict.py | py | 2,059 | python | en | code | 4 | github-code | 90 |
18250966569 | H, W = map(int, input().split())
S = [input() for _ in range(H)]
vis = [[-1 for i in range(W)] for j in range(H)]
que = [(0,0)]
itr = 0
color = "."
if S[0][0]=="#":
itr=1
color="#"
vis[0][0]=itr
while len(que)>0:
v, h = que.pop(0)
itr = vis[v][h]
if itr%2==0:
color="."
else:
color="#"
que2 = []
... | Aasthaengg/IBMdataset | Python_codes/p02735/s399636670.py | s399636670.py | py | 1,239 | python | en | code | 0 | github-code | 90 |
6950967815 | class Solution:
def toStr(self, pattern, n):
result = ''
for i in range(n):
mask = 1 << (n - i - 1)
if pattern & mask:
result = result + 'Q'
else:
result = result + '.'
return result
def work(self, cur, n, le... | Nov11/punchcarding | 51. N-Queens.py | 51. N-Queens.py | py | 1,064 | python | en | code | 0 | github-code | 90 |
5390818852 |
outcomes = {'A X': [3], 'A Y': [4], 'A Z': [9], 'B X': [1], 'B Y': [5], 'B Z': [9], 'C X': [7], 'C Y': [2], 'C Z': [6]}
outcomes2 = {'A X': [3], 'A Y': [4], 'A Z': [8], 'B X': [1], 'B Y': [5], 'B Z': [9], 'C X': [2], 'C Y': [6], 'C Z': [7]}
my_points = 0
secondstrat = 0
with open("data.txt",'r') as d:
for l... | DamnStr4ight/adventofcode | 2022/02/dec2.py | dec2.py | py | 537 | python | en | code | 0 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.