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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
72680641938 | import sublime
from .debugger_info import Debugger
import os
from os.path import dirname
import sys
from subprocess import Popen, PIPE
import subprocess
from os import path
import shlex
import select
import re
class LLDBDebugger(Debugger):
"""
LLDBDebugger debug cpp programs with
lldb
"""
RUN_PRIOR = 0.5
... | Jatana/FastOlympicCoding | debuggers/Cpp_OSX_Debugger.py | Cpp_OSX_Debugger.py | py | 7,219 | python | en | code | 365 | github-code | 13 |
1235522412 | from secrets import access_key, secret_access_key
import boto3
import os
client = boto3.client('s3',
aws_access_key_id = access_key,
aws_secret_access_key = secret_access_key)
for file in os.listdir():
if '.py' in file:
upload_file_bucket = 'youtube-dummy-... | Derrick-Sherrill/DerrickSherrill.com | automatic_s3_uploader.py | automatic_s3_uploader.py | py | 446 | python | en | code | 307 | github-code | 13 |
9071040680 | import sys
sys.stdin = open("in_out/section2/chapter2/in3.txt", "rt")
def sol(n, s, e, k):
a = n[s-1:e]
a.sort()
return a[k-1]
case = int(input())
for i in range(case):
n_count, s, e, k = map(int, input().split())
n = list(map(int, input().split()))
print("#%d %d" %(i, sol(n, s, e, k)))
p... | mins1031/coding-test | section2/KNum.py | KNum.py | py | 328 | python | en | code | 0 | github-code | 13 |
25588243243 | from random import randint, choice as randchoice
from time import time as current_time
from datetime import timedelta
from input import Box
from constants import Colours
import pygame
import pygame.freetype
import sys
class Generate:
def __init__(self):
# Modify table into sudoku
se... | antony-c/sudoku | sudoku.py | sudoku.py | py | 7,005 | python | en | code | 1 | github-code | 13 |
74907160337 | import cv2 as cv
import numpy as np
img = cv.imread("../../resource/chapter8/opencv-logo.png")
def rotate_bond(img, angle):
h, w, _ = img.shape
cX, cY = w // 2, h // 2
M = cv.getRotationMatrix2D((cX, cY), -angle, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
nW = int((h * sin) + (w * cos... | codezzzsleep/records2.1 | robot-and-vision/test/chapter8/demo03.py | demo03.py | py | 555 | python | en | code | 0 | github-code | 13 |
31392690189 | from pathlib import Path
def advance(line, pos=0, right=3):
pos = (pos + right) % 31
is_tree = True if line[pos] == "#" else False
if is_tree:
return 1, pos
else:
return 0, pos
def go_down(lines, down=1, right=3):
count = 0
pos = 0
for num_line, line in enumerate(lines)... | Gramet/adventofcode | 2020/day3/solution.py | solution.py | py | 1,421 | python | en | code | 0 | github-code | 13 |
8310410816 | from flask_restful import Resource, reqparse
from api.models import Booking
from api.utils import get_customer_data
from bson import ObjectId
parser = reqparse.RequestParser()
parser.add_argument('customer_info', type=dict, required=True, help='Customer information must be a dictionary')
parser.add_argument('booking_... | rohteemie/transafe-booking-service | api/controllers.py | controllers.py | py | 3,752 | python | en | code | 1 | github-code | 13 |
33774429726 | import argparse
import requests
from lxml import etree as ET
class Preprocess():
def __init__(self):
self.severities = {}
def Parser(self):
parser_arg = argparse.ArgumentParser()
parser_arg.add_argument('-A', '--action', help='Action for SM Create/Update default Create', default='Creat... | userpy/selfportal-back | scripts/create_zno.py | create_zno.py | py | 8,283 | python | en | code | 0 | github-code | 13 |
34003351327 | #WHILE LOOP
#WHILE(CONDITION):
#BODY OF THE LOOP
'''
i=1
s=int(input("enter the limit"))
sum=0
while i<=s:
if i%2==0:
sum=sum+i
i=i+1
print(sum)
'''
#print didits
# n=int(input("enter the number"))
# num=n
# sum=0
# while n>0:
# d=n%10
# print(d)
# n=n//10
# sum=sum+d**3
# print("sumo... | mhdsulaimzed/Pycharm-Practice | pythonProject/luminartech/day 1-25/whileloop.py | whileloop.py | py | 846 | python | en | code | 0 | github-code | 13 |
25102975123 | '''
Common utilities
'''
import os
import pwd
import socket
import threading as th
import traceback
import http.client
import logging
import errno
import itertools
import re
import select
import shlex
import psutil
import subprocess
import argparse
from paramiko import SSHClient, AutoAddPolicy
logger = logging.getLog... | Alcereo/LoadTestingToolsCentos | tank/tank_src/yandextank/common/util.py | util.py | py | 18,274 | python | en | code | 0 | github-code | 13 |
40502832385 | from pwn import *
import math
from Crypto.Util.number import inverse
r = remote('134.209.237.231', 4242, level='debug')
r.sendline('challenge')
r.recvuntil('Problem:')
s = r.recvline()
s = s.split(b',')
s = [int(x) for x in s]
m = 0
for i in range(3, len(s)):
x0 = s[i-3]
x1 = s[i-2]
x2 = s[i-1]
x3 =... | forward0606/CTF | CCUISC/Crypto/Crypto/SCIST_LCG/exploit.py | exploit.py | py | 649 | python | en | code | 2 | github-code | 13 |
31704323998 | import random
def makegame(range):
randomnumb = random.randint(0, range)
while True:
guess = int(input('Geef een willekeurig getal: '))
if guess == randomnumb:
print('Goed geraden!')
break
else:
print('Verkeerd')
range = int(input('Geef een bereik: '... | LukaHerrmann/ProjectC_Opdr | Structured_Programming/ForOpdr1/a/randomgame.py | randomgame.py | py | 338 | python | nl | code | 0 | github-code | 13 |
72544325458 | from __future__ import absolute_import
import pprint
import logging
import importlib
from itertools import repeat
import boto3
from botocore.client import Config
from botocore.exceptions import ClientError
from .models import TaskMeta
log = logging.getLogger(__name__)
def import_class(qualname):
parts = qualna... | blitzagency/flowbee | flowbee/utils.py | utils.py | py | 9,489 | python | en | code | 0 | github-code | 13 |
29200447785 | import pprint
import random
w, h = 4, 5;
# Generating a random grid of 0s and 1s
# 0s are blocks and 1s are valid
grid = [
[1, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 1],
[1, 1, 1, 0],
[1, 0, 1, 1]
]
# grid = [[random.randint(0, 1) for x in range(w)] for y in range(h)]
# pprint.pprint(grid)
| SunandanBose/practiceDS | DataStructure/src/main/java/com/raj/robo_nav/robo_nav.py | robo_nav.py | py | 311 | python | en | code | 1 | github-code | 13 |
6662462914 | from typing import NamedTuple, Optional
from datetime import date
from flask import session
from .db import query
from .tables.listings import Listing
from .consts import AMENITIES_CHOICES
def suggest_price(listing: Listing, simulate_extra_amenities=[]):
existing_amenities = listing.amenities.split(', ')
if s... | ThatsJustCheesy/C43-project | mybnb/host_toolkit.py | host_toolkit.py | py | 2,726 | python | en | code | 0 | github-code | 13 |
70587607058 |
import cv2
import json
from pathlib import Path
def check(data_dir, target_dir):
anno_dir = Path(data_dir) / 'annotation'
for img_path in Path(data_dir).glob('./*.png'):
img_name = img_path.stem
anno_file = anno_dir / f'{img_name}.json'
with open(str(anno_file), 'r') as file:
... | dnmca/vfr | src/tools/check_annotation.py | check_annotation.py | py | 733 | python | en | code | 0 | github-code | 13 |
38298409767 | import einstellungen
import pygame
import random
# Bilder
gras_bild = pygame.image.load("bilder/gras.png")
game_over_bild = pygame.image.load("bilder/game_over.png")
game_over_oberfläche = pygame.transform.scale(
game_over_bild,
(einstellungen.BILDSCHIRM_BREITE // 2, einstellungen.BILDSCHIRM_HÖHE // 2),
)
gra... | paulutsch/snake | logik.py | logik.py | py | 6,133 | python | de | code | 0 | github-code | 13 |
31944979469 | from config import *
from functions import *
from graphic_functions import *
from colorset import *
from classes import Teilchen, Sun
import pygame
import matplotlib.pyplot as plt
test_pos = []
liste_teilchen = init_particle_list(100,width,height)
for i in liste_teilchen:
i.velocity = np.array([0,0])
i... | Tyyyr/manythingsfloatinspace | test.py | test.py | py | 1,476 | python | en | code | 0 | github-code | 13 |
40545267325 | """
Base module for the waifu.im API. The API documentation can be found at
https://waifu.im/docs/
"""
import typing
import requests
from anime_api import exceptions
from .types import ImageTag, SearchSort, ImageOrientation
from .objects import Image, _ImageDimensions
class WaifuImAPI:
"""
Docs: https://wai... | Nekidev/anime-api | anime_api/apis/waifu_im/__init__.py | __init__.py | py | 4,973 | python | en | code | 115 | github-code | 13 |
42150680839 | from random import shuffle
def draw():
balls = [x for x in range(1,60)]
shuffle(balls)
numbers = balls[:6]
numbers.sort()
return numbers
def checkResults(ticket, draw):
return draw == ticket
if __name__ == '__main__':
won = False
ticket = draw() # generate our ticket
# simula... | tliesnham/python-lottery | lottery.py | lottery.py | py | 502 | python | en | code | 0 | github-code | 13 |
41643204275 | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
seenMap = {}
maxLength = 0
l = 0
for r in range(len(s)):
if s[r] in seenMap:
l = max(l, seenMap[s[r]]+1)
maxLength = max(maxLength, r-l+1)
seenMap[s[r]]... | ibatulanandjp/Leetcode | #3_LongestSubstringWithoutRepeatingCharacters/solution1.py | solution1.py | py | 354 | python | en | code | 1 | github-code | 13 |
38466919522 | # 7. В одномерном массиве целых чисел определить два
# наименьших элемента. Они могут быть как равны между
# собой (оба являться минимальными), так и различаться.
import random
SIZE = 10 # >1
lst = [random.randint(0, 10) for _ in range(SIZE)]
print(lst)
# решение 1: за линию
def swap_if(a, b):
if a ... | 1frag/alg_and_data | geekbrains/lesson3/7.py | 7.py | py | 748 | python | ru | code | 0 | github-code | 13 |
75041571856 | """Total Ways to Sum - 18"""
from math import ceil
combinations = []
def split(num, other_parts=[]):
for a in range(1, ceil(num/2.0)):
current_combination = [a, num-a]+other_parts
current_combination.sort()
if current_combination not in combinations:
combinations.append(current... | Cynthia7979/bitburner | contract-224193.cct.py | contract-224193.cct.py | py | 601 | python | en | code | 0 | github-code | 13 |
15316892501 | import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# from sklearn.datasets.samples_generator import make_blobs
# Load csv & visualize it
cust_df = pd.read_csv("Cust_Segmentati... | elsheikh21/clustering-techniques | k-means-clustering.py | k-means-clustering.py | py | 1,896 | python | en | code | 0 | github-code | 13 |
3345649973 | '''
https://github.com/DFIR-ORC/dfir-orc/tree/main/src/OrcLib
'''
import ndk, ptypes
from ptypes import *
from ndk.datatypes import *
class _REPARSE_DATA_BUFFER(pstruct.type):
def __PathBuffer(self):
length = self['ReparseDataLength'].li.int()
return dyn.clone(pstr.wstring, length=length)
_fiel... | arizvisa/syringe | template/fs/ntfs.py | ntfs.py | py | 13,363 | python | en | code | 35 | github-code | 13 |
9548607140 |
from rest_framework.decorators import api_view
from rest_framework.response import Response
from base.models import Room
from base.api.serializer import RoomSerializer
@api_view(['GET'])
def getRoutes(request):
routes = [
'GET /api',
'GET / api/rooms',
'GET /api/room/:id'
]
r... | jithinrajmm/chat-room | base/api/views.py | views.py | py | 683 | python | en | code | 0 | github-code | 13 |
28081561200 | import os
from os.path import join as opj
from scipy import spatial
import copy
import numpy as np
import cv2
import pickle
from math import *
def parse_pt(pt_file):
with open(pt_file) as f:
lines = f.readlines()
img_rects = dict()
for line in lines:
line = line.strip().split(',')
... | he010103/Traffic-Brain | AI-City-MTMC/tools/gen_res.py | gen_res.py | py | 2,312 | python | en | code | 15 | github-code | 13 |
32611798190 | def main():
height = get_height()
for i in range(height):
# to print space
for k in range(height - i - 1):
print(' ', end="")
# to print # and do not break to new line
for l in range(i + 1):
print("#", end="")
# to print a new line
print(""... | minhngocda/cs50_2022 | sentimental-mario-less/mario.py | mario.py | py | 558 | python | en | code | 0 | github-code | 13 |
26018000246 | from absl.testing import parameterized
import tensorflow as tf
from nucleus7.coordinator.predictors import predict_using_predictor
from nucleus7.coordinator.predictors import (
represent_predictor_through_nucleotides)
from nucleus7.core.nucleotide import Nucleotide
from nucleus7.utils import nest_utils
class Tes... | audi/nucleus7 | tests/coordinator/predictors_test.py | predictors_test.py | py | 4,628 | python | en | code | 35 | github-code | 13 |
28598008840 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 7 14:22:19 2022
@author: Dartoon
"""
import numpy as np
import astropy.io.fits as pyfits
import matplotlib.pyplot as plt
import glob, pickle
from galight.tools.astro_tools import plt_fits
from galight.data_process import DataProcess
ID = 10004
ban... | dartoon/my_code | projects/2022_fit_Liu19_catalog/3_read_pickle.py | 3_read_pickle.py | py | 1,950 | python | en | code | 0 | github-code | 13 |
7740380885 | import numpy as np
import gym # import from Gym
class OpenAIEnvironment(object):
"""This class serves as an interface between the standardized environments of OpenAI Gym and the PS agent.
You must install the gym package and make sure that the programm can access it (ie provide the path) to run this code.""" ... | EazyReal/Quantum-Machine-Learning-2020-fall | HW2/environments/env_openai.py | env_openai.py | py | 10,307 | python | en | code | 1 | github-code | 13 |
31515843768 | import copy
import hydra
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import utils
from agent.dreamer import DreamerAgent, stop_gradient
import agent.dreamer_utils as common
class RND(nn.Module):
def __init__(self,
obs_dim,
hidden_dim,
... | mazpie/mastering-urlb | agent/rnd.py | rnd.py | py | 4,723 | python | en | code | 23 | github-code | 13 |
12861904350 | print('Task 1 of 3: Function "Create your list"')
def fun_list():
"""fun_list makes the list of the length = n and of the item maximum value = m"""
n = int(input("Input the number of items in your list:\n"))
m = int(input("Input the maximum value of the item in your list:\n"))
q = input("Do you want ... | nestelementary/Contacts | G117_Nesteruk_DZ_4_Function_3_in_1.py | G117_Nesteruk_DZ_4_Function_3_in_1.py | py | 2,439 | python | en | code | 0 | github-code | 13 |
17160653382 | # 접을 수 있느냐?
# 없다면 전에 접었던 것은 성공했느냐 했다면 return/ 못했다면 하나 더 지우는 것으로 가자
# 원소 두개 남긴다면 length C length-2 가 경우의 수, 길이는 2
def getResult(erase):
global visited
if length - erase == 2:
return 2, length*(length-1)/2
elif length <= 1:
return 0, 1
else:
# 접을 수 없는가?
if (length - erase... | jiyong1/problem-solving | swea/fold_sequence.py | fold_sequence.py | py | 976 | python | ko | code | 2 | github-code | 13 |
14386456385 | #
# @lc app=leetcode.cn id=78 lang=python3
#
# [78] 子集
#
from typing import List
count = 0
# @lc code=start
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
track = []
def backtrack(track, nums, start):
global count
# print(' '*4*coun... | largomst/leetcode-problem-solution | 78.子集.2.py | 78.子集.2.py | py | 753 | python | en | code | 0 | github-code | 13 |
69798141137 |
from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('accounts/',include('accounts.urls')),
path('eatin/',include('feed.urls')),
path('cart/',include('myCart.urls')),
path('cook/',include('cook.urls... | limorB/EatIn | eatin/urls.py | urls.py | py | 506 | python | en | code | 0 | github-code | 13 |
19420522287 | import subprocess
import shutil
import numpy as np
import os
from dataclasses import dataclass
from multiprocessing import Pool
from rnamake_ens_gen import logger, wrapper
log = logger.get_logger("score")
@dataclass(frozen=True, order=True)
class Opts:
wrapper_opts: wrapper.Opts = wrapper.Opts()
output_num:... | jyesselm/rnamake_ens_gen | rnamake_ens_gen/simulate.py | simulate.py | py | 3,109 | python | en | code | 0 | github-code | 13 |
35386366491 | from distutils.core import setup, Extension
from sys import platform
import os
libraries = [];
if platform == 'darwin':
libraries.append('glfw');
os.environ['LDFLAGS'] = '-framework Cocoa -framework OpenGL -framework IOKit -framework CoreFoundation -framework CoreVideo';
elif platform == 'win32':
libraries.append('... | victorliu/PyGeom2 | setup.py | setup.py | py | 812 | python | en | code | 1 | github-code | 13 |
1011948550 | from django.db import models
class Course(models.Model):
"""
普通课程
"""
title = models.CharField(max_length=32)
class DegreeCourse(models.Model):
"""
学位课程
"""
title = models.CharField(max_length=32)
class PricePolicy(models.Model):
"""价格策略"""
price = models.IntegerField()
... | FatPuffer/Django-ContentType | contenttype/app01/models_bak.py | models_bak.py | py | 505 | python | en | code | 0 | github-code | 13 |
74880472978 | class Query:
def __init__(self, query):
self.type = query[0]
self.number = int(query[1])
if self.type == 'add':
self.name = query[2]
class HashTable:
def __init__(self, size):
self.size = size
self.table = [[] for _ in range(self.size)]
self.prime = 1... | DA-testa/phone-book-221RDB020 | main.py | main.py | py | 1,847 | python | en | code | 0 | github-code | 13 |
21039192316 | import io
import requests
import json
from PIL import Image
api_url = "API_URL"
payload = {"img_url":"https://raw.githubusercontent.com/pjreddie/darknet/master/data/person.jpg",
"search_query":"horse"}
response = requests.post(api_url, data = json.dumps(payload))
if response.status_code == 200:
bbox... | bismillahkani/AWS-Serverless-AI | SAM/clip_crop/app/testapi.py | testapi.py | py | 577 | python | en | code | 1 | github-code | 13 |
3490732337 | def solve_by_recuisive(weights,values,bagsize):
left = 0
right = len(weights) - 1
return recursive(weights,values,left,right,bagsize)
def recursive(weights,values,left,right,rest):
"""
:param weights: 物品的重量
:param values: 价值
:param left:
:param right:
:param rest: 背包剩余的承重
:retu... | guyuejia/LearnDS | DynamicProgramming/Knapsack.py | Knapsack.py | py | 1,852 | python | zh | code | 0 | github-code | 13 |
24417006396 | import sys
class Redirection(object):
def __init__(self, in_obj, out_obj):
self.input = in_obj
self.output = out_obj
def read_line(self):
res = self.input.readline()
self.output.write(res)
return res
if __name__ == '__main__':
if not sys.stdin.isatty():
sys.stdin = Redirection(in_obj=sys.stdin, out_obj... | PacktPublishing/Mastering-Python-Scripting-for-System-Administrators- | Chapter04/redirection.py | redirection.py | py | 461 | python | en | code | 178 | github-code | 13 |
32485454353 | import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import pandas as pd
from config import CLIENT_ID, CLIENT_SECRET
client_credentials_manager = SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
# user_i... | jmoussa/spotify-visualizer | utils.py | utils.py | py | 2,483 | python | en | code | 0 | github-code | 13 |
18218834827 | # Tuple is a data type made up of collection of items
# !!!!!!!! Tuples are immutable !!!!!!!!
# There are 2 ways to declare a tuple
# Declaring a tuple with tuple() function implies that the argument is an iterable one (list or string)
# Tuple Declaration is as follows
tuple_1 = ("a", "b", "c", "d", "e")
tuple_2 = (2... | eagledeath85/Python_Courses | python_for_beginners/tuples.py | tuples.py | py | 1,225 | python | en | code | 0 | github-code | 13 |
19481071488 | import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup(
name = "xtsi",
version = "1",
description = "xtsi",
options = {"build_exe" : {"includes" : "atexit" }},
executables = [Executable("xtsi.py", base = base)])
| dxe4/xls_to_mysql_insert | setup.py | setup.py | py | 319 | python | en | code | 4 | github-code | 13 |
21271882607 | from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from proj.models import XssProject, XssItem
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from d... | xiaoxiaoleo/xsstry | proj/views.py | views.py | py | 1,003 | python | en | code | 2 | github-code | 13 |
70336819858 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | im-ethz/flirt | docs/conf.py | conf.py | py | 5,329 | python | en | code | 48 | github-code | 13 |
17055329214 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class LinkTypeResult(object):
def __init__(self):
self._level = None
self._link_type_code = None
self._link_type_name = None
self._parent_code = None
self._state... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/LinkTypeResult.py | LinkTypeResult.py | py | 3,380 | python | en | code | 241 | github-code | 13 |
23951364709 | #With the use of Sparse matrix (sparse matrix is implemented by using dictionary)
from math import *
import numpy as np
from datetime import datetime
def loadMovieLens(path='.', file='/Train.dat'):
# Load data
prefs={}
for line in open(path+file):
(user,movieid,rating)=line.split(':')
pref... | jaydeep1997/Cross_Domain_Recommender_System | matrix_factorization/single_domain/100K/3single_domain_genre/5testing_sparse_1m_genre.py | 5testing_sparse_1m_genre.py | py | 3,293 | python | en | code | 3 | github-code | 13 |
29423220139 | import json
from models import User, NewsItem, EmailSubscription
from __main__ import app
@app.route('/news/<int:news_item_id>/subscribe', methods=['GET'])
def subscribe_to_news_item(news_item_id):
member = User.get_signed_in_user()
subscribed = 'n/a'
if member is None:
status = '401'
else:
news_item = News... | javilm/msx-center | routes/subscriptions/subscribe_to_news_item.py | subscribe_to_news_item.py | py | 648 | python | en | code | 0 | github-code | 13 |
72343775058 | import os
import numpy as np
import scipy.sparse as sp
import random
from copy import deepcopy
from collections import OrderedDict
from random import shuffle
import torch
import networkx as nx
import dgl
from torch.nn import functional as F
import time
import datetime
import argparse
from collections impo... | bbjy/DAN | src/main_version.py | main_version.py | py | 16,761 | python | en | code | 1 | github-code | 13 |
20747633887 | #!/usr/bin/env python3
###################################################################################
# This script will detect unecessary includes in header files. #
###################################################################################
import os
import sys
import subprocess
wit... | 0xff7/Squally | CheckIncludes.py | CheckIncludes.py | py | 1,131 | python | en | code | null | github-code | 13 |
15302546648 | import os
def create_dir_if_exists(dir_path):
if not os.path.exists(dir_path):
os.makedirs(dir_path)
def download_data():
filenames = ["train.csv", "test.csv", "enhanced_train.csv"]
download_url = "https://rhdzmota-cloud-storage.herokuapp.com/temporal-link/dropbox-files?file_name={}&file_path={}"
... | RHDZMOTA/PAP-ML-17 | HW02/setup.py | setup.py | py | 727 | python | en | code | 0 | github-code | 13 |
20102402314 | from ursina import *
app = Ursina()
me = Animation('assets\player',collider ='box',y=1,)
Sky()
camera.orthographic = True
camera.fov = 20
Entity(
model = 'quad',
texture = 'assets\BG',
scale=50,z=5
)
def update():
me.y += held_keys['w']*6*time.dt
me.y += held_keys['s']*6*time.dt
app.r... | salihslx/Games | game1.py | game1.py | py | 324 | python | en | code | 0 | github-code | 13 |
19856224373 | from zipfile import ZipFile
from io import BytesIO
from openpyxl.xml.constants import (
ARC_CORE,
ARC_WORKBOOK,
ARC_STYLE,
ARC_THEME,
SHARED_STRINGS,
EXTERNAL_LINK,
)
from openpyxl.workbook.properties import DocumentProperties, read_properties
from openpyxl.workbook.names.external import detec... | jchuahtacc/openpyxl-imagereader-patch | patch_reader/excel.py | excel.py | py | 4,287 | python | en | code | 1 | github-code | 13 |
10255536366 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 9 19:06:48 2020
@author: sarroutim2
"""
import torch.nn as nn
import torch
from .base_rnn import BaseRNN
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
class Classifier(nn.Module):
... | sarrouti/multi-class-text-classification-pytorch | models/classifier.py | classifier.py | py | 1,337 | python | en | code | 3 | github-code | 13 |
16132904003 | #!/usr/bin/env python3
from jinja2 import Template
# We can use raw, endraw markers to escape
# Jinja delimiters.
data = """
{% raw %}
His name is {{ name }}
{% endraw %}
"""
tm = Template(data)
msg = tm.render(name="Peter")
print(msg)
| udhayprakash/PythonMaterial | python3/jinja_templating/e_jinja_rawdata.py | e_jinja_rawdata.py | py | 240 | python | en | code | 7 | github-code | 13 |
74009936016 | import os
from unittest import TestCase
from models import db, User, Message, Follows
# BEFORE we import our app, let's set an environmental variable
# to use a different database for tests (we need to do this
# before we import our app, since that will have already
# connected to the database
os.environ['... | tylerfelsted/warbler | test_message_model.py | test_message_model.py | py | 1,531 | python | en | code | 0 | github-code | 13 |
38138107286 | import requests
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from se... | manojnilanga/scrape_realstate | check_realstate.py | check_realstate.py | py | 3,129 | python | en | code | 0 | github-code | 13 |
37933917452 | import random
class Healthy():
def __init__(self, row, col, title='0'):
self.row = row
self.col = col
self.title = title
class Sick(Healthy):
def __init__(self, row, col, IR, MR, title='I'):
super().__init__(row, col, title)
self.title = title
self.IR = IR
... | RiskyClick/40Challenges | EpidemicOutbreakTerminal.py | EpidemicOutbreakTerminal.py | py | 3,803 | python | en | code | 0 | github-code | 13 |
42628693650 | """
Forms for reservation:
* Creation
* Update
* Delete
"""
import datetime
from django import forms
from roomalloc.models import Profile, Reservation
from roomalloc.util import validation
time_start_help_text = "\
<ul> \
<li> Minute should be 30 or 0 </li>\
<li> Second should be 0 </li>\
<li> Dat... | cnguyenm/RoomAlloc | roomalloc/form/reservation.py | reservation.py | py | 4,515 | python | en | code | 0 | github-code | 13 |
70476114258 | t=int(input())
for v in range(t):
binary = input()
length = len(binary)
if binary == '1'*length:
print('0'*length)
continue
number = int(binary,2)
number+=1
res=bin(number).replace('0b', '')
while len(res)<length:
res='0'+res
print(res) | baquyptit2001/ctdl-gt | nhi_phan_ke_tiep.py | nhi_phan_ke_tiep.py | py | 293 | python | en | code | 0 | github-code | 13 |
30612183888 | import numpy as np
import pandas as pd
class QLearningAgents:
def __init__(self, n_agents, action_space, gamma=0.0):
self.gamma = gamma
self.n_agents = n_agents
self.agents = [QLearningTable(action_space, gamma=self.gamma) for _ in range(self.n_agents)]
def select_action(self, obs):
... | liangyancang/agent-based-modeling-in-electricity-market-using-DDPG-algorithm | algorithm/QLearning.py | QLearning.py | py | 2,423 | python | en | code | 20 | github-code | 13 |
3726597100 | import functools
import numpy as np
from garage.experiment import deterministic
from garage.sampler import DefaultWorker
from iod.utils import get_np_concat_obs
class OptionWorker(DefaultWorker):
def __init__(
self,
*, # Require passing by keyword, since everything's an int.
... | jaekyeom/IBOL | garagei/sampler/option_worker.py | option_worker.py | py | 6,427 | python | en | code | 28 | github-code | 13 |
6680862619 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gdmapstool', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='gdmap',
name='scen... | nens/flooding-public | flooding_lib/tools/gdmapstool/migrations/0002_auto_20200928_1652.py | 0002_auto_20200928_1652.py | py | 427 | python | en | code | 0 | github-code | 13 |
17703721349 |
from django.core.management.base import BaseCommand, CommandError
from apps.orders.models import Order, OrderItem
from apps.shipments.models import ShipmentLog, Shipment
from django.utils import timezone
import requests
import json
import datetime
class Command(BaseCommand):
def handle(self, *args, **options):
... | oshevelo/sep_py_shop | FirstShop/apps/shipments/management/commands/create.py | create.py | py | 1,915 | python | en | code | 0 | github-code | 13 |
21498501659 | ############HELPER CLASS AND FUNCTIONS######################
#Class that defines an operation (i.e one line in the input)
class Operation:
def __init__(self,line,w=0,x=0,y=0,z=0):
self.x=x
self.w=w
self.y=y
self.z=z
op_parts = line.split(" ")
self.operand = op_parts[0... | shaefeli/AdventOfCode2021 | day24/day24.py | day24.py | py | 5,506 | python | en | code | 0 | github-code | 13 |
34300679615 | # Data processing workflow
import numpy as np
import pandas as pd
#import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
# Using the element Table in rdkit, the pt_dict out of the comment part is from the code below
# from rdkit import Chem
# pt = Chem.GetPeriodicTable()
# pt_dict = dict()
# for i i... | Jingdan-Chen/IRC_helper | funarg.py | funarg.py | py | 16,444 | python | en | code | 0 | github-code | 13 |
44765823526 | import json
import xml.etree.ElementTree as ET
def readXML(xmlFile):
if xmlFile is None:
return None
else:
tree = ET.parse(xmlFile)
root = tree.getroot()
prefix = root.tag
# save all the variables in a dictionary
variables = root.attrib
# used to make the... | paolocesa/c4aEnginePaolo | controller/mini_planner/Logica.py | Logica.py | py | 5,303 | python | en | code | 0 | github-code | 13 |
846669462 | # The `serializers.py` file is responsible for defining serialization
# and deserialization logic to convert complex data types, such as
# model instances, into JSON or other formats for API responses and vice versa.
# Create your serializers here.
from rest_framework import serializers
from apps.todo.models import T... | MentorMate/mentormate-django-cookiecutter-template | {{cookiecutter.project_name}}/apps/todo/api/v1/serializers.py | serializers.py | py | 533 | python | en | code | 0 | github-code | 13 |
7600562856 | #!/usr/bin/env python
"""Defines common algorithms over FSTs"""
from pyfoma.fst import FST, State, Transition
import pyfoma.private.partition_refinement as partition_refinement
import heapq, operator, itertools, functools
from collections import deque
from typing import Dict, Callable
# region Function Wrappers
def... | mhulden/pyfoma | src/pyfoma/algorithms.py | algorithms.py | py | 34,910 | python | en | code | 25 | github-code | 13 |
10173364835 | import numpy as np
def simple_predict(x, theta):
"""
Computes the prediction vector y_hat from two non-empty numpy.array.
Args:
x: has to be an numpy.array, a matrix of dimension m * n.
theta: has to be an numpy.array, a vector of dimension (n + 1) * 1.
Return:
y_hat as a numpy.array, a vector of dimension m ... | jmcheon/ml_module | 02/ex00/prediction.py | prediction.py | py | 2,584 | python | en | code | 0 | github-code | 13 |
25530206403 | import os
from linebot import LineBotApi, WebhookParser
from linebot.models import MessageEvent, TextMessage, TextSendMessage, TemplateSendMessage, ButtonsTemplate, MessageTemplateAction, ImageCarouselColumn, ImageCarouselTemplate, CarouselTemplate, CarouselColumn
channel_access_token = os.getenv("LINE_CHANNEL_ACCES... | wuyibang/linebottest | utils.py | utils.py | py | 4,217 | python | en | code | 0 | github-code | 13 |
71648261457 | import logging
from qark.issue import Severity, Issue
from qark.scanner.plugin import ManifestPlugin
log = logging.getLogger(__name__)
TASK_REPARENTING_DESCRIPTION = (
"This allows an existing activity to be reparented to a new native task i.e task having the same affinity as the "
"activity. This may lead t... | linkedin/qark | qark/plugins/manifest/task_reparenting.py | task_reparenting.py | py | 1,330 | python | en | code | 3,071 | github-code | 13 |
73868994577 | from datetime import datetime
from json import loads
def process_time(time):
time = time.strftime('%Y-%m-%dT%H:%M:%S')
return time
def convert_dict_to_string(message):
"May not use this function as dictionary seems to be working fine."
msg_str = ''
for key, value in message.items():
if val... | chrisbombino/cs631-project | scripts/helper.py | helper.py | py | 3,117 | python | en | code | 8 | github-code | 13 |
6656684898 | with open("input.txt") as f:
input = f.read().splitlines()
draw_numbers = input.pop(0).split(",")
boards = []
new_board = []
for line in input:
if len(line.strip()) == 0:
if new_board != []:
boards.append(
{
"board": new_board,
"row":... | RuairidhCa/aoc2021 | 04/04.py | 04.py | py | 2,362 | python | en | code | 0 | github-code | 13 |
74675180816 | import io
from mstk.topology import Molecule, Topology, UnitCell
from mstk.forcefield import ForceField, ZftTyper
from mstk.simsys import System
from mstk.wrapper import Packmol
definition = '''
TypeDefinition
h_1 [H][CX4]
c_4 [CX4]
c_4h2 [CX4;H2]
c_4h3 [CX4;H3]
HierarchicalTree
h_1
c_4
c_4h2
c_4h3
... | z-gong/mstk | docs/examples/export.py | export.py | py | 1,125 | python | en | code | 7 | github-code | 13 |
25969066453 | import streamlit as st
import sklearn
import pickle
import pandas as pd
import numpy as np
iris_data = pickle.load(open("irismodel.sav", 'rb'))
st.title('Iris Data prediction app')
#adding images
from PIL import Image
setosa = Image.open("iris_setosa.jpg")
virginica = Image.open("Iris_virginica.jpg")
v... | SimeonIfalore/Iris_prediction_app | iris.py | iris.py | py | 1,291 | python | en | code | 0 | github-code | 13 |
9370249293 |
#This function is mainly responsible for setting up the host server for the multipl-screen version of the game
#Check CitedCode for specific citations
import socket
import threading
from queue import Queue
IP = socket.gethostbyname(socket.gethostname())
HOST = str(IP) # put your IP address here if playing on multip... | ryanyxw/GomokuAI | Host.py | Host.py | py | 4,354 | python | en | code | 1 | github-code | 13 |
40912726702 | import pandas as pd
from openpyxl.workbook import Workbook
from openpyxl.worksheet.table import TableStyleInfo, Table
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.styles import Alignment, DEFAULT_FONT
from startup_file_manage import FileManager
class ExcelManipulator:
def __init... | Mike-Durning/work_ui | pyqt_proj/src/excel_manipulation.py | excel_manipulation.py | py | 8,294 | python | en | code | 0 | github-code | 13 |
31805809623 | from abc import ABC, abstractmethod
import datetime
import glob
import itertools
from joblib import dump, load
import os
import pickle
import time
import uuid
import sys
# Manipulating, analyzing and processing data
from collections import OrderedDict
import numpy as np
import pandas as pd
import scipy as sp
from scipy... | john-james-ai/Ames | src/pipeline_v3.py | pipeline_v3.py | py | 41,699 | python | en | code | 0 | github-code | 13 |
20259393504 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | dhermes/bezier | scripts/doc_template_release.py | doc_template_release.py | py | 5,336 | python | en | code | 230 | github-code | 13 |
42386709326 | from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import time
# ----------------------------- PREPARE OPTIONS ----------------------------- #
URL = "https://orteil.dashnet.org/exper... | Carmui/100-days-Python | Day 48 PROJECT/Cookie_Game_Bot.py | Cookie_Game_Bot.py | py | 2,072 | python | en | code | 0 | github-code | 13 |
11420427417 | import boto3
from sqs_client.contracts import SqsConnection as SqsConnectionBase
class SqsConnection(SqsConnectionBase):
def __init__(
self,
region_name: str = None,
access_key: str = None,
secret_key: str = None,
endpoint_url: str = None,
):
self._access_key =... | jptavarez/python-sqs-client | sqs_client/connection.py | connection.py | py | 1,559 | python | en | code | 7 | github-code | 13 |
1732534886 | """
DECANUM - Robot Inventor MicroPython Software -
Project : Guidage vehicule 2 pairMotor avec joystick ( motor)
: et mémorisation du circuit.
Application : carguidage.py
Auth : remybeaudenon@yahoo.com
Date : 06/2023
"""
version = "v1p1"
import gc, os, umachi... | remybeaudenon/lego_hub_pyfw | MCR/MCRIInstall-v1p1-4.py | MCRIInstall-v1p1-4.py | py | 4,927 | python | en | code | 0 | github-code | 13 |
8626824657 | import json
import argparse
from tqdm import tqdm
from pyserini.search.lucene import LuceneSearcher
from utils import read_json, write_json, read_config
def retrieve(queries, num_candidates, searcher, pid2title):
def get_text(hit, title):
text = json.loads(hit.raw)['contents'][len(title):].strip()
... | VedangW/upr-kilt | bm25/search.py | search.py | py | 3,359 | python | en | code | 0 | github-code | 13 |
37923025538 | ## @file AthenaPoolCnvSvc_jobOptions.py
## @brief AthenaPoolCnvSvc job options file to illustrate available AthenaPoolCnvSvc properties.
## @author Peter van Gemmeren <gemmeren@bnl.gov>
## $Id: AthenaPoolCnvSvc_jobOptions.py,v 1.13 2008-12-04 20:54:31 gemmeren Exp $
#####################################################... | rushioda/PIXELVALID_athena | athena/Database/AthenaPOOL/AthenaPoolCnvSvc/share/AthenaPoolCnvSvc_jobOptions.py | AthenaPoolCnvSvc_jobOptions.py | py | 3,584 | python | en | code | 1 | github-code | 13 |
16360911007 | # https://leetcode.com/problems/kth-largest-element-in-a-stream/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# https://leetcode.com/problems/reverse-linked-list
class Solution:
def reverseList(self, head: Opti... | aux-Issa/Leetcode | representative_60_problems/LinkedList/reverse-linked-list.py | reverse-linked-list.py | py | 521 | python | en | code | 0 | github-code | 13 |
15599619490 | from collections import deque
people = deque(input().split(" "))
n = int(input())
counter = 1
while len(people) > 1:
final = people.popleft()
if counter == n:
print(f"Removed {final}")
counter = 1
else:
counter += 1
people.append(final)
winner = people.popleft()
p... | PowerCell12/Programming_Advanced_Python | Lists as Stacks and Queues/Lab/05. Hot Potato.py | 05. Hot Potato.py | py | 346 | python | en | code | 0 | github-code | 13 |
23247994356 | # encoding: utf-8
"""
Created by misaka-10032 (longqic@andrew.cmu.edu).
All rights reserved.
DFS. A bit faster than BFS, because str (immutable) operation is time consuming.
"""
__author__ = 'misaka-10032'
class Solution(object):
letters = [
' ', # 0
'', # 1
'abc', # 2... | misaka-10032/leetcode | coding/00017-letter-comb-of-phone-number/solution.py | solution.py | py | 1,180 | python | en | code | 1 | github-code | 13 |
15400312097 | """Coordinator for E3DC integration."""
from datetime import timedelta, datetime
import logging
from time import time
from typing import Any
import pytz
from e3dc import E3DC # Missing Exports:; SendError,
from e3dc._rscpLib import rscpFindTag
from homeassistant.config_entries import ConfigEntry
from homeassistant.... | torbennehmer/hacs-e3dc | custom_components/e3dc_rscp/coordinator.py | coordinator.py | py | 19,363 | python | en | code | 22 | github-code | 13 |
35648439655 | import random
import numpy as np
from PIL import Image
from captcha.image import ImageCaptcha
NUMBER = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
LOW_CASE = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z']
U... | scusec/Data-Mining-for-Cybersecurity | Homework/2019/Task8/4/Code/captcha_gen.py | captcha_gen.py | py | 1,841 | python | en | code | 66 | github-code | 13 |
40614168980 | import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
from config import *
sess = tf.InteractiveSession()
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
r... | VGxiaozhao/ChineseChess | CNN/model.py | model.py | py | 1,953 | python | en | code | 0 | github-code | 13 |
23965360860 | """
归并排序 n*log_2(n)
使用递归 先对二分的左右两个列表排序,然后对左右半部合并排序
"""
def mergeSort(alist):
print('Splitting', alist)
if len(alist) > 1:
mid = len(alist) // 2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
# 合并操作
i = ... | siyi-wind/cs-course-project | homework/7_6_1.py | 7_6_1.py | py | 1,012 | python | en | code | 3 | github-code | 13 |
25995737804 | #!/usr/bin/env python
# coding: utf-8
import keras
from keras.layers import Dropout, Activation, BatchNormalization, Dense, average, Lambda, Concatenate, Flatten
from keras.layers import Input, Conv2D, MaxPooling2D, concatenate, Dropout, AveragePooling2D, ConvLSTM2D, Conv3D, MaxPooling3D, GlobalAveragePooling3D, MaxPo... | rvsingh31/VidRecognizer | archive/Code/gcp/TSN/models.py | models.py | py | 11,835 | python | en | code | 1 | github-code | 13 |
20215312473 | import pytest
from Pages.MainPage import MainPage
from Pages.Checkboxes import Checkboxes
@pytest.mark.usefixtures("init_driver")
class TestCheckboxes():
def test_checkboxes(self):
self.mainPage=MainPage(self.driver)
self.mainPage.click_on_checkboxes_page()
self.checkbox=Checkboxes(sel... | kakamband/HerokuPracticeSelenium | Tests/TestCheckboxes.py | TestCheckboxes.py | py | 784 | python | en | code | 1 | github-code | 13 |
18750222891 | import youtube_dl
from time import sleep as s
from tkinter import *
from PIL import ImageTk
import sys
import os
root = Tk()
w = 1000 # width for the Tk root
h = 600 # height for the Tk root
# get screen width and height
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height o... | owenwijaya22/universal-downloader | src/downloader.py | downloader.py | py | 4,257 | python | en | code | 4 | github-code | 13 |
23574708212 | from datetime import datetime, timedelta
from dateutil import parser
def get_video_ids(response, days, keyword):
items = response["items"]
ids = []
limit_date = (datetime.now() - timedelta(days=days)).date() if days > -1 else None
for item in items:
published_date = parser.parse(item["snippet"... | ivan-svetlich/youtube_autoplaylist | youtube_autoplaylist/get_ids.py | get_ids.py | py | 783 | python | en | code | 0 | github-code | 13 |
12046148315 | from nonebot import export, on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.permission import SUPERUSER
from nonebot.adapters.cqhttp import Bot, Event
from .data_source import get_pixiv
export = export()
export.description = 'Pixiv图片'
export.usage = 'Usage:\n pixiv {日榜/周榜/月榜... | yintian710/nb2_test | awesome/plugins/pixiv/__init__.py | __init__.py | py | 802 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.