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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
74827059552 | # Este codigo tiene que correrse en el repositorio de cb-da
from cb_da import da
from cb_lottery_maker import lottery_maker
from entities.data_processing import data_preparation, output_preparation
import pandas as pd
import os
##--------------------------------------------------------------------------------... | EL-BID/matricula-digital-tacna | cb_da/da_tacna_sin_distancia.py | da_tacna_sin_distancia.py | py | 2,820 | python | en | code | 0 | github-code | 1 |
71874425955 | #!/usr/bin/python3
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
import RPi.GPIO as GPIO
import time
import pyotp
import atexit
app = Flask(__name__)
totp = pyotp.TOTP(pyotp.random_base32())
setup_mode = True
@app.route('/sms', methods=['POST'])
def sms():
global ... | connickshields/garage-pi | app.py | app.py | py | 1,109 | python | en | code | 0 | github-code | 1 |
29659773390 | """
Write a program to search for the "saddle points" in a 5 by 5 array of
integers.
A saddle point is a cell whose
value is greater than or equal to any in its row,
and less than or equal to any in its column.
There may be more than one saddle point in the array.
Print out the coordinates of any saddle points your p... | CarltonBranch/Python-Portfolio-2023 | university_exercises/saddle_points.py | saddle_points.py | py | 3,476 | python | en | code | 0 | github-code | 1 |
41094584105 | from sqlalchemy import Column, Integer, String, TIMESTAMP, LargeBinary
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Image(Base):
__tablename__ = 'image'
id = Column(Integer, primary_key=True)
filename = Column(String(255))
content_type = Column(String(50))
... | lavrinec/GOV-Crawler | crawler/src/image.py | image.py | py | 612 | python | en | code | 0 | github-code | 1 |
23000939408 | import heapq
def selection_sort(array):
for i in range(len(array)):
min_val = i
for j in range(i+1,len(array)):
if array[j] < array[min_val]:
min_val = j
temp = array[i]
array[i] = array[min_val]
array[min_val] = temp
return array
def inserti... | antoniofranciscoandrade/data-structures-algorithms | algorithms/sort.py | sort.py | py | 3,686 | python | en | code | 0 | github-code | 1 |
33239264929 | # -*- coding: utf-8 -*-
from django.conf.urls import *
from django.conf import settings
urlpatterns = patterns('gibbon',
# url(r'^admin/', include(admin.site.urls)),
# url(r'^$', 'views.home'),
url(r'^$', 'views.hello'),
url(... | bung87/gibbon | gibbon/urls.py | urls.py | py | 582 | python | en | code | 0 | github-code | 1 |
34470440270 | # 내가 정의할 것
# 주사위 정보 => 위치, 위 앞 옆, 방향
# 점수 => 숫자 * 개수
# 위치 => 처음엔 0, 0 / 오른쪽으로 움직임
# 회전 => 주사위 아랫면이 보드 해당칸에 있는 숫자보다 크면 현재 진행방향에서 90도 시계방향 회전
# 주사위 아랫면이 더 작으면 반시계 90도 회전
# 동일하면 현재 방향
from collections import deque
n, m = map(int, input().split())
grid = [list(map(int, input().split())) for _ in range(n)]
... | yeafla530/algorithms | 코드트리/삼성코데_2023/2021_상반기_정육면체한번더굴리기.py | 2021_상반기_정육면체한번더굴리기.py | py | 2,898 | python | ko | code | 0 | github-code | 1 |
24676602198 | from azure.storage.blob import BlockBlobService
from azure.storage.blob import ContentSettings
from azure.storage.blob import PublicAccess
import csv
import random
import time
import datetime
import os
path = '/Users/boxunng/Desktop/ClickStream/sample_data'
os.chdir(path)
# Blob 相關
mystoragename = "demousestorageaccou... | HaydenNBX/AzureProject | ClickStream/create_data_upload_blob001.py | create_data_upload_blob001.py | py | 1,887 | python | en | code | 0 | github-code | 1 |
43177819716 | from http import HTTPStatus
import allure
import pytest
from base.api.base import BaseAPI
from base.api.users.resource_libraries.resource_libraries import get_resource_library, get_resource_libraries, \
create_resource_library, update_resource_library, delete_resource_library
from base.api.users.resource_librarie... | Nikita-Filonov/demo_auto_tests | tests/api/users/permissions/scopes/test_scopes_for_resource_libraries.py | test_scopes_for_resource_libraries.py | py | 3,026 | python | en | code | 3 | github-code | 1 |
1593219832 | import tkinter as tk
from tkinter import messagebox
import socket
SERVER_ADDRESS = "localhost"
SERVER_PORT = 8080
def send_data():
pan_number = entry_pan.get()
'''password = entry_password.get()'''
if not pan_number :
messagebox.showerror("Error", "Please enter PAN card number .")
return
... | belhamra1/tokenization | theclient.py | theclient.py | py | 1,720 | python | en | code | 0 | github-code | 1 |
16755595914 | '''
Creates the plot of the predicted amount of waste for different mutation
rates and different numbers of active genes. To make the plot use:
python wasteplot.py
The graph will be saved to Probability.eps
NOTE: You CANNOT use pypy for this as pylab is current unsupported. Use
python 2.7 instead.
'''
from pylab i... | brianwgoldman/ReducingWastedEvaluationsCGP | wasteplot.py | wasteplot.py | py | 883 | python | en | code | 11 | github-code | 1 |
10264187346 | from molecula import frmolec
#import molecula.frmolec
import numpy as np
class SpectraCorr:
"""Módulo que faz as correções da contribuição de 13C nos espectros de massas.
"""
def __init__(self, controller, array):
# Inicializa as variáveis como locais.
self.controller = controller
# Array a ser corrigido
... | vicerodrigues/troca-hd | fileIO/spectracorr.py | spectracorr.py | py | 1,297 | python | pt | code | 1 | github-code | 1 |
24881862549 | import unittest
from downloader.constants import PathType
from test.objects import config_with
from test.fake_path_resolver import PathResolverFactory
base_path = '/standard'
base_system_path = '/system'
external_storage = 'off'
tmp_whatever = '/tmp/whatever'
normal_path_1 = 'normal/file'
normal_path_2 = 'other/fi... | theypsilon-test/downloader | src/test/unit/test_path_resolver.py | test_path_resolver.py | py | 4,227 | python | en | code | 0 | github-code | 1 |
23204502387 | import torch
import dgl
import numpy as np
from loading_data import loading_feature
from dgl.nn.pytorch import pairwise_squared_distance
from typing import List, Tuple
import math
"""
输入:左/右脑特征矩阵
输出:每个脑区一个链接矩阵
特征按照脑区分类、计算相似性、kNN建图
采集每个vertex所属脑区,构建相关性矩阵
有几个脑区没有,有些脑区数据点很多,考虑随机采样,有些脑区很少,考虑不要了?
DGL有计算相关性的公式:无
"""
def ... | taotianli/gin_model.py | examples/pytorch/PETMR/local_graph_construction.py | local_graph_construction.py | py | 4,951 | python | en | code | 5 | github-code | 1 |
10671630888 | # -*- coding: utf-8 -*-
# Author: trummerjo
# Module: MSLHttpRequestHandler
# Created on: 26.01.2017
# License: MIT https://goo.gl/5bMj3H
"""Handles & translates requests from Inputstream to Netflix"""
from __future__ import absolute_import, division, unicode_literals
import traceback
import base64
import BaseHTTPServ... | Toysoft/plugin.video.netflix | resources/lib/services/msl/http_server.py | http_server.py | py | 2,507 | python | en | code | 4 | github-code | 1 |
1372879417 | import vision_msgs.msg as vision_msgs
def create_detection_msg(header, detections):
"""
Create Detection2DArray ROS message.
Parameters
----------
header : std_msgs.Header -- header with image's timestamp
detections : (n, 6) np.array -- n detections
Each detection is 2d bb... | mit-acl/yolov7_ros | yolov7_ros/src/yolov7_ros/utils.py | utils.py | py | 1,145 | python | en | code | 8 | github-code | 1 |
72362822113 | load(
"//rules:common.bzl",
_common = "common",
)
load("//rules:java.bzl", _java = "java")
load(
"//rules:sandboxed_sdk_toolbox.bzl",
_sandboxed_sdk_toolbox = "sandboxed_sdk_toolbox",
)
load(
"//rules:utils.bzl",
_get_android_toolchain = "get_android_toolchain",
)
load(":providers.bzl", "Android... | bazelbuild/rules_android | rules/android_sandboxed_sdk/android_sandboxed_sdk_macro.bzl | android_sandboxed_sdk_macro.bzl | bzl | 3,857 | python | en | code | 165 | github-code | 1 |
26583529824 | import pygame
import os
import sys
import sqlite3
from helicopter import Helicopter
from person import Person
from board import Board
from camera import Camera
from enemy import Enemy
MYEVENTTYPE = pygame.USEREVENT + 1
COLOR_INACTIVE = pygame.Color('white')
COLOR_ACTIVE = pygame.Color('green')
user = 'guest'
class ... | irkatsuk/helicopter | game.py | game.py | py | 8,803 | python | en | code | 0 | github-code | 1 |
11060596998 | from selenium.webdriver.common.by import By
from traceback import print_stack
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import *
import utilities.custom_logger as cl
import logging
import time
import os
from s... | mohan1411-qa/QA_Automation_Testing | letsKode/base/selenium_driver.py | selenium_driver.py | py | 13,248 | python | en | code | 1 | github-code | 1 |
34499422240 | import csv
import time
import traceback
import ctypes
import os
import struct
from ctypes import *
from pymouse import PyMouse
from pykeyboard import PyKeyboard
class Action(object):
def __init__(self, file):
self.file = file
self.m = PyMouse()
self.k = PyKeyboard()
def action_read(sel... | DODdarcy/csv_mouse_drag | draw_c.py | draw_c.py | py | 3,947 | python | en | code | 0 | github-code | 1 |
29973357450 | # Se tiene una matriz cuadrada de orden N realizar lo siguiente
# - Hallar el promedio de la diagonal principal y el promedio de la diagonal secundaria
# - Ordenar ascendentemente la diagonal principal
# - Hallar el promedio de los pares que están encima de la diagonal principal y de los impares de la diagonal... | AndHak/Universidad-Semestre1-Python | Taller 3 - 13.py | Taller 3 - 13.py | py | 6,113 | python | es | code | 2 | github-code | 1 |
23211743948 | # set up for the Sod shock test
import get_cmake_command
sod_options = {
"rmin_in_au": 0.0,
"rmax_in_au": 6.68459e-12,
"ncell": 1000,
"gamma": 5.0 / 3.0,
"maxtime_in_yr": 6.342e-9,
"number_of_snaps": 10,
"ic": "IC_SOD",
"eos": "EOS_IDEAL",
"boundaries": "BOUNDARIES_OPEN",
"pote... | bwvdnbro/HydroCodeSpherical1D | write_configuration_sod.py | write_configuration_sod.py | py | 522 | python | en | code | 4 | github-code | 1 |
41034182924 | from __future__ import annotations
import abc
import functools
from typing import Any
from typing import AsyncGenerator
from typing import AsyncIterator
from typing import Awaitable
from typing import Callable
from typing import ClassVar
from typing import Dict
from typing import Generator
from typing import Generic
f... | sqlalchemy/sqlalchemy | lib/sqlalchemy/ext/asyncio/base.py | base.py | py | 8,718 | python | en | code | 8,024 | github-code | 1 |
30494415917 | #!/usr/bin/env python
__author__ = "Sam Way"
__copyright__ = "Copyright 2014, The Clauset Lab"
__license__ = "BSD"
__maintainer__ = "Sam Way"
__email__ = "samfway@gmail.com"
__status__ = "Development"
class Struct:
""" Create a Python object from a dictionary of key-values """
def __init__(self, **entries):... | samfway/university_network | misc/util.py | util.py | py | 1,179 | python | en | code | 0 | github-code | 1 |
8264772317 | # -*- coding: utf-8 -*-
"""
Brython GUI for leaflet map and various useful plugins
TODO :
- parent_element doit être dans le document avant insertion de la carte leaflet sinon KO
- régler le problème des load qui ne sont pas bons si on les mets dans un répertoire gui
"""
__author__ = "thierry.herve@f... | gitthious/brython-2Dmap | map2D.py | map2D.py | py | 4,188 | python | en | code | 0 | github-code | 1 |
36104276243 | import bpy
import bmesh
from mathutils import Vector, Matrix
# Internal modules
import nmv.scene
import nmv.mesh
import nmv.utilities
####################################################################################################
# @get_vertex_position
###########################################################... | BlueBrain/NeuroMorphoVis | nmv/mesh/ops/mesh_vertex_ops.py | mesh_vertex_ops.py | py | 30,319 | python | en | code | 111 | github-code | 1 |
12852099257 |
from flask import Blueprint, jsonify
from flask_apispec import doc, use_kwargs
from flask_jwt_extended import jwt_required, current_user
from webargs import fields
from ..import models, errors
app = Blueprint('post', __name__)
@doc(security=[{'bearer': []}], tags=['posts'])
@app.route('/')
@use_kwargs({
'cursor... | gnixxyz/flask-rest-api-example | web/routes/post.py | post.py | py | 1,246 | python | en | code | 0 | github-code | 1 |
16709470567 | import random
import math
cr=0.9999
t0=1000000
tmin=1
x1=random.uniform(-10,10)
x2=random.uniform(-10,10)
randx=random.uniform(0,1)
def f(x1,x2):
return (4-(2.1*(x1**2))+(x1**4)/3)*(x1**2)+(x1*x2)+(-4+(4*(x2**2))*x2**2)
"""Current State"""
cs=f(x1,x2)
while (t0>tmin):
y1 = (random.uniform(-10, 10))
y2 = ... | odiapratama/Simulated-Annealing | SimulatedAnnealing.py | SimulatedAnnealing.py | py | 903 | python | en | code | 0 | github-code | 1 |
10466685172 | #***************************************************************************
#* Copyright (c) 2001,2002 Jürgen Riegel <juergen.riegel@web.de> *
#* *
#* This file is part of the FreeCAD CAx development system. *
#* ... | 15831944/YanhuaNC-master | src/App/FreeCADInit.py | FreeCADInit.py | py | 25,685 | python | en | code | 0 | github-code | 1 |
25057062346 | from random import randint, random
__author__ = 'joelwhitney'
# SIE 558 - Final Take - Insert into DB
# this file:
# 1) opens connection to mysql db and sets up insert statement
# 2) set up pi serial connection
# 3) opens file to write results to and start reading from serial
# imports
import time
import... | snittel/SIE589_ImplementationofTemporalFields_JoelWhitney | TemporalFieldStream_InsertFakeDatatoDB.py | TemporalFieldStream_InsertFakeDatatoDB.py | py | 4,923 | python | en | code | 0 | github-code | 1 |
74539196192 | #!/usr/bin/env python3
# -- General configuration ------------------------------------------------
extensions = [
"sphinx_copybutton",
"sphinx_design",
"sphinx.ext.mathjax",
"sphinxext.rediraffe",
"myst_parser",
]
templates_path = []
source_suffix = [".rst", ".md"]
root_doc = "index"
# General inf... | jupyterhub/team-compass | docs/conf.py | conf.py | py | 3,426 | python | en | code | 62 | github-code | 1 |
4073730876 | #-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# NOTE: width of source code should be <= 80 characters to facilitate printing.
#23456789012345678901234567890123456789012345678901234567890123456789012345... | has220/Population-analysis | 211_P6.py | 211_P6.py | py | 15,984 | python | en | code | 0 | github-code | 1 |
40379512160 | import os
import sys
import setuptools
__version__ = ''
__author__ = ''
# Get the root path of the project
root_path = sys.argv[ 0 ].split( '/venv' )[ 0 ]
# Read the __version__ and __author__ inforrmation
with open( os.path.abspath( os.path.join( root_path, 'm3u_serializer', 'version.py' ) ) ) as f:
exec( f.rea... | pe2mbs/m3u_serializer | setup.py | setup.py | py | 860 | python | en | code | 0 | github-code | 1 |
26807926850 | import os
import sys
import numpy as np
import pytest
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
module = __import__("Scalarization", fromlist=["Tchebycheff"])
class TestTchebycheff:
@pytest.mark.parametrize(
("x", "w", "ans"),
[
(np.array([1, 2, 3]), np.array(... | mit17024317/2020-0730 | Optimizer/Search/Scalarization/test/test_Tchebycheff.py | test_Tchebycheff.py | py | 712 | python | en | code | 0 | github-code | 1 |
39729817988 | from tkinter import *
def order():
requested = []
for a in list_box.curselection():
requested.insert(a, list_box.get(a))
for b in requested:
print(f"You have ordered {b.title()}")
def entry():
a = entry_box.get()
list_box.insert(list_box.size(), a)
... | Mucodev/Learning_tk | tkinter/learning_tk_3.py | learning_tk_3.py | py | 1,226 | python | en | code | 0 | github-code | 1 |
1592915856 | import socket
from threading import Thread
class Udp(object):
def __init__ (self ,s):
self.s=s
def a(self):
p1=Thread(target=self.fs)
p2=Thread(target=self.js)
p1.start()
p2.start()
def fs(self):
while True:
data=input('请输入:')
se... | Lousm/Python | 02_py服务器,mysql/第7周/05复习/01_udp线程.py | 01_udp线程.py | py | 675 | python | en | code | 0 | github-code | 1 |
40029812168 | import random
num = random.randint(1, 100)
print(num)
fruit = random.choice(["apple", "orange", "grape", "banana", "strawberry"])
print(fruit)
coin = random.choice(["h", "t"])
guess = input("Enter heads or tails (h/t): ")
if guess == coin:
print("you won!")
else:
print("Bad luck.")
if coin == "h":
print(... | jozsefKecskesi/Python-projects | PythonBasics/random/randoms.py | randoms.py | py | 2,236 | python | en | code | 0 | github-code | 1 |
10990379924 | from towhee.runtime.factory import HubOp
class ImageEmbedding:
"""
`image_embedding <https://towhee.io/tasks/detail/operator?field_name=Computer-Vision&task_name=Image-Embedding>`_
is a task that attempts to comprehend an entire image as a whole
and encode the image's semantics into a real vector... | towhee-io/towhee | towhee/runtime/hub_ops/image_embedding.py | image_embedding.py | py | 8,425 | python | en | code | 2,843 | github-code | 1 |
41100281608 | """
init
"""
from vault_cleaner.kv2 import (
get_age_filtered_paths,
get_current_secret_data,
write_secret_data,
delete_path
)
def copy_kv2_secrets(source_mount: str, destination_mount: str, age: int):
"""
Summary:
get kv2 secrets older than $age days and copies them from source to des... | ewhitesides/vault_cleaner | source/vault_cleaner/__init__.py | __init__.py | py | 1,362 | python | en | code | 0 | github-code | 1 |
39705833845 | from rest_framework import serializers
from todolist.models import Task
from django.contrib.auth.models import User
class TaskSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Task
fields = ['url', 'id', 'owne... | GabrielCornejoB/to-do-app | back-end/todolist/serializers.py | serializers.py | py | 624 | python | en | code | 0 | github-code | 1 |
16346858484 | import time
from multiprocessing import Process, Manager
import cv2
from ultralytics import YOLO
def process_frame(original_frames, processed_frames):
# Load a model
model = YOLO('yolov8n.pt')
while True:
if original_frames.qsize() > 0:
original_frame = original_frames.get()
... | otm0937/yolo | multi_yolo.py | multi_yolo.py | py | 3,016 | python | en | code | 0 | github-code | 1 |
31269891808 |
soma = 0
contador = 0
while True:
valor = int(input('Digite um valor: '))
if valor == 0:
break
soma += valor
contador += 1
print(f'a soma de tudo é {soma}, total de {contador} numeros, média de {soma/contador:.^5.2f}') | PauloHudson/Python | 31.py | 31.py | py | 247 | python | pt | code | 0 | github-code | 1 |
29151062024 | #defining the function middle_element and giving it 1 parameter
def middle_element(lst):
#if statement to see if there are an even or odd number of elements in the list lst
if len(lst) % 2 == 0:
#if above answer is even we are setting the return value to be the avg of the middle two numbers of the list
#finding... | ghostkillerguy/ITP270-Whyrick | repls/middle_element.py | middle_element.py | py | 756 | python | en | code | 0 | github-code | 1 |
38725552119 | # source : https://leetcode.com/problems/valid-sudoku/submissions/
"""
Runtime: 116 ms, faster than 50.32% of Python3 online submissions for Valid Sudoku.
Memory Usage: 13.6 MB, less than 99.09% of Python3 online submissions for Valid Sudoku.
"""
#def isValidSudoku(self, board: List[List[str]]) -> bool:
def isValidSud... | Aprisyta/coding_interview_questions | leetcode/36 ValidSudoku.py | 36 ValidSudoku.py | py | 2,622 | python | en | code | 0 | github-code | 1 |
24275800266 | """
Simple twitter crawler program to gather Hungarian tweets
Authentication and twitter access
"""
import tweepy
auth = tweepy.OAuthHandler('#####', '#####')
auth.set_access_token('#-###', '#####')
api = tweepy.API(auth, wait_on_rate_limit=True)
try:
redirect_url = auth.get_authorization_url()
except tweepy.Twe... | TimmDay/machine_learning | tweetcrawler_auths.py | tweetcrawler_auths.py | py | 378 | python | en | code | 0 | github-code | 1 |
23278878197 | import os
import cv2
import lmdb
import numpy as np
import argparse
import shutil
import sys
def checkValid(imgBin):
if imgBin is None:
return False
try:
imgBuffer = np.fromstring(imgBin, dtype=np.uint8)
img = cv2.imdecode(imgBuffer, cv2.IMREAD_GRAYSCALE)
img_h... | saig599/Yr4_dissertation | 956299/create_dataset.py | create_dataset.py | py | 4,554 | python | en | code | 0 | github-code | 1 |
16557318705 | # https://www.acmicpc.net/problem/1248
# Solved Date: 20.04.17.
import sys
read = sys.stdin.readline
def check(index, arr, ans):
acc = 0
for i in range(index, -1, -1):
sign = arr[i][index]
acc += ans[i]
if sign == 1 and acc <= 0:
return False
elif sign == -1 and ac... | imn00133/algorithm | BaekJoonOnlineJudge/CodePlus/500BruteForce/Recursion/baekjoon_1248.py | baekjoon_1248.py | py | 1,528 | python | en | code | 0 | github-code | 1 |
42813125484 | import os
import openai
os.chdir('C:\\git\\powershell-labs\\openai')
openai.api_key = open('pykey.txt').read()
question = "List the 3 most populated US states with population, and abbreviation, output in json format"
aimodel = "text-davinci-003"
os.system('cls')
print('Submitting request to openai...')
response = o... | Skatterbrainz/notebooks | ps-openai/openaisample.py | openaisample.py | py | 436 | python | en | code | 0 | github-code | 1 |
72220113633 | #!/usr/bin/python3
import sys
import numpy as np
import pandas as pd
np.random.seed(1)
full_labels = pd.read_csv('annotations/labels.csv')
grouped = full_labels.groupby('filename')
gb = full_labels.groupby('filename')
grouped_list = [gb.get_group(x) for x in gb.groups]
train_index = np.random.choice(len(grouped_lis... | brianegge/garbage_bin | scripts/split_labels.py | split_labels.py | py | 748 | python | en | code | 4 | github-code | 1 |
74391663074 | # -*- coding: utf-8 -*-
"""
主程式檔
"""
from fastapi import FastAPI, status, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from utils.app import router
from utils.config import config, WebLogger
API = config['... | hello02923/Shop_project | shop/main.py | main.py | py | 2,402 | python | en | code | 0 | github-code | 1 |
27862605917 | import os
def make_app_folder(app_name: str) -> None:
"""
creates project folder system
:param app_name: str name of heroku application
:return: None
"""
os.mkdir(app_name)
def make_procfile(app_name: str) -> None:
"""
creates Procfile to tell Heroku what files to run
:param ap... | danielschutz/streamlit-heroku | src/streamlit_heroku/main.py | main.py | py | 1,903 | python | en | code | 2 | github-code | 1 |
7788844145 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 4 09:52:50 2019
@author: Aashish Ravindran
"""
def file_read(file):
"""
Reads a file and returns a dictionaary containgin run No and seqNo received for each run
"""
#Receiver Level
line=file.readlines()
count=0;
dict={}... | aashishravindran/PacketLossAnalysis | global_functions.py | global_functions.py | py | 7,379 | python | en | code | 0 | github-code | 1 |
42240524012 | from django.contrib import admin
from django.urls import path
from . import views
app_name = "assistance_app"
urlpatterns = [
path(
'',
views.MainView.as_view(),
name='main'
),
path(
'listar-asistencias/',
views.ListAllAssistances.as_view(),
name='assistance... | Rogrback/Control-asistencia | applications/assistance/urls.py | urls.py | py | 685 | python | en | code | 1 | github-code | 1 |
74143119072 | from flask import Flask, render_template, request, redirect, url_for
from bson import ObjectId
from pymongo import MongoClient
import os
from datetime import datetime
app = Flask(__name__)
client = MongoClient("mongodb://127.0.0.1:27017")
db = client.HelpAustralia
donations = db.donations
goal=70000
@app.route("/")
... | BeaverJulia/HelpAustralia | app.py | app.py | py | 1,759 | python | en | code | 0 | github-code | 1 |
72369704674 | class TicTacToe:
def __init__(self):
self.board = [[
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
], [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
]]
self.turn = 0
self.plays = []
def __str__(self) -> str:
result = []
for rowIndex in range(3):
row = []
for colIn... | levidyrek/tic-tac-toe-ai | src/tic_tac_toe.py | tic_tac_toe.py | py | 2,796 | python | en | code | 0 | github-code | 1 |
15160391023 | import os
from ssr.utility.logging_extension import logger
class PathManager:
def __init__(
self,
pan_ntf_idp,
msi_ntf_idp,
rgb_tif_idp,
vissat_workspace_dp,
ssr_workspace_dp,
):
self.vissat_workspace_dp = vissat_workspace_dp
self.pan_ntf_idp = ... | SBCV/SatelliteSurfaceReconstruction | ssr/path_manager.py | path_manager.py | py | 5,633 | python | en | code | 75 | github-code | 1 |
11929972635 | import os
from flask import Flask, Blueprint, request
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, hash_password
from flask_security.models import fsqla_v2 as fsqla
from flask_migrate import Migrate
from flask_bootstrap import Bootstr... | edwinlock/csef | webapp/__init__.py | __init__.py | py | 4,326 | python | en | code | 1 | github-code | 1 |
19819016338 | import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread("imagens/eu.jpg", 0)
img1 = cv.imread("imagens/eu.jpg", 0)
linhas, colunas = img1.shape
matriz = np.float32([(1, 0, 50),[0, 1, 100]])
deslocada = cv.warpAffine(img1, matriz, (linhas, colunas))
mes = cv.addWeighted(img, 0.1, img... | vitormnoel/opencv | visao-comp/mesclar.py | mesclar.py | py | 409 | python | en | code | 0 | github-code | 1 |
2702333822 | # Given a target amount n and a list of distinct coin values, what's the fewest coins needed
# to make the change amount
import sys, time
def rec_coin(target, coins):
coins.sort()
result = 0
if target in coins:
return 1
for i in coins:
temp = target
if i < target:
tem... | maitrinhdnc/DSA-PYTHON-CODES | Recursion /17_coin-change.py | 17_coin-change.py | py | 1,158 | python | en | code | 0 | github-code | 1 |
23174708021 | '''You are given a string S and width w.
Your task is to wrap the string into a paragraph of width w.
Input Format
The first line contains a string, S.
The second line contains the width, w.
Sample Input
ABCDEFGHIJKLIMNOQRSTUVWXYZ
4
Sample Output
ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ
'''
import textwrap
def wrap(stri... | 7Aishwarya/HakerRank-Solutions | Python/text_wrap.py | text_wrap.py | py | 565 | python | en | code | 6 | github-code | 1 |
31001236125 | import pandas as pd
import numpy as np
import time
import networkx as nx
import ast
from iteration_utilities import unique_everseen, duplicates
import operator
###################DataFrame:#####################################
#Read .CSV File that contains networks of all KCore bots between a sequence of bots. Each ro... | sai6kiran/TwitterBotFarms | kCoreBots/CoreBotEN/MachineLearning/NaiveBayes/CoreBotsSentiment/PythonScripts/KCoreBotStatistics.py | KCoreBotStatistics.py | py | 9,193 | python | en | code | 0 | github-code | 1 |
10291321382 | import requests
from bs4 import BeautifulSoup
URL = "https://online-samsung.ru/catalog/smartfony/"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
post = soup.find("div","commerce-order-item-add-to-cart-form-commerce-product-39672 commerce-order-item-add-to-cart-form" )
#post_id... | tester214pro/botdocker | mParser.py | mParser.py | py | 645 | python | en | code | 0 | github-code | 1 |
11207917458 | """Analyze log files produced by launch-task"""
import argparse
import datetime
import re
import sys
from collections import namedtuple
from edx.analytics.tasks.tools.analyze.measure import Measurement
from edx.analytics.tasks.tools.analyze.parser import LogFileParser
from edx.analytics.tasks.tools.analyze.report imp... | openedx/edx-analytics-pipeline | edx/analytics/tasks/tools/analyze/main.py | main.py | py | 9,334 | python | en | code | 90 | github-code | 1 |
34380053666 | """
Module with A* algorithm
Classes:
A_star
"""
import math
from queue import PriorityQueue
from agent import Agent
from world import World
class A_Star:
@staticmethod
def run_algorithm(agent: Agent, world: World) -> list[tuple]:
"""
Performs A* algorithm in given instance of
:pa... | BartekWrzalski/Maze_Q-learning | a_star.py | a_star.py | py | 2,840 | python | en | code | 0 | github-code | 1 |
6494276087 | n, m = map(int, input().split())
dna = []
for _ in range(n):
dna.append(list(input()))
d = []
for i in range(m):
dict = {}
for j in range(n):
if dna[j][i] in dict.keys():
dict[dna[j][i]] += 1
else:
dict[dna[j][i]] = 1
d.append(dict)
answer =... | JoonseoKang/coding_test | 백준/Silver/1969. DNA/DNA.py | DNA.py | py | 520 | python | en | code | 0 | github-code | 1 |
5500052090 |
# =======================================================APi Connection ==================================================================
# installation
#pip install --upgrade google-api-python-client
# build the instance with API Key
from googleapiclient.discovery import build
def Api_connec... | Moha-cm/Youtube-Dataharvesting- | API_connection.py | API_connection.py | py | 1,421 | python | en | code | 0 | github-code | 1 |
25433621989 | # 시간복잡도
# O(n+m)
import sys
input = sys.stdin.readline
n,m,k = map(int,input().split())
pre = [int(input()) for _ in range(n)]
aft = [int(input()) for _ in range(m)]
a_idx, b_idx = 0, 0
load, cost = 0, 0
while a_idx < n and b_idx < m:
if pre[a_idx] == 0:
a_idx += 1
continue
el... | reddevilmidzy/baekjoonsolve | 백준/Silver/2134. 창고 이전/창고 이전.py | 창고 이전.py | py | 908 | python | en | code | 3 | github-code | 1 |
37237546341 | import numpy as np
def fasta2one_hot(sequence, total_win_len):
"""
This converts a fasta sequences (in nucleotides) to one-hot representation
this was modificated with an exception to handle the no A,C,G,T,N letter and
transforme it to N
"""
langu = ['A', 'C', 'G', 'T',... | simonorozcoarias/YORO | utils/onehotProcessing.py | onehotProcessing.py | py | 615 | python | en | code | 1 | github-code | 1 |
40803566449 | from gensim.test.utils import datapath, get_tmpfile
from gensim.models import KeyedVectors
glove_file = datapath('/home/mathuryash5/7th Sem/Web Technologies - II/QuizUp/trained_model/glove.6B.50d.txt')
tmp_file = get_tmpfile("word2vec_50d.txt")
# calling glove2word2vec script
from gensim.scripts.glove2word2vec import ... | mukundsood1996/QuizUp | get_similar_categories.py | get_similar_categories.py | py | 640 | python | en | code | 0 | github-code | 1 |
70888302755 | # -*- coding: utf-8 -*-
# 노드의 개수 n, 간선에 대한 정보가 담긴 2차원 배열 vertex가 매개변수로 주어질 때,
# 1번 노드로부터 가장 멀리 떨어진 노드가 몇 개인지를 return 하도록 solution 함수를 작성해주세요.
from collections import deque
import copy
# bfs 알고리즘을 통해 노드 1로 부터 각 노드 사이의 최단 거리를 구한다.
def bfs(edge,n):
myqueue = deque([])
check_dict = {}
check = [0] * (n+1)
... | rhkddud3917/Algorithm-Practice | Programmers/level3/프로그래머스-level3-가장 먼 노드.py | 프로그래머스-level3-가장 먼 노드.py | py | 1,636 | python | ko | code | 0 | github-code | 1 |
34387827768 | import uci.Ptcls as Ptcls
import numpy as np
def test_compute_kinetic_energies():
vx = np.array([0.1, 0.2])
vy = np.array([10.1, 0.3])
vz = np.array([23.4, 42.5])
m = np.array([2.3, 3.4])
kinetic_energies = Ptcls.compute_kinetic_energies(vx, vy, vz, m)
for i in range(2):
assert abs(kine... | Tech-XCorp/ultracold-ions | test/test_Ptcls.py | test_Ptcls.py | py | 822 | python | en | code | 2 | github-code | 1 |
306549963 | #!/usr/bin/env python
import sys, os
import cnavgpost.mergehistories.event_cycles_module as histseg
from cnavgpost.mergehistories.history_node_links_module import *
import cPickle as pickle
def add_event_link_options(parser):
parser.add_argument('--cnavg', help='the CN-AVG output directory for a sample')
parser.... | dzerbino/cn-avg | paper_figures/cnavgpost/mergehistories/score_and_link_cycles.py | score_and_link_cycles.py | py | 3,210 | python | en | code | 3 | github-code | 1 |
25087252294 | #дан массив чисел,если число встречается хоть один раз,то добавить его в новый массив
import random
arr = [random.randint(1_10) for i in range(100)]
arr2 = []
for i in arr1:
if arr1.count(1) >= 2:
arr2.append(1)
print(arr1)
print(arr2) | dima191091/My-project | массив д/з.py | з.py | py | 320 | python | ru | code | 0 | github-code | 1 |
72663773474 | """
routines for creating the tree structures to be
uploaded to the api from the outputs of the
cohort_analysis methods
"""
from nest_py.core.jobs.checkpoint import CheckpointTimer
from nest_py.core.jobs.jobs_logger import log
import nest_py.core.data_types.tablelike_entry as tablelike_entry
import nest_py.omix.data_... | KnowEnG/platform | nest_py/omix/jobs/cohort_tree_etl.py | cohort_tree_etl.py | py | 5,500 | python | en | code | 2 | github-code | 1 |
14376985012 | from argparse import ArgumentParser
from datetime import datetime
from os import remove
from os.path import join
import joblib
import numpy
from mpi4py import MPI
from scipy.stats import kendalltau, spearmanr
# Local packages
try:
import RARinterpret
except ModuleNotFoundError:
import sys
sys.path.append(... | Richard-Sti/RARinterpret | scripts/run_pc.py | run_pc.py | py | 3,833 | python | en | code | 1 | github-code | 1 |
17726346978 | from PyQt5.QtCore import QUrl, QObject, pyqtSlot
from PyQt5.QtWebEngineWidgets import QWebEngineView as QWebView
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QVBoxLayout
import threading
import logging
import time
import os
import ui.utils
class Applicatio... | EtienneDesticourt/MakuraReader | ui/application.py | application.py | py | 4,423 | python | en | code | 0 | github-code | 1 |
30686629861 | # Part 2
dots = set()
folds = []
with open("input13") as f:
for line in f:
if line == "\n":
continue
if line[0] == "f":
fold = line.strip().split()[2].split("=")
folds.append([fold[0], int(fold[1])])
else:
dots.add(tuple(map(int, line.strip()... | jlgridley/AdventOfCode2021 | Day13/13.py | 13.py | py | 2,078 | python | en | code | 0 | github-code | 1 |
17815017352 | import json
import random
import re
from services.services import is_subscribed, is_admin
from vk_session import vk_session
def get_button(button):
return {
"action": {
"type": "text",
"payload": "{\"button\": \""+ "1" + "\"}",
"label": str(button['text'])
},
... | chrnk-exe/GoodMorningBot | bot/lib.py | lib.py | py | 2,928 | python | en | code | 1 | github-code | 1 |
24209042617 | ##############################################
# Stefan Grulović (20150280) - Project part A
# 10/6/2019
# Part A is to build a program which can read a file
# that contains Formula 1 racing results and then filter,
# search and or calculate statistics from the data.
##############################################
# Li... | Grulovic/Phyton | Part A - F1.py | Part A - F1.py | py | 13,308 | python | en | code | 0 | github-code | 1 |
45532933544 | from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
from django.core import serializers
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from . import models
clas... | watsonjiang/apihub | admin/views.py | views.py | py | 2,956 | python | en | code | 0 | github-code | 1 |
43135793844 | import torch
from ...util import torch_dtype_from_str
def map_controlnet(pt_mod, dim=320, device="cuda", dtype="float16"):
if not isinstance(pt_mod, dict):
pt_params = dict(pt_mod.named_parameters())
else:
pt_params = pt_mod
params_ait = {}
for key, arr in pt_params.items():
ar... | FizzleDorf/AIT | AITemplate/ait/util/mapping/controlnet.py | controlnet.py | py | 1,304 | python | en | code | 49 | github-code | 1 |
42767390194 | import cv2
import depthai as dai
import numpy as np
def getMonoCamera(pipeline, side):
mono = pipeline.createMonoCamera()
mono.setResolution(dai.MonoCameraProperties.SensorResolution.THE_720_P)
if side == 'LEFT':
mono.setBoardSocket(dai.CameraBoardSocket.LEFT)
else:
mono.setBoardSocket(... | mahi-ma/CameraCalibration | depth_capture_mono.py | depth_capture_mono.py | py | 1,588 | python | en | code | 1 | github-code | 1 |
38069302412 | from ..repository.models import *
from ..extensions import db
from ..utils import get_current_time, build_cpt_path
from gi.repository import Limba
from gi.repository import AppStream
import os
import glob
import shutil
import gzip
def safe_move_file(old_fname, new_fname):
if not os.path.isfile(old_fname):
... | limbahq/limba-hub | lihub/maintain/update_indices.py | update_indices.py | py | 2,220 | python | en | code | 2 | github-code | 1 |
70735318754 | import os
import glob
import random
import monai
from os import makedirs
from os.path import join
from tqdm import tqdm
from time import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from datetime import datetime
from segment_anyt... | bowang-lab/MedSAM | extensions/point_prompt/train_point_prompt.py | train_point_prompt.py | py | 10,100 | python | en | code | 1,269 | github-code | 1 |
13734513309 | from typing import List
from django.conf import settings
from twirp.context import Context
from twirp.exceptions import TwirpServerException
from base.models import Lexicon
from lib.domain import Questions
from lib.wdb_interface.constants import TIMEOUT
from lib.wdb_interface.exceptions import WDBError
from lib.wdb_i... | domino14/Webolith | djAerolith/lib/wdb_interface/wdb_helper.py | wdb_helper.py | py | 3,006 | python | en | code | 32 | github-code | 1 |
6123989613 | from manimlib.imports import *
from scipy.optimize import curve_fit
def yx2features(ran=[0, 5], number=100):
def func(): return ((max(ran) - min(ran) + 1) * np.random.random(number)) + min(ran)
x1 = np.array(func)
x2 = np.array(list(map(lambda z: int(z), func())))
y = np.array([1 if x1[i] > x2[i] els... | vivek3141/videos | mario.py | mario.py | py | 13,778 | python | en | code | 132 | github-code | 1 |
31110702904 | ## ##################################################
import csv
import numpy as np
## import scipy.io
## import pickle
import scipy.stats
import os
## import scipy.linalg as sp_linalg
import mvm_mmmvr_lib.mvm_prepare as mvm_prepare
## import tensor_decomp
## ###################################################
## ###... | KCL-Planning/rosplan_prediction | squirrel_relations_prediction/scripts/mvm_mmmvr_lib/load_data.py | load_data.py | py | 15,796 | python | en | code | 2 | github-code | 1 |
16964224154 | """add mark_flag to mailbox
Revision ID: afb03fbe983d
Revises: 6333dc7ec84b
Create Date: 2020-11-14 15:29:00.221551-05:00
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'afb03fbe983d'
down_revision = '6333dc7ec84b'
branch_labels = None
depends_on = None
def ... | DaniilKurlovich/slowmail | backend/app/alembic/versions/afb03fbe983d_add_mark_flag_to_mailbox.py | afb03fbe983d_add_mark_flag_to_mailbox.py | py | 498 | python | en | code | 0 | github-code | 1 |
6584264656 | from typing import Optional, TYPE_CHECKING
from UM.Logger import Logger
import cura.CuraApplication # Imported this way to prevent circular references.
from cura.Machines.ContainerTree import ContainerTree
from cura.Machines.Models.QualityProfilesDropDownMenuModel import QualityProfilesDropDownMenuModel
if TYPE_CHE... | Ultimaker/Cura | cura/Machines/Models/CustomQualityProfilesDropDownMenuModel.py | CustomQualityProfilesDropDownMenuModel.py | py | 2,255 | python | en | code | 5,387 | github-code | 1 |
42629944723 | from flask import Flask, render_template, request
from flask_debugtoolbar import DebugToolbarExtension
from stories import all_stories
app = Flask(__name__)
app.config["SECRET_KEY"] = "mad libs"
debug = DebugToolbarExtension(app)
@app.route('/')
def index():
return render_template("selection.html", stories = all_... | wendybujalski/springboard-exercises | 19.2.12/app.py | app.py | py | 729 | python | en | code | 0 | github-code | 1 |
23395554336 | '''
Author: Michael Sherif Naguib
Date: May 7, 2019
@: University of Tulsa
Question #20:
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the numbe... | Michael-Naguib/ProjectEuler | 20.py | 20.py | py | 784 | python | en | code | 0 | github-code | 1 |
6864807449 | def malus_calc(student_data,activity_list):
malus_student = 0
for student_individual in student_data:
malus_student += student_individual.malus_calc()
malus_activity = 0
for activity in activity_list:
if activity.time.night == True:
malus_activity += 5
malus_total = ... | DutchProg/Roostermakers | __Main/malus_calc.py | malus_calc.py | py | 378 | python | en | code | 0 | github-code | 1 |
10442491312 | # tee ratkaisu tänne
def pisimmat(my_list):
longest = 0
newList = []
for i in my_list:
if len(i) > longest:
longest = len(i)
for i in my_list:
if len(i) == longest:
newList.append(i)
return newList
if __name__ == "__main__":
my_list = ["adele", "mark... | dnnijmlinn/Python-mooc-2021 | osa04-19_listan_pisimmat/src/listan_pisimmat.py | listan_pisimmat.py | py | 410 | python | en | code | 1 | github-code | 1 |
71276363875 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 25 10:42:17 2019
@author: Colton Smith
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metr... | coltonfsmith/BlogProjects | pima_analysis.py | pima_analysis.py | py | 2,898 | python | en | code | 19 | github-code | 1 |
7833199559 | """Definition of DAFs."""
from __future__ import annotations
from functools import reduce
import field
from common import Bool, Unsigned, gen_rand
from xof import XofTurboShake128
class Daf:
"""A DAF"""
# Algorithm identifier for this DAF, a 32-bit integer.
ID: Unsigned = None
# The number of Agg... | cfrg/draft-irtf-cfrg-vdaf | poc/daf.py | daf.py | py | 6,619 | python | en | code | 14 | github-code | 1 |
35442528263 | # build out the loop
from time import sleep
import re
from random import randint # avoid throttling by not sending too many requests one after the other
from warnings import warn
from time import time
from IPython.core.display import clear_output
import numpy as np
# find the total number of posts to find th... | Maincakes/Craigslist_Housing_Scraper | Test.py | Test.py | py | 1,668 | python | en | code | 0 | github-code | 1 |
19495834349 | from aubio import source, tempo
import numpy as np
def get_file_bpm(path, params=None):
""" Calculate the beats per minute (bpm) of a given file.
path: path to the file
param: dictionary of parameters
"""
if params is None:
params = {}
# default:
samplerate, win_s, hop_s = 44100, 1024, 512
if 'mode' in par... | Miking98/piano-sheet-music | test.py | test.py | py | 1,647 | python | en | code | 9 | github-code | 1 |
74358224674 | import logging
from typing import Union
from pydantic import BaseModel
from wikibaseintegrator import wbi_config
from wikibaseintegrator.wbi_helpers import execute_sparql_query
import config
from helpers import console
from models.enums import Return
from models.wikicitations_wikibase import WikiCitationsWikibase
lo... | dpriskorn/wikicitations-api | models/lookup_wikicitations_qid.py | lookup_wikicitations_qid.py | py | 3,837 | python | en | code | 1 | github-code | 1 |
12600180751 | '''
title : blockchain.py
description : A blockchain implemenation
author : Adil Moujahid
date_created : 20180212
date_modified : 20180309
version : 0.5
usage : python blockchain.py
python blockchain.py -p 5000
python blockchain.... | adilmoujahid/blockchain-python-tutorial | blockchain/blockchain.py | blockchain.py | py | 11,355 | python | en | code | 617 | github-code | 1 |
3808295127 | #!/usr/bin/env python3
import rospy
from duckietown_msgs.msg import DroneControl
from duckietown.dtros import DTParam, DTROS, NodeType, ParamType
class FlyCommandsMuxNode(DTROS):
def __init__(self, node_name):
# Initialize the DTROS parent class
super(FlyCommandsMuxNode, self).__init__(node_name... | duckietown/dt-drone-interface | packages/fly_commands_mux/src/fly_commands_mux_node.py | fly_commands_mux_node.py | py | 3,647 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.