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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
42335237588 | # -*- coding:utf-8 -*-
def FindNumsAppearOnce(array):
xorValue = AdjacentXor(array) # o(n)
index = getFirstBit(xorValue)
temp1 = 0
temp2 = 0
for i in array: # o(k*n) k为位数
if isBit1(i, index):
temp1 = temp1^i
else:
temp2 = temp2^i
return temp1, temp2
# ... | TangAL0203/code_to_offer | python/FindNumsAppearOnce.py | FindNumsAppearOnce.py | py | 1,868 | python | en | code | 1 | github-code | 6 |
29916696641 | import unittest
from livecli import Livecli
from livecli.plugins.rtmp import RTMPPlugin
from livecli.stream import RTMPStream
class TestPluginRTMPPlugin(unittest.TestCase):
def setUp(self):
self.session = Livecli()
def assertDictHas(self, a, b):
for key, value in a.items():
self.... | ariesw/livecli | tests/test_plugin_rtmp.py | test_plugin_rtmp.py | py | 2,035 | python | en | code | 0 | github-code | 6 |
34711863736 | from fastapi import FastAPI
from fastapi import HTTPException
import models
app = FastAPI()
coffeeDescriptions = [
"A latte is a coffee drink made with espresso and steamed milk. It is a single shot of espresso served in a tall glass, with a layer of steamed milk on top, and a layer of microfoam on top of that.",... | ByteOfKathy/RESTAPI-example | backend.py | backend.py | py | 3,994 | python | en | code | 0 | github-code | 6 |
37169098035 | __author__ = "Moath Maharmeh"
__license__ = "GNU General Public License v2.0"
__version__ = "1.1"
__email__ = "moath@vegalayer.com"
__created__ = "13/Dec/2018"
__modified__ = "5/Apr/2019"
__project_page__ = "https://github.com/iomoath/file_watchtower"
import sqlite3
import os
import csv
DEFAULT_PATH = os.path.join(o... | iomoath/file_watchtower | db.py | db.py | py | 10,875 | python | en | code | 30 | github-code | 6 |
73739274748 | #!/usr/bin/env python3
""""
This module provides the interface to manage the state of configured workers.
It allows to setup the virtual environment, install dependencies into it and
then to execute BuildBot worker commands.
"""
import sys
import os.path
import argparse
import getpass
import socket
import paramiko
i... | dA505819/maxscale-buildbot | worker-management/manage.py | manage.py | py | 6,833 | python | en | code | 0 | github-code | 6 |
70488670907 | # accepted on coderun
import sys
deltas = ((1, 1), (-1, 1), (-1, -1), (1, -1))
def cut_down():
n, m, w, b, whites, blacks, turn = get_pars()
checkers_board = [[' ' for i in range(n)] for j in range(m)]
for j_, i_ in whites:
checkers_board[j_ - 1][i_ - 1] = 'w'
for j_, i_ in blacks:
c... | LocusLontrime/Python | Yandex_fast_recruit_days/Easy/Checkers.py | Checkers.py | py | 1,242 | python | en | code | 1 | github-code | 6 |
12100232146 | import random
from heaps import heapsort
def mergesort(l, low, high):
def merge(l, low, middle, high):
left_runner = low
right_runner = middle + 1;
# While there are elements in right run:
sorted_l = []
while left_runner <= middle and right_runner <= high:
if l... | Shaywei/MyDevTools | Python/BasicDataStructures/sorts.py | sorts.py | py | 3,070 | python | en | code | 0 | github-code | 6 |
21509653092 | from fastapi import APIRouter, Depends, Request, Response
from sqlalchemy.orm import Session
from typing import List
from uuid import UUID
from api.models.node_threat import NodeThreatCreate, NodeThreatRead, NodeThreatUpdate
from api.routes import helpers
from db import crud
from db.database import get_db
from db.sche... | hollyfoxx/ace2-gui | backend/app/api/routes/node_threat.py | node_threat.py | py | 2,805 | python | en | code | 1 | github-code | 6 |
20802484372 | class Graph:
def __init__(self):
self.edges = []
self.visited = []
self.adjacent = 0
pass
def from_matrix(self, matrix):
self.visited = [False for i in range(len(matrix))]
for i in matrix:
self.edges.append([])
for i in range(len(matrix)):
... | michbogos/olymp | utils/graph.py | graph.py | py | 964 | python | en | code | 0 | github-code | 6 |
36213639675 | #!/usr/bin/env python
# coding: utf-8
import os
import math
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from PIL import Image
import time
import os,glob
import matplotlib.pyplot as plt
from random import choice
VGG_MEAN=[103.939,116.779,123.68]
class VGGNet():
def __init__(se... | castleKing1997/Style_Transfer | StyleTransfer.py | StyleTransfer.py | py | 7,795 | python | en | code | 0 | github-code | 6 |
34616102356 | from fenics import *
import numpy as np
from Stretch_Mesh import stretch_mesh
def solver_para(nx,ny,tau):
# Create mesh and define function space
mesh = stretch_mesh(nx=nx,ny=ny)
V = FunctionSpace(mesh, "P", 1)
# Define boundary condition
tol = 1E-14
u_D = Expression('near(x[0], 1, tol) ? pow(1-x[1],4)... | alixsleroy/PhD-project2 | Solver Package/Interpolate_Solver.py | Interpolate_Solver.py | py | 2,554 | python | en | code | 1 | github-code | 6 |
20473378944 | import json
import numpy as np
class calculte():
def __init__(self, data, n_x, n_y, t_s, morning_time, afternoon_time):
self.data = data
self.n_x = n_x
self.n_y = n_y
self.t_s = t_s
self.morning = morning_time
self.afternoon_time = afternoon_time
def _process_dat... | Jkcert/deecamp-frontend | src/ors_backend/model/schedule/calculation.py | calculation.py | py | 2,473 | python | en | code | 1 | github-code | 6 |
30109795593 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 7 10:30:52 2021
@author: X
"""
import json
import lz4.frame, lz4.block
import os
import copy
# The full path to the Firefox folders is:
# C:\Users\USERNAME\AppData\Roaming\Mozilla\Firefox\Profiles
# Each profile gets its own folder and from there, the bookm... | AndrewWigginCout/bookmarks | bookmarks.py | bookmarks.py | py | 7,127 | python | en | code | 1 | github-code | 6 |
15932158711 | from ..exceptions import HydraError, ResourceNotFoundError
from . import scenario, network
from .. import db
from ..db.model import ResourceGroup, ResourceGroupItem, Node, Link
from .scenario import _get_scenario
from sqlalchemy.orm.exc import NoResultFound
import logging
log = logging.getLogger(__name__)
def _get_g... | hydraplatform/hydra-base | hydra_base/lib/groups.py | groups.py | py | 3,757 | python | en | code | 8 | github-code | 6 |
34886436598 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the dayOfProgrammer function below.
def dayOfProgrammer(year):
if year == 1918:
return '26.09.1918'
date = 256 - 243
# 1917 ke bawah kabisat hanya bisa di modulasi 4
is_leap_year_under_1917 = (year <= 1917 an... | nipeharefa/hackkerrank-problemsolving-practice | day-of-the-programmer.py | day-of-the-programmer.py | py | 930 | python | en | code | 1 | github-code | 6 |
9695092385 | #!/bin/python3
import datetime
import json
import threading
import time
import turtle
import sys
from urllib import request
from collections import namedtuple
class ISS():
def __init__(self):
self.is_instance = True
self._astronauts_url = 'http://api.open-notify.org/astros.json'
self._... | mattbhenley/ISS_Locator | locator.py | locator.py | py | 4,144 | python | en | code | 0 | github-code | 6 |
33851082611 | def parse(line):
f = line.split(" ")
return f if len(f) == 1 else (f[0], int(f[1]))
def parse_items(items_l):
f = items_l.split(":")
return [int(i) for i in f[1].split(",")]
def parse_operation_function(operation_l):
f = operation_l.split("=")
g = f[1].split(" ")
if g[-1].isdigit():
... | akepa/advent-of-code-2022 | day11/day11.py | day11.py | py | 1,934 | python | en | code | 0 | github-code | 6 |
25968516319 | """added san and is_my_move to Move
Revision ID: f39051a2ca9b
Revises: c9b0d072e5e4
Create Date: 2020-12-16 13:05:46.434429
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f39051a2ca9b'
down_revision = 'c9b0d072e5e4'
branch_labels = None
depends_on = None
de... | joshua-stauffer/opening-book-api | migrations/versions/f39051a2ca9b_added_san_and_is_my_move_to_move.py | f39051a2ca9b_added_san_and_is_my_move_to_move.py | py | 929 | python | en | code | 2 | github-code | 6 |
70827770107 | from selenium import webdriver
from datetime import datetime
import boto3
import os
import time
now = datetime.now()
folder_name = now.strftime("%Y%m%d")
image_name = "traffic_" + now.strftime("%Y%m%d") + "-" + now.strftime("%H-%M") + ".png"
Bucket_name = "googletrafficmap"
prefix = folder_name + "/"
#Get... | nathan36/GoogleTrafficMap-GIF | GoogleTrafficMap-GIF/saveImage.py | saveImage.py | py | 993 | python | en | code | 0 | github-code | 6 |
44632720863 | #!/usr/bin/env python
import sys
import shutil
from typing import Optional, List, Tuple, Dict
import typer
from rich import print
from rich.columns import Columns
from rich.console import Console
from rich.traceback import install
# fmt: off
# Mapping from topics to colors
TOPICS = {
"TIMR": "#9a9a99",
"VOTE"... | fansehep/Raft_Key-Value | RAFT_6_824/src/raft/dslogs.py | dslogs.py | py | 3,483 | python | en | code | 4 | github-code | 6 |
40428996054 | # python3
class Node:
def __init__(self, key=None, next=None):
self.key = key
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert(self, key):
self.head = Node(key, self.head)
def check(self):
if not self.head:
print... | probhakarroy/Algorithms-Data-Structures | Data Structures/week4/hashing_chaining.py | hashing_chaining.py | py | 1,831 | python | en | code | 0 | github-code | 6 |
3035731078 | i = 1
f = 1.2
b = True
l = [1, 2, 3]
d = {'a': 1, 'b': 2}
s = {1, 2, 3}
t = (1, 2, 3)
def greeting():
print('Hello world')
def func(something):
return something
# Appending a function to a list
l.append(greeting)
# Adding a function to dictionary
d.update({'greeting': greeting})
| Archana-SK/python_tutorials | Decorators/_functions_as_normal_objects.py | _functions_as_normal_objects.py | py | 301 | python | en | code | 0 | github-code | 6 |
18529816397 | # 对学生基本信息进行画像展示分析。包括性别、年级、班级、住址、班主任等形成学生画像标签。
# 对个体维度对学生学业情况进行描述性统计分析。
# 对成绩情况进行统计,并汇总各个科目历史考试成绩趋势,
# 明确学生当前学科成绩分布特点以及未来成绩趋势,为学业干预提供输入。
# 度量指标如原始分、得分率、标准分(Z以及T分)、全年级排名、全班排名、离均值等。
# 学生消费画像分析,通过对学生一卡通消费数据,分析学生消费情况;
# 支持消费分布数据统计分析;
# 如消费趋势对比,对消费进行预警,便于了解学生生活方式尤其是贫困生,并及时干预支持消费明细的查询。
# 学生考勤画像分析,如学生考勤数据统计:如缺勤、迟到、请假、到勤的比例和实际天... | kjp96/tianchi | ClassDef.py | ClassDef.py | py | 2,928 | python | zh | code | 0 | github-code | 6 |
35168238376 | from serpent.game_agent import GameAgent
from serpent.input_controller import KeyboardKey
import offshoot
class SerpentSuperHexagonGameAgent(GameAgent):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.frame_handlers["PLAY"] = self.handle_play
self.frame_handler_setups["PLAY... | cameron-j-knight/General-AI | plugins/SerpentSuperHexagonGameAgentPlugin/files/serpent_SuperHexagon_game_agent.py | serpent_SuperHexagon_game_agent.py | py | 1,675 | python | en | code | 0 | github-code | 6 |
74637081787 | import socket
import time
from PyQt5.QtCore import QTimer, QThread
import queue
import logging
import pyaudio
import threading
logging.basicConfig(format="%(message)s", level=logging.INFO)
class AudioRec(QThread):
def __init__(self, threadChat):
super().__init__()
self.threadChat = threadChat
... | shully899509/OpenParty | app/client/ClientAudio.py | ClientAudio.py | py | 2,191 | python | en | code | 0 | github-code | 6 |
92459438 | print("Mustafa kapasi")
# a = int(input("Enter your name:"))
# print(a)
# b = [1 , 3, 4, 5]
# print(b)
# print(b[1])
# b[0] = 35
# print(b)
# c = (45 , 32, 43, 12)
# print(c)
# c[0] = 24
# print(c)
# calculating orders
print("Welcome to Our Restaurant")
a1 = 0
a2 = 0
b1 = 0
b2 = 0
print("Enter 1 for punjabi ... | Mustu19/Python-Programs | revision1.py | revision1.py | py | 970 | python | en | code | 0 | github-code | 6 |
7945180135 | def merge_files(filenames, output_filename):
with open(output_filename, 'a') as output_file:
for filename in filenames:
with open(filename, 'r') as input_file:
output_file.write(input_file.read())
output_file.write('\n') # Add a new line between each file's conte... | eilishbaby/spam_toolss | compilation.py | compilation.py | py | 723 | python | en | code | 0 | github-code | 6 |
41843820390 | import numpy as np
from sklearn.metrics import f1_score
from sklearn.naive_bayes import BernoulliNB
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
class NaiveBayes:
"""
Naive Bayes implementation based on Multi-variate Bernoulli using python
... | gmortuza/machine-learning-scratch | machine_learning/bayesian/naive_bayes/naive_bayes.py | naive_bayes.py | py | 5,821 | python | en | code | 6 | github-code | 6 |
30791686316 | from numba import *
from numba import error
#@autojit
def func():
if x:
print("hello")
else:
print("world")
def compile_func1():
try:
jit(void())(func)
except error.NumbaError as e:
print("exception: %s" % e)
__doc__ = """
>>> compile_func1()
--------------------- Numb... | garrison/numba | numba/tests/test_reporting.py | test_reporting.py | py | 1,664 | python | en | code | null | github-code | 6 |
30162086505 | from tkinter import *
fenetre = Tk()
import debug as de
import sauvegarde as sauvegarde
import plateau as plateau
import pions as pions
import gestionnaire_evenements as g_evenements
import menu as menu
import gestionnaire_images as g_images
import ast
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 13 18:48:54 201... | PierreMonrocq/L1-Latroncules-game | Main.py | Main.py | py | 4,373 | python | en | code | 0 | github-code | 6 |
10702615749 | # pylint: disable=E0401
import js
import functools
from pyodide.ffi import create_once_callable, create_proxy
from enum import Enum
from typing import Callable, TypedDict, Sequence, MutableMapping, Union
State = MutableMapping[str, Union[str, int, dict, list, None]]
Actions = dict[str, Callable]
Attributes = dict[st... | harehare/python-wasm-vdom | vdom.py | vdom.py | py | 6,230 | python | en | code | 0 | github-code | 6 |
42755033612 | # 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 --------------------------------------------------------------
from dat... | tpoisonooo/Documentation | source/conf.py | conf.py | py | 5,214 | python | en | code | null | github-code | 6 |
71477050428 | import sys
input = sys.stdin.readline
n, k = map(int, input().split())
data = list(map(int, input().split()))
ans = 0
start = 0
end = 20*n
while start <= end:
# 그룹들의 최소가 mid인가?
mid = (start + end) // 2
my_sum = 0
count = 0
for i in range(n):
my_sum += data[i]
if my_sum >= mid:
... | YOONJAHYUN/Python | BOJ/17951.py | 17951.py | py | 490 | python | en | code | 2 | github-code | 6 |
22912396559 | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from flask import Flask, request, jsonify, make_response, abort
import requests
from stations import stations
app = Flask(__name__)
name = [
'station_train_code',
'from_station_name',
'to_station_name',
'lishi',
'start_time',
'ar... | shenmj053/querytickets | tickets.py | tickets.py | py | 5,024 | python | en | code | 0 | github-code | 6 |
26524076638 | import math
def calculatein(main_list, dictionary, imm, non_imm):
time_loss = 0
for f, l in imm:
fir = main_list.index(f)
sec = main_list.index(l)
order = [fir, sec]
order.sort()
sub_list = main_list[order[0]+1: order[1]+1]
for i in range(0, len(sub_list)):
... | mortezatajerii/projects | Python/quera-program programmer.py | quera-program programmer.py | py | 2,368 | python | en | code | 0 | github-code | 6 |
18956703257 | from datetime import datetime, timezone
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
import logging
import os
import mongo_client
from typing import Optional, List, Union
import random
client = WebClient(token=os.environ.get("SLACK_TOKEN"))
good_words_collection = mongo_client.get_good_... | isaacson-f/slack-bots | goodwords_service.py | goodwords_service.py | py | 2,887 | python | en | code | 0 | github-code | 6 |
5033666757 | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.db import transaction
from django.template import loader
from django.core.exceptions import ValidationError
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from djan... | davidbarat/P13 | needhelp/help/views.py | views.py | py | 3,219 | python | en | code | 0 | github-code | 6 |
28395924014 | import os
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
class AnimeDataset(Dataset):
def __init__(self, dataset_path, image_size):
self.transform = transforms.Compose([
transforms.Resize(image_size),
transforms.Cen... | cwpeng-cn/DCGAN | data.py | data.py | py | 1,276 | python | en | code | 0 | github-code | 6 |
8528358737 | """
crown.py
COMP9444, CSE, UNSW
"""
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
# the data for this task has three columns: x y and class.
# the input of nn will be x and y, and the output will be a binary class.
class Full3Net(torch.nn.Module):
# assume we have a linear nn here:
... | sijinwnag/COMP9444_HW1 | hw1/crown.py | crown.py | py | 2,002 | python | en | code | 0 | github-code | 6 |
12066066456 |
from random import randint
# n = randint(0, 100)
n = 71
playing = True
count = 0
while playing:
guess = int(input('Guess my number (0-100)? '))
if guess > n:
print('Too big')
elif guess < n:
print('Too small')
else:
print('bingo')
break
count += 1
if count == 7:
... | paty0504/nguyentienthanh-fundamental-c4e13 | ss3/test.py | test.py | py | 360 | python | en | code | 0 | github-code | 6 |
39189785619 | """
Example of the FrequentistSurface plot.
Usage: surf_plot.py FILE
where FILE is a file containing Surface to be plotted. The surface is expected
to be found in the `/surface` directory of the FILE.
"""
import sys
import matplotlib.pyplot as plt
from cafplot import load
from cafplot.plot.surface import (
plot_... | usert5432/cafplot | examples/surf_plot.py | surf_plot.py | py | 791 | python | en | code | 0 | github-code | 6 |
75145119867 | A, B = map(int,input().split())
C = int(input())
hour = (B+C)//60 # 몫이므로 (30+20)//60= 0 이렇게 더함
min = (B+C)%60 # 나머지
if (B+C >= 60):
if (A+hour >= 24): # 24시간 넘어갈 경우 24시간 빼줘서 0부터 시작하게 만들어줌
A = A-24
A = A + hour # 뺴준 값에다 다시 hour 더해주기
print(A, min)
else: # B+C < 60
if(A >= 24):
A = A-24
... | zlnongi/Algorithm | baekjoon17.py | baekjoon17.py | py | 429 | python | ko | code | 1 | github-code | 6 |
24347960900 | import numpy as np
import os
from .image_extraction import extract_images_from_pdf
from .images import get_box
from PIL import Image
from flask import current_app
def reference_image(exam_id, page, dpi, widget_area_in=None, padding=0):
"""Returns a reference image for a specified area
The reference image is... | zesje/zesje | zesje/blanks.py | blanks.py | py | 3,019 | python | en | code | 9 | github-code | 6 |
24955814708 | import shutil
import pytest
from repo2rocrate.snakemake import find_workflow, get_lang_version, make_crate
SNAKEMAKE_ID = "https://w3id.org/workflowhub/workflow-ro-crate#snakemake"
def test_find_workflow(tmpdir):
root = tmpdir / "snakemake-repo"
workflow_dir = root / "workflow"
workflow_dir.mkdir(paren... | crs4/repo2rocrate | test/test_snakemake.py | test_snakemake.py | py | 3,932 | python | en | code | 1 | github-code | 6 |
2785515345 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import logging as log
from time import sleep
from html import escape
import requests
class FloodException(Exception): pass
def send(config, post):
# prepare config
c = {'token': '', 'chat': '', 'maxlength': 1000, 'skip': [], 'censor': []}
c.update(... | TechCiel/Reachee | sender/telegram.py | telegram.py | py | 2,274 | python | en | code | 11 | github-code | 6 |
10422651353 | from __future__ import annotations
import copy
from dataclasses import dataclass
from enum import Enum
from typing import TYPE_CHECKING, Self
from randovania.bitpacking import bitpacking
from randovania.bitpacking.bitpacking import BitPackDecoder, BitPackEnum, BitPackValue
from randovania.bitpacking.type_enforcement ... | randovania/randovania | randovania/layout/base/dock_rando_configuration.py | dock_rando_configuration.py | py | 8,008 | python | en | code | 165 | github-code | 6 |
11467657062 | # p161 미로찾기(그래프탐색)
def solve_maze(g, start, end):
qu = []
done = set()
qu.append(start)
done.add(start)
while qu:
p = qu.pop(0)
v = p[-1]
if v == end:
return p
for x in g[v]:
if x not in done:
qu.append(p + x)
... | hsyeon4001/algorithm_records | Python/교재/5.py | 5.py | py | 2,747 | python | en | code | 0 | github-code | 6 |
23647554795 | from flask import render_template, request, flash, jsonify
from appInitialize import app, db
from model.client import Client
from model.product import Product
from model.order import Order
import json
@app.route('/')
def index ():
return render_template('layout.html')
#Consultar clientes
@app.route('/read/clients... | cesar-orozco-chr/tienda-online | read/app.py | app.py | py | 4,862 | python | en | code | 0 | github-code | 6 |
30493177090 | #Seting the Hyper Parameters
param_test1 = {
'max_depth':[3,5,6,10],
'min_child_weight':[3,5,10],
'gamma':[0.0, 0.1, 0.2, 0.3, 0.4],
# 'reg_alpha':[1e-5, 1e-2, 0.1, 1, 10],
'subsample':[i/100.0 for i in range(75,90,5)],
'colsample_bytree':[i/100.0 for i in range(75,90,5)]
}
#Creating the classifier
model_xg = XGB... | garagaby/Kernel-Airflow | bin/implementing_pipeline_models.py | implementing_pipeline_models.py | py | 681 | python | en | code | 0 | github-code | 6 |
7176555609 | import functools
from typing import (
Any,
Callable,
TypeVar,
cast,
)
import warnings
TFunc = TypeVar("TFunc", bound=Callable[..., Any])
def deprecate_method(func: TFunc, message: str = None) -> TFunc:
@functools.wraps(func)
def deprecated_func(*args: Any, **kwargs: Any) -> Any:
warni... | ethereum/py-evm | eth/tools/_utils/deprecation.py | deprecation.py | py | 662 | python | en | code | 2,109 | github-code | 6 |
40880830024 | from bs4 import BeautifulSoup
import requests,re,os
import textract
os.chdir("..")
DATA_DIR = "data/fiscal_pdf"
SAVE_DIR = "data/fiscal_txt"
pre_link="http://www.imf.org"
target_dir = "http://www.imf.org/external/np/g20/"
g8_link = "http://www.g8.utoronto.ca/summit/index.htm"
# Extract all IMF Staff Note from IMF webs... | utipe/imf_fiscal | code/corpus_extraction.py | corpus_extraction.py | py | 1,880 | python | en | code | 0 | github-code | 6 |
19365158235 | import pickle, ssl, logging
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import pytorch_lightning as pl
import models, curves, utils1, utils, preresnet, resnet
DATASET = datasets.CIFAR10
TEST_ITEMS = 50_000
BATCH_SIZE = 128... | jonasjuerss/mode-connectivity | james/main.py | main.py | py | 12,280 | python | en | code | 0 | github-code | 6 |
70073356027 | from asyncio import coroutine, get_event_loop
from time import time
import requests
import json
class IngestaoDadosDogs:
def __init__(self, urls, dir):
self.urls = urls
self.dir = dir
@coroutine
def collect(self):
start = time()
loop = get_event_loop()
scrape_li... | gustavo-duarte-silva/MentoramaPythonPRO_MOD9 | mod9pro/ScriptsAssincronos/scriptConcorrente.py | scriptConcorrente.py | py | 1,155 | python | en | code | 0 | github-code | 6 |
37187212499 | # solved by satyam kumar (refernce https://www.youtube.com/watch?v=cjWnW0hdF1Y)
# question link https://leetcode.com/problems/longest-increasing-subsequence/
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
# creating cache
lst=[1]*len(nums)
# iterating from e... | saty035/DSA_Python | Longest Increasing Subsequence_leetcode/Longest Increasing Subsequence.py | Longest Increasing Subsequence.py | py | 675 | python | en | code | 2 | github-code | 6 |
38285343171 | """
Created on Fri Apr 24 11:34:48 2020
Matthew Irvine
1001401200
4/24/2020
Windows 10
"""
import os
def getFullSize(path):
#variables used to determine if the path is a file or a directory
isFile = os.path.isfile(path)
isDir = os.path.isdir(path)
#if it is a file
if isFile:
#calcu... | Tropolopolo/ProgrammingLanguages | mli1200_PA6/mli1200_PA6.py | mli1200_PA6.py | py | 1,257 | python | en | code | 0 | github-code | 6 |
27773589780 | import os
import asyncio
from telepyrobot.setclient import TelePyroBot
from pyrogram import filters
from pyrogram.types import Message
from telepyrobot import COMMAND_HAND_LER
from telepyrobot.utils.pyrohelpers import ReplyCheck
__PLUGIN__ = os.path.basename(__file__.replace(".py", ""))
__help__ = f"""
`{COMMAND_HAND... | Divkix/TelePyroBot | telepyrobot/plugins/self_destruct.py | self_destruct.py | py | 1,145 | python | en | code | 40 | github-code | 6 |
41045511776 | #!/usr/bin/python3
# Simon, Simon, Silvija
number1 = 0
number2 = 0
operation = None
bAsk = 1
def add(number1, number2):
print(number1 + number2)
def subtract(number1, number2):
print(number1 - number2)
def multiply(number1, number2):
print(number1 * number2)
def divide(number1, number2):
try:
... | simonSlamka/UCL-ITtech | programming/calc_pairChallenge.py | calc_pairChallenge.py | py | 1,809 | python | en | code | 2 | github-code | 6 |
39620185683 |
# Importa e define oque for nescessário para o código
import pygame
import random
WIDTH = 880
HEIGHT = 660
from config import GAME, QUIT
def init_screen(screen):
# Variável para o ajuste de velocidade
clock = pygame.time.Clock()
# Carrega o fundo da tela inicial
background = pygame.image.load('Flyin... | RodrigoAnciaes/Flying_Fox_game | Flying_Fox_Game/first_screen.py | first_screen.py | py | 1,182 | python | pt | code | 0 | github-code | 6 |
34375411916 | #!/usr/bin/env python3
from curses import wrapper
from functools import partial
from Gamepad import Gamepad
import curses
import time
def spd_scale(y0, x0, y1, x1, x):
"""Get the speed at the given value of time.
NOTE: The output is not clamped,
regardless of the reference points given."""
# Two ... | kknives/rudra-training | motor-control/js_control.py | js_control.py | py | 2,024 | python | en | code | 0 | github-code | 6 |
29477807046 | """
Portfolio: LongWrite
#100DaysOfCode with Python
Day: 89
Date: 2023-07-21
Author: MC
"""
from tkinter import *
from time import strftime, gmtime
from tkinter.messagebox import showinfo
from tkinter import filedialog
# ---------------------------- constance ------------------------------------ #
FONT_48 = ("New... | chinek01/LongWrite | main.py | main.py | py | 5,331 | python | en | code | 0 | github-code | 6 |
40449028487 | from ray.rllib.evaluation import MultiAgentEpisode, RolloutWorker
from ray.rllib.agents.callbacks import DefaultCallbacks
from ray.rllib.env import BaseEnv
from ray.rllib.policy import Policy
from typing import Dict
from ray.rllib.policy.sample_batch import SampleBatch
import numpy as np
import time
import csv
import... | tud-amr/AC-LCP | utils/callbacks.py | callbacks.py | py | 12,175 | python | en | code | 2 | github-code | 6 |
9980232390 | class Settings():
""" A class to store all the settings for our Alien Invasion Game. """
def __init__(self):
""" Initialize the game's settings """
#Screen settings
#Height and Width of our game screen.
self.screen_width = 1200
self.screen_height = 800
#Set the... | mihirjadhav04/Alien_Invasion_Game | settings.py | settings.py | py | 1,857 | python | en | code | 0 | github-code | 6 |
741344040 | import os
from pytest_mock import MockFixture
from app.config import get_config, DevelopmentConfig, ProductionConfig, PRODUCTION, DEVELOPMENT
def test_get_config_in_development():
app_config = get_config()
assert app_config.env == DEVELOPMENT
assert isinstance(app_config, DevelopmentConfig)
def test_... | hrozan/utfpr-final-paper | legacy/smart-object/tests/test_config.py | test_config.py | py | 771 | python | en | code | 2 | github-code | 6 |
39620196443 | # ===== Inicialização =====
# ----- Importa e inicia pacotes
import pygame
import random
pygame.init()
# ----- Gera tela principal
WIDTH = 880
HEIGHT = 800
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Flying_Fox')
gravity = 1
difficult = 0
# ----- Inicia assets
METEOR_WIDTH = 100
METE... | RodrigoAnciaes/Flying_Fox_game | Folder_de_Testes/Flappy.py | Flappy.py | py | 4,902 | python | en | code | 0 | github-code | 6 |
15662314012 | '''
The 'd' in projd stands for directory. Project based helper functions. A
project is a group of files and directories within a common root dir. This
module contains functions for finding the root directory, etc.
There are two sub-organizing principles seen in projects, based around how they
find the root directo... | todddeluca/projd | projd.py | projd.py | py | 5,109 | python | en | code | 0 | github-code | 6 |
27241749881 | import pygal
from random import randint
class Die:
def __init__(self, sides=6):
self.sides = sides
def roll(self):
return randint(1, self.sides)
die = Die(8)
die_1 = Die(8)
results = [die.roll() + die_1.roll() for x in range(1000)]
frequencies = [results.count(x) for x in range(2, 2 * di... | mbrad26/Data-Vizualization | Recap/recap_die_2d8.py | recap_die_2d8.py | py | 580 | python | en | code | 0 | github-code | 6 |
4829544125 | def main():
#fuel()
taqueria()
def fuel():
tank = float(tank_status()) * 100
if tank <= 1:
print('E')
elif tank >= 99:
print('F')
else:
print(str(int(tank)) + "%")
def tank_status():
while True:
fract = input("Fraction: ").split("/")
try:
... | Calvin-Spens/scripting | python_scripting/cs50_problems/problem_set_3.py | problem_set_3.py | py | 637 | python | en | code | 0 | github-code | 6 |
40464221544 | import os.path
import re
import numpy as np
from PIL import Image
NUM_RE = re.compile(r'(\d+)')
maxint = 999999
WHITE_LIST_FORMATS = {'png', 'jpg', 'jpeg', 'bmp'}
def hstack_images(input_filenames, target_size=(224, 224)):
"""
Horizontally stack all images from @input_filenames in order and write to @out... | eklitzke/dnn-fastai-project | vidextend/flow.py | flow.py | py | 2,047 | python | en | code | 2 | github-code | 6 |
34107122191 | from flask import g, request, current_app
import iot_api_core
import time
class InstanceVersionBaseBehavior():
def __init__(self, widget_type, namespace, instance_id):
self.widget_type = widget_type
self.namespace = namespace
self.instance_id = instance_id
self.lumavate = iot_api_core.Lumavate()
... | Lumavate-Team/python-hello | app/iot_api_core/instance_version_base.py | instance_version_base.py | py | 12,129 | python | en | code | 0 | github-code | 6 |
29358868643 | from sqlalchemy.orm import joinedload
from clld.db.util import get_distinct_values
from clld.db.models import common
from clld.web import datatables
from clld.web.datatables.base import LinkCol, Col, LinkToMapCol
from clld.web.datatables.parameter import Parameters
from clld.web.datatables.value import Values, ValueNam... | tsammalex/plansa | plansa/datatables.py | datatables.py | py | 2,802 | python | en | code | 0 | github-code | 6 |
5759869864 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
#%% Importar los datos (leer la imagen)
img = mpimg.imread('../Data/indice.png')
plt.imshow(img)
#%% reordenar la imagen en una sola tabla
d = img.shape
img_col = np.reshape(img,(d[0]*d[1],d[2]))
#%% Convertir los datos a media cero... | OscarFlores-IFi/CDINP19 | code/p13.py | p13.py | py | 1,039 | python | es | code | 0 | github-code | 6 |
72370696507 | from django.urls import path
from products.views import (
CreateProduct,
CreateOption,
Products,
UpdateProduct,
Option,
UpdateOption,
)
urlpatterns = [
path("", Products.as_view()),
path("create/product", CreateProduct.as_view()),
path("update/product/<int:pk>", UpdateProduct.as_vie... | ohnas/Manager-backend | products/urls.py | urls.py | py | 478 | python | en | code | 0 | github-code | 6 |
8595213301 | import openpyxl,os,shutil
import pandas as pd
import pymssql
from sqlalchemy import create_engine
backupPath='files-backup'
def get_xlsx_to_dataframe(fliename):
wb = openpyxl.load_workbook(fliename)
sheets = wb.sheetnames
ws = wb.get_sheet_by_name(sheets[0])
df = pd.read_excel(fliename)
if not o... | zjz7304/xlsx_to_database | util.py | util.py | py | 666 | python | en | code | 0 | github-code | 6 |
2687351802 | import numpy as np
import matplotlib.pyplot as plt
import random as rnd
import turtle
N = 100
Nw = 1000
def wedrowniczek(length):
x0, y0 = 0,0
x,y = x0,y0
walkx,walky = [x],[y]
for i in range(length):
rand = rnd.randint(1,4)
if rand == 1:
x += 1
elif rand == 2:
y += 1
elif rand == ... | filipmalecki94/Computer_modeling | lista3/zadanie1.py | zadanie1.py | py | 784 | python | en | code | 0 | github-code | 6 |
3081251304 | # -*- coding: utf-8 -*
"""Graphics
.. module:: graphics
:synopsis: Module for creating graphs
"""
# imports
import matplotlib.pyplot as plt
import numpy as np
import resoncalc.output as output
from math import ceil
from csv import DictReader
# globals
n_points = 1000 # count of points in graph
n_rows = 20.0 #... | hydratk/resoncalc | src/resoncalc/graphics.py | graphics.py | py | 8,384 | python | en | code | 0 | github-code | 6 |
75401661626 | import numpy as np
import time
import torch
from multiprocessing import Array, Manager
from dgl.dataloading.dataloader import GraphCollator
from collections import deque, namedtuple
from gp.utils.datasets import DatasetWithCollate
"""
Following namedtuple makes data collating nad referencing easier
"""
GraphLabelN... | LechengKong/MAG-GNN | dataset.py | dataset.py | py | 4,231 | python | en | code | 1 | github-code | 6 |
18524960895 | exp_name = 'cdr_0fold'
_base_ = [
'../_base_/models/late_integration_drp/base_deepCDR.py',
'../_base_/dataset/drp_dataset/drugs_genes_dataset.py',
'../_base_/exp_setting/base_setting.py',
'../_base_/default_runtime.py'
]
data = dict(
train=dict(
celllines_data='data/processed_raw_data/564_c... | yivan-WYYGDSG/AGMI | configs/deepcdr/cdr.py | cdr.py | py | 1,014 | python | en | code | 1 | github-code | 6 |
3025420311 | import sys
file = str(sys.argv[1]) # file passed through command line
with open(file) as f:
input = f.read().split('\n')
def detector(data: list, size: int) -> list:
pos = []
for line in data:
for i in range(len(line)):
seq = line[i:i+size]
if len(set(seq)) == len(seq):
... | cclark20/aoc | solutions/day_06.py | day_06.py | py | 483 | python | en | code | 0 | github-code | 6 |
5564785730 | from src.core.interfaces.model_abc import ModelAbstract
from src.core.interfaces.repository_abc import RepositoryAbstract
from src.shared import parse_config
from sqlalchemy.orm import Session
import logging
import logging.config
import dataclasses
from typing import List
from datetime import datetime
class SqlAlchem... | ricky-codes/APIGest | src/infrastructure/services/repository.py | repository.py | py | 3,071 | python | en | code | 0 | github-code | 6 |
17591759593 | import pathlib
from PIL import Image
class image_to_c_array:
def __init__(self, image_path, output_path, format_bytes_count, char_array_name, include_header_guard=False, include_header_guard_name=None, reset_output_file=True):
self.image_path = image_path
self.output_path = output_path
... | 0xRooted/File-To-C-Array | filetocarray.py | filetocarray.py | py | 1,846 | python | en | code | 0 | github-code | 6 |
26112891425 | __authors__ = ["T. Vincent"]
__license__ = "MIT"
__date__ = "07/01/2019"
import os
import logging
import weakref
from . import qt
import silx.resources
from silx.utils import weakref as silxweakref
_logger = logging.getLogger(__name__)
"""Module logger"""
_cached_icons = None
"""Cache loaded icons in a weak struc... | silx-kit/silx | src/silx/gui/icons.py | icons.py | py | 11,642 | python | en | code | 106 | github-code | 6 |
38076886961 | import os
from pathlib import Path
from tempfile import NamedTemporaryFile
import pytest
import pytest_mock
from werkzeug.exceptions import NotFound
from iceart.models import Artist, ArtistDto, ArtistViewModel
def test_artist_vm_init():
with pytest.raises(NotFound):
ArtistViewModel(-1)
def test_artist... | JonSteinn/iceart_api | tests/test_models/test_artist.py | test_artist.py | py | 1,537 | python | en | code | 1 | github-code | 6 |
35522645807 | import requests
from time import sleep
timeToWait = 300 # Time to wait between callouts (in seconds)
while (True):
# Get list of commands to run this callout
URL = "https://slack.flemingcaleb.com:5000/api/agent/4/command/"
r = requests.get(url=URL)
if r.status_code == requests.codes.ok:
# Pro... | flemingcaleb/InfraBot | agent/agent.py | agent.py | py | 567 | python | en | code | 3 | github-code | 6 |
72330655547 | # TEE RATKAISUSI TÄHÄN:
def summa(luku: int):
# kun luku on 1, ei ole muita summattavia...
if luku <= 1:
return luku
return luku + summa(luku - 1)
if __name__ == "__main__":
tulos = summa(3)
print(tulos)
print(summa(5))
print(summa(10)) | jevgenix/Python_OOP | osa11-14_rekursiivinen_summa/src/rekursiivinen_summa.py | rekursiivinen_summa.py | py | 278 | python | fi | code | 4 | github-code | 6 |
39756253957 | """
Plot a grid on H2
with Poincare Disk visualization.
"""
import logging
import os
import matplotlib.pyplot as plt
import numpy as np
import geomstats.visualization as visualization
from geomstats.geometry.hyperbolic import Hyperbolic
H2 = Hyperbolic(dimension=2)
METRIC = H2.metric
def main(left=-128,
... | hhajri/geomstats | examples/plot_grid_h2.py | plot_grid_h2.py | py | 1,552 | python | en | code | null | github-code | 6 |
1004630370 | """
DESKRIPSI SOAL
Buatlah program yang menerima 3 buah input nilai dan outputkan jumlah maksimal
dari 2 bilangannya ! diantara ketiga input tersebut.
PETUNJUK MASUKAN
Input terdiri atas 3 angka dalam 1 baris
PETUNJUK KELUARAN
Outputkan angka jumlah terbesar dari 2 angka
"""
a, b, c = list(map(int, input().split... | refeed/PAlgoritmaTRPLA | OKT_22_2020/uts_problem_i.py | uts_problem_i.py | py | 595 | python | id | code | 0 | github-code | 6 |
74056199547 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .activations import ACTIVATIONS
class Embedding(nn.Module):
'''
Abstract base class for any module that embeds a collection of N vertices into
N hidden states
'''
def __init__(self, features, hidden, **kwargs):
super()... | isaachenrion/jets | src/architectures/embedding/embedding.py | embedding.py | py | 2,081 | python | en | code | 9 | github-code | 6 |
31146266095 | import tensorflow as tf
import keras.backend as K
def huber_loss(y_true, y_pred):
return tf.losses.huber_loss(y_true, y_pred)
def adjust_binary_cross_entropy(y_true, y_pred):
return K.binary_crossentropy(y_true, K.pow(y_pred, 2))
def MMD_Loss_func(num_source, sigmas=None):
if sigmas is None:
s... | rs-dl/MMD-DRCN | customLoss.py | customLoss.py | py | 1,575 | python | en | code | 7 | github-code | 6 |
14255581243 | from selenium import webdriver
import time, re
from bs4 import BeautifulSoup
import pyautogui
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
import pyperclip
import os
# 主要功能就是访问300mium所有影片详情页,然后挨个下载封面
class Crawl_51luxu:
def main(self, Dir='F:\\pic\... | ExcaliburEX/GHS | Crawl_51luxu.py | Crawl_51luxu.py | py | 7,503 | python | en | code | 5 | github-code | 6 |
35573581070 |
from models.resnet import ResNet
from models.unet import UNet, UNet_dualHeads
model_zoo = {
'UNet': UNet,
'UNet_dualHeads': UNet_dualHeads
}
def get_model(cfg):
########################### COMPUTE INPUT & OUTPUT CHANNELS ############################
print("Satellites: ", cfg.DATA.satellites)
pr... | puzhao8/sentinel2-burn-severity | models/__init__.py | __init__.py | py | 1,171 | python | en | code | 0 | github-code | 6 |
72010622268 |
#Stack using Linked List
class StackNode:
def __init__(self,data):
self.data=data
self.next=None
class Stack:
def __init__(self):
self.root=None
def isempty(self):
return True if self.root is None else False
def push(self,data):
new_node=StackNode(data)
n... | Hemasri-3/datastructures_in_python | stack.py | stack.py | py | 1,018 | python | en | code | 0 | github-code | 6 |
15451649393 | #!/bin/python
import csv
import urllib
import sys
if __name__ == "__main__":
with open('payphone_set.csv', 'rb') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
if row[0] == 'ID':
continue
number = "+" + row[0]
neighborhood = row[7]
lat = row[5]
lon = row[6]
params = url... | emilyville/SFpayphones | upload.py | upload.py | py | 575 | python | en | code | 4 | github-code | 6 |
33205173219 | from django.urls import path
from .views import (get_user, add_user, get_categories, get_recipe,
add_to_favourite, get_user_favourites,
get_recipes_in_category, get_random_recipe,
add_to_dislikes)
urlpatterns = [
path('users/<int:telegram_id>', get_user... | AlexanderZharyuk/recipes | recipes_admin_api/api/urls.py | urls.py | py | 684 | python | en | code | 1 | github-code | 6 |
32371727829 | def main():
for cont in range(0, 44):
with open("C:\\Users\\p22.ribeiro\\OneDrive\\repocode\\challenge-python\\dataset\\{}".format(cont), "r", encoding="cp1252") as arquivo:
frase = arquivo.read()
for remove in '!@#$%&*()<>:;,./?\|][}{=+-"~£':
frase = frase.replace(remove, ' ').lowe... | htmribeiro/challenger-python | others/reverse_index.py | reverse_index.py | py | 770 | python | pt | code | 0 | github-code | 6 |
24206813915 | import webapp2
import jinja2
import os
from google.appengine.ext import db
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
template_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=True)
def to_render(template, **para):
t = template_env.get_template(template)
... | tongtie/udacity | WebDevelopment/hw3/my_solution.py | my_solution.py | py | 2,089 | python | en | code | 0 | github-code | 6 |
13058259505 | from datetime import datetime, timezone
from config import Config
from logger import logger
from model.coordinates import Coordinates
from model.media_type import MediaType
from model.ts_source import TsSource
class MediaFile:
original_path: str
original_filename: str
filename: str
media_type: MediaT... | mbogner/imagination | model/media_file.py | media_file.py | py | 3,104 | python | en | code | 0 | github-code | 6 |
19482945267 | import math
import random
import numba as nb
import numpy as np
@nb.jit(nopython=True)
def dimension_selector_uniform(n_dimensions):
return random.randrange(n_dimensions)
def get_dimension_selector_expovariate(
lambd=None,
rel_lambd=None,
):
if lambd is not None and rel_lambd is not None:
r... | risicle/cluscheck | cluscheck/__init__.py | __init__.py | py | 7,246 | python | en | code | 0 | github-code | 6 |
18339770466 | import requests
import json
url = "https://api.telegram.org/bot5653233459:AAHWejZRnvy4luWTetBSbQY5jTzS11mA35U/sendMessage"
photo_url = "https://api.telegram.org/bot5653233459:AAHWejZRnvy4luWTetBSbQY5jTzS11mA35U/sendPhoto"
document_url = "https://api.telegram.org/bot5653233459:AAHWejZRnvy4luWTetBSbQY5jTzS11mA35U/sendD... | mayuritoro/tele_bot | tele_bot/trial.py | trial.py | py | 5,973 | python | en | code | 0 | github-code | 6 |
34228298510 | import os
import re
import sys
import glob
import builtins
from contextlib import contextmanager
import setuptools
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as _build_ext
from setuptools.command.install import install as _install
with open("README.md", "r") as fh:
... | AlkaidCheng/aliad | setup.py | setup.py | py | 1,655 | python | en | code | 0 | github-code | 6 |
20052609139 | import numpy as np
import matplotlib.pyplot as plot
import math
def jacobi(x):
x1, x2 = x
return np.array([[1, math.sin(x2)], [-math.cos(x1), 1]])
def func(x):
x1, x2 = x
return np.array([x1 - math.cos(x2) - 1, x2 - math.sin(x1) - 1])
def find_delta_x(f, J):
return np.linalg.solve(J, -1 * f)... | mehakun/Labs | 6th_semester/NumMethods/2_lab/task_2.py | task_2.py | py | 3,004 | python | en | code | 2 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.