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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
15130917408 | # %%
from pprint import pprint
from datasets import load_dataset
test_file = "../data/ekonspacing/test_small.txt"
val_file = "../data/ekonspacing/val_small.txt"
train_file = "../data/ekonspacing/train_small.txt"
# %%
dataset = load_dataset(
"ekonspacing.py",
name="small",
data_files={"train": str(train_f... | entelecheia/transformer-datasets | datasets/ekonspacing/ekonspacing_test.py | ekonspacing_test.py | py | 500 | python | en | code | 0 | github-code | 36 |
17079442964 | import logging
from .html import extract_html_text
from .pdf import extract_pdf_text
logger = logging.getLogger(__name__)
def extract_text(file_path: str) -> str:
"""Extract text from any kind of file as long as it's html or pdf"""
try:
if file_path.endswith('.html'):
return extract_htm... | amy-langley/tracking-trans-hate-bills | lib/util/misc.py | misc.py | py | 691 | python | en | code | 2 | github-code | 36 |
22926496902 | import cv2
import math
# Source: https://richardpricejones.medium.com/drawing-a-rectangle-with-a-angle-using-opencv-c9284eae3380
# Made slight adjustments to color
def draw_angled_rec(x0, y0, width, height, angle, img, color):
_angle = angle * math.pi / 180.0
b = math.cos(_angle) * 0.5
a = math.sin(_angl... | MatanPazi/opt_fabric_layout | minAreaRect_Test.py | minAreaRect_Test.py | py | 2,974 | python | en | code | 1 | github-code | 36 |
13987393028 | from sys import maxsize as maxint
class Solution:
def minSubArrayLen(self, s, nums):
cs = 0
start = 0
min_len = maxint
for end in range(len(nums)):
cs += nums[end]
while cs >= s and start <= end:
min_len = min(min_len, end - start + 1)
... | dariomx/topcoder-srm | leetcode/first-pass/facebook/minimum-size-subarray-sum/Solution.py | Solution.py | py | 485 | python | en | code | 0 | github-code | 36 |
521538009 | #imports
import numpy as np
import matplotlib.pyplot as plt
import scipy.constants as const
from scipy.special import iv as I0
from scipy.special import kv as K0
#Define Global Variables
L_geo = 55.6e-9
Z0 = 50.0
F0_base = 0.95e9 #At lowest Temp
squares= 27223
c_couple = 1.5e-14
TC = 1.5
Delta_0 = (3.5*const.Bo... | Ashleyyyt/Characterizing-KIDs | Simulate KID.py | Simulate KID.py | py | 7,177 | python | en | code | 0 | github-code | 36 |
29290663147 | from django.db import models
from wagtail.admin.edit_handlers import MultiFieldPanel, RichTextFieldPanel, StreamFieldPanel
from wagtail.core.fields import RichTextField, StreamField
from wagtail.snippets.models import register_snippet
from ..modules import text_processing
from .. import configurations
from ..blogs.blo... | VahediRepositories/AllDota | dotahub/home/blogs/models.py | models.py | py | 1,626 | python | en | code | 0 | github-code | 36 |
7182836122 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: José Sánchez-Gallego (gallegoj@uw.edu)
# @Date: 2023-01-19
# @Filename: test_callback.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
import unittest.mock
import click
from click.testing import CliRunner
from unclick.core import... | albireox/unclick | tests/test_callback.py | test_callback.py | py | 1,732 | python | en | code | 0 | github-code | 36 |
22502725218 | # -*- coding: utf-8 -*-
__docformat__ = "restructuredtext en"
"""
the PLUGIN extend
File: app_plugin_ext.py
Copyright: Blink AG
Author: Steffen Kube <steffen@blink-dx.com>
"""
from blinkdms.code.lib.oTASK import oTASK
from blinkdms.code.lib.main_imports import *
from blinkdms.code.lib.obj imp... | qbicode/blinkdms | blinkdms/code/lib/app_plugin_ext.py | app_plugin_ext.py | py | 2,218 | python | en | code | 0 | github-code | 36 |
27549684390 | """
Query builder examples.
NOTES:
# Infix notation (natural to humans)
NOT ((FROM='11' OR TO="22" OR TEXT="33") AND CC="44" AND BCC="55")
# Prefix notation (Polish notation, IMAP version)
NOT (((OR OR FROM "11" TO "22" TEXT "33") CC "44" BCC "55"))
# Python query builder
NOT(AND(OR(from_='11', to='22', t... | ikvk/imap_tools | examples/search.py | search.py | py | 2,613 | python | en | code | 608 | github-code | 36 |
17232377687 | import numpy as np
import json
import CMS_lumi
import os
import copy
import ROOT
def main():
#work_dir = "."
#plots_dir = "."
ROOT.gROOT.SetBatch()
ROOT.gStyle.SetOptStat(0000)
ROOT.gStyle.SetPalette(ROOT.kVisibleSpectrum)
file_obs = ROOT.TFile("higgsCombineTest.GoodnessOfFit.mH1... | vshang/Limits | plot_gof.py | plot_gof.py | py | 3,697 | python | en | code | 0 | github-code | 36 |
15857685473 | # -*- coding: utf-8 -*-
import os
import sys
import webbrowser
from invoke import task
docs_dir = 'docs'
build_dir = os.path.join(docs_dir, '_build')
@task
def readme(ctx, browse=False):
ctx.run("rst2html.py README.rst > README.html")
if browse:
webbrowser.open_new_tab('README.html')
def build_doc... | CenterForOpenScience/COSDev | tasks.py | tasks.py | py | 1,383 | python | en | code | 6 | github-code | 36 |
6942705198 | '''
Complete the following 3 searching problems using techniques
from class and from Ch15 of the textbook website
'''
#1. (7pts) Write code which finds and prints the longest
# word in the provided dictionary. If there are more
# than one longest word, print them all.
import re
def split_line(line):
#this functi... | ParkerCS/ch15-searches-sdemirjian | ch15ProblemSet.py | ch15ProblemSet.py | py | 2,450 | python | en | code | 0 | github-code | 36 |
9866560419 | from mlagents_envs.environment import UnityEnvironment
from mlagents_envs.environment import ActionTuple
from mlagents_envs.side_channel.engine_configuration_channel import EngineConfigurationChannel
import numpy as np
import mlagents.trainers
from collections import namedtuple
obs = namedtuple(
'obs',
... | chagmgang/baselines | baselines/env/simple_drone.py | simple_drone.py | py | 3,699 | python | en | code | 1 | github-code | 36 |
15006294998 | import pandas as pd
from bs4 import BeautifulSoup as bs
#Criando objeto BS
def get_file(file_name):
content = []
with open(file_name, 'r') as file:
content = file.readlines()
content = ''.join(content)
soup = bs(content,'xml')
return soup
#Buscando parents
def get_parents(soup):
... | jonesamandajones/powercenter | create_excel.py | create_excel.py | py | 3,991 | python | en | code | 0 | github-code | 36 |
35610933721 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
ret = []
if root == None : return ""
q = deque()
q.append(root)
while q :
k = len(q)
for i in ... | is-yusuf/Random-leetcoding- | Iterative serialize.py | Iterative serialize.py | py | 1,418 | python | en | code | 0 | github-code | 36 |
74160129703 | '''
Algorithm: just count how many characters(frequency more than one regard it as one)
'''
#!/bin/python3
import sys
from collections import Counter
def stringConstruction(s):
# Complete this function
return len(Counter(s).values())
if __name__ == "__main__":
q = int(input().strip())
for a0 in range(... | CodingProgrammer/HackerRank_Python | (Strings)String_Construction(Counter_FK1).py | (Strings)String_Construction(Counter_FK1).py | py | 413 | python | en | code | 0 | github-code | 36 |
947951498 | #!/home/shailja/.virtualenv/my_env/bin/python3
import requests
import bs4
import sys
content = sys.argv[1]
def display_actual_text(text,para_no):
text = text[para_no]
[s.extract() for s in text(['style', 'script', '[document]', 'head', 'title'])]
visible_text = text.getText()
print(visible_text)
w... | SKT27182/web_scaping | wiki_search.py | wiki_search.py | py | 1,728 | python | en | code | 0 | github-code | 36 |
71592171944 | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import deque
# Complete the bfs function below.
def bfs(n, m, edges, s):
#Create adjacency list empty on array
neighbors = [[] for i in range(n) for j in range(1)]
#Include neighbors of each vertex, with index minus 1... | Gabospa/computer_science | bfs.py | bfs.py | py | 1,506 | python | en | code | 0 | github-code | 36 |
16931221429 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 24 23:39:39 2018
@author: yorklk
"""
import os
import numpy as np
from skimage.morphology import label
from keras.models import Model, load_model
from keras.layers import Input, Activation, Add, BatchNormalization
from keras.layers.core import Dro... | yorklk/dsb2018-U-Net | U-Net.py | U-Net.py | py | 13,208 | python | en | code | 0 | github-code | 36 |
13988415228 | # kinda lame, this was supposedly done in logarithmic time, though did not
# get totally rt the trick
class Solution:
def getNoZeroIntegers(self, n: int) -> List[int]:
for x in range(n - 1, 0, -1):
y = n - x
if '0' in str(x) or '0' in str(y):
continue
els... | dariomx/topcoder-srm | leetcode/trd-pass/easy/convert-integer-to-the-sum-of-two-no-zero-integers/convert-integer-to-the-sum-of-two-no-zero-integers.py | convert-integer-to-the-sum-of-two-no-zero-integers.py | py | 354 | python | en | code | 0 | github-code | 36 |
9157699619 | import argparse
from typing import List
import config
import mysql.connector
from collections import OrderedDict
from binance_data import BinanceData
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
def load(data: List['BinanceData']):
# db connection
# db batch insert new table
... | Sherry-W071/Real-time-Cryptocurrency-Data-Aggregation-and-Processing-Pipeline | transform_load.py | transform_load.py | py | 9,045 | python | en | code | 0 | github-code | 36 |
28886388336 | # from urllib import request
from django.shortcuts import render, redirect
from .models import Post, Comment
from .forms import CommentForm, PostUpdateForm
# from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
# LoginRequiredMixin is simply the class based version fo... | MSKose/django-blog-app | blog/views.py | views.py | py | 6,019 | python | en | code | 1 | github-code | 36 |
1693307394 | import numpy as np
import math
import cv2
center_points = {}
objects_bbs_ids = []
id_count = 0
vechical_count = 0
count = 0
person_id = 0
camera = cv2.VideoCapture("video.mp4")
object_detector = cv2.createBackgroundSubtractorMOG2(history = None, varThreshold = None)
kernelOp = np.ones((3,3), np.uint8)
kernelC1 = n... | Computer4062/Python-Projects | Road Tracker/counter.py | counter.py | py | 2,880 | python | en | code | 0 | github-code | 36 |
8293997114 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 17 13:44:46 2021
@author: bfeng1
"""
import json
import sys
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from scipy.signal import savgol_filter
from sklearn.utils import resample
from sklearn.metrics import a... | bfeng1/Jump-Classification-Project | aim2.py | aim2.py | py | 12,898 | python | en | code | 0 | github-code | 36 |
32830767547 | def get_data(inp_file_num):
"""
this function returns the data of the selected input file in desired format.
"""
f = open(f"{inp_file_num}.in", "r")
num_of_shifts = int(f.readline().strip())
lines = list(
line for line in (list(map(int, l.strip().split(" "))) for l in f) if line
)
... | apoorvamalhotra/MysteriousSafeguards | dsAssignment/assignment.py | assignment.py | py | 2,590 | python | en | code | 0 | github-code | 36 |
7305279610 | #!/usr/bin/env python
import rospy
import serial
import time
import sys
import math
from FOF_API.MOCAP.getrigidbody import NatNetClient
from geometry_msgs.msg import Pose
body = {}
class mocap_reader:
def __init__(self,clientAddress,serverAddress):
rospy.init_node('mocap_reader', anonymous=True, disable_si... | CoRotProject/FOF-API | Agents/UWB_agent/mocap_ros.py | mocap_ros.py | py | 6,365 | python | en | code | 0 | github-code | 36 |
1858113091 | import subprocess
import os
import simplejson
import base64
import socket
from util import kg
import time
import threading
import pyttsx3
from PIL import ImageGrab
import sys
import shutil
import cv2
from util import sound_record
import tkinter
ip = "192.168.1.105" #Change this value according to yours... | st4inl3s5/kizagan | kizaganEN.py | kizaganEN.py | py | 11,980 | python | en | code | 72 | github-code | 36 |
26610494943 | # This class implements the adaptive rank transformation used in classifier ANOVA_subset_ranking_lr
import sklearn.base as base
import scipy
import time
import logging
import torch
from utilities.optirank.ranking_multiplication import ranking_transformation
import numpy as np
import statsmodels.api as sm
from statsmod... | paolamalsot/optirank | utilities/ANOVA_subset_ranking.py | ANOVA_subset_ranking.py | py | 6,722 | python | en | code | 0 | github-code | 36 |
26451217511 | # Función para agregar un contacto a la lista
def agregar_contacto(nombre, telefono, lista_contactos):
nuevo_contacto = {"Nombre": nombre, "Teléfono": telefono}
lista_contactos.append(nuevo_contacto)
print(f"Contacto {nombre} agregado.")
# Función para eliminar un contacto de la lista
def eliminar_contacto... | mateotettamanti/gestioncontacts | main.py | main.py | py | 2,271 | python | es | code | 0 | github-code | 36 |
34450828117 | import pytest
from PyQt6.QtTest import QTest
from PyQt6.QtWidgets import QLineEdit
from pytestqt import qtbot
from main import OLXWork, OLXSettings
from PyQt6 import QtCore
def test_olxwork_button_stop_clicked(qtbot):
parent = OLXSettings()
widget = OLXWork(parent= parent)
widget.show()
qtbot.addWidg... | Kandel269/OLXroom | test_main.py | test_main.py | py | 3,676 | python | en | code | 0 | github-code | 36 |
8492180165 | print('\n\n****************************************')
''' Python Socket Objects: are just like files, you can read and write to them.
These are the entry point for sending and receiving data to a client.
Python -> Clients Job:
connect --> send --> receive
'''
print(' Example of a simple client:')
'''localhost is o... | ncterry/Python | Security_Basics/Sec_Send&Receive/Sec_Send&Receive.py | Sec_Send&Receive.py | py | 1,087 | python | en | code | 0 | github-code | 36 |
22330605569 | import asyncio
import logging
import os
import re
import warnings
from asyncio import Future
from functools import wraps
from inspect import signature
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
from tqdm.auto import tqdm
from rubrix._constants import (
DATASET_NAME_REGEX_PATTER... | Skumarh89/rubrix | src/rubrix/client/api.py | api.py | py | 24,714 | python | en | code | null | github-code | 36 |
71707177064 | import openai
import csv
import argparse
from collections import Counter
from typing import List
from data.discourse_connectors import discourse_connectors
# Ihr OpenAI GPT-3 API-Schlüssel
api_key = "[insert your API KEY here]"
def parse_arguments() -> argparse.Namespace:
"""CLI-Argumente parsen."""
parser = ... | SandroWick/gpt_discourseconnectives_counter | gpt_discourseconnectives_project.py | gpt_discourseconnectives_project.py | py | 4,623 | python | de | code | 0 | github-code | 36 |
19905228937 | import random
# Print board
def print_board(board):
print("+---+---+---+")
for i in range(3):
print("|", end=" ")
for j in range(3):
print(board[i * 3 + j], end=" | ")
print("\n+---+---+---+")
# Check who is the winner
def check_winner(board):
winning_combos = [(0, 1,... | kpeeva/tictactoe | game.py | game.py | py | 2,134 | python | en | code | 0 | github-code | 36 |
21394122423 | Denominations = {1:[2000,500,200,100,50,20,10,5,2,1],2:[100,50,20,10,5,2,1,0.50,0.25,0.10,0.05,0.01],3:[50,20,10,5,2,1,0.5,0.2,0.1,0.05,0.02,0.01],4:[10000,5000,2000,1000,500,100,50,10,5,1],5:[100,50,20,10,5,2,1,0.5,0.2,0.1,0.05,0.02,0.01]}
def checkval(s):
while(True):
value = input("--> Enter the amou... | ar0757/Change_giving_program | Change_Giver.py | Change_Giver.py | py | 5,856 | python | en | code | 0 | github-code | 36 |
9487574383 | import os, glob
from sqlalchemy import *
import sqlalchemy.exc
from sqlalchemy.orm import sessionmaker
from parse import *
from lxml import etree
from datetime import datetime, date, time
step_types = {
'given': 0,
'when': 1,
'then': 2
}
curpath = os.path.basename(os.getcwd())
if curpath == 'steps':
o... | AlexandrMov/sqlbehave | sqlbehave/testmodule.py | testmodule.py | py | 5,971 | python | en | code | 0 | github-code | 36 |
17743117135 | n = int(input())
cached = {}
def f(n):
if n in cached:
return cached[n]
if 0 <= n <= 1:
return 1
f_n = f(n-1) + f(n-2)
cached[n] = f_n
return f_n
print(f(n)) | baocogn/self-learning | big_o_coding/Green_06/day_9_quiz_8_FIBONACCI.py | day_9_quiz_8_FIBONACCI.py | py | 200 | python | en | code | 0 | github-code | 36 |
28067802602 | # 퐁당퐁당 안된다 선입후출 !
import sys
input = sys.stdin.readline
n = int(input())
count = 0
for _ in range(n) :
word = list(map(str, input()))
word.pop() # 맨뒤에 '/n'를 제거 위함
stack = []
for i in range(len(word)) :
if len(stack) == 0 :
stack.append(word[i])
else :
if word[... | hwanginbeom/algorithm_study | 1.algorithm_question/3.stack,queue/66.Stack_sejin.py | 66.Stack_sejin.py | py | 520 | python | en | code | 3 | github-code | 36 |
34162683454 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import tempfile
from subprocess import PIPE, Popen
import os
import random
import codecs
import math
from sklearn.pipeline import FeatureUnion
from sklearn.pipeline import Pipeline
from resources import SEMEVAL_SCORER_PATH
logger = logging.getLogger(__na... | daimrod/opinion-sentence-annotator | utils.py | utils.py | py | 7,027 | python | en | code | 0 | github-code | 36 |
21924375123 | #!/usr/bin/env python
import unittest
from network import Arc, Node, Network
class NetworkTestCase(unittest.TestCase):
def test_basic(self):
node = Node('one')
nw = Network([node])
self.assertEqual(nw.find_node('one'), node)
node = Node(('two', 2))
nw.add_node(node)
... | sh4rkfin/misc | python/network_test.py | network_test.py | py | 1,441 | python | en | code | 0 | github-code | 36 |
35742603936 | #!/usr/bin/env python3
import jetson.inference
import jetson.utils
import rospy
import os
import numpy as np
import cv2
import ctypes
from sensor_msgs.msg import Image, CameraInfo
from cv_bridge import CvBridge, CvBridgeError
class semanticSegmentation:
def __init__(self, topics_to, network, labels_file, camera_info... | ZiadGhanem/Adaptive-Cruise-Control-Application | graduation_project_pkgs/graduation_project_simulation/scripts/semantic_segmentation/semantic_segmentation.py | semantic_segmentation.py | py | 4,078 | python | en | code | 0 | github-code | 36 |
26946898269 | import numpy as np
import rogues
def dramadah(n, k=1):
"""
dramadah a (0,1) matrix whose inverse has large integer entries.
An anti-hadamard matrix a is a matrix with elements 0 or 1 for
which mu(a) := norm(inv(a),'fro') is maximal.
a = dramadah(n, k) is an n-by-n (0,1) matrix f... | macd/rogues | rogues/matrices/dramadah.py | dramadah.py | py | 1,919 | python | en | code | 16 | github-code | 36 |
35860493029 | import allure
from integration_template.forms.main_form import MainForm, TypeOfTesting
from tests.test_base import TestBase
class TestMainForm(TestBase):
main_form = MainForm()
def setup(self):
with allure.step("Go to main page"):
self.go_to_start_page()
with allure.step("Main p... | Polmik/py-selenium-auto-template | tests/main_form/test_main_form.py | test_main_form.py | py | 889 | python | en | code | 0 | github-code | 36 |
31868481915 | import CRUD
while True:
ListaTareas = CRUD.Leer()
print("\n---------------------------------------")
print("Aplicación CRUD")
print("1. Adicionar Tarea")
print("2. Consultar Tareas")
print("3. Actualizar Tarea")
print("4. Eliminar Tarea")
print("5. Salir")
opci... | deiividramirez/MisionTIC2022 | Ciclo 1 (Grupo 36)/Clases/ControladorCRUD.py | ControladorCRUD.py | py | 2,587 | python | es | code | 0 | github-code | 36 |
6254269803 | from __future__ import unicode_literals
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post, Tag
from .forms import PostAddForm
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required
def delete(request, post_id):
post = get_object_o... | Naoshin-hirano/blog_app | blog/blog_app/views.py | views.py | py | 2,376 | python | ja | code | 0 | github-code | 36 |
8126703324 | import random
# Choisi un mot
mots = []
with open("mots.txt") as fl:
for l in fl:
mots.append(l.rstrip("\n"))
mot = random.choice(mots)
# Variable cle
lettres = []
faux = 0
trouve = False
corps_plein = ["O", "/", "|", "\\", "/", "\\"]
corps = [" ", " ", " ", " ", " ", " "]
while not trouve:
trouve = ... | Salah78/pythonPendu | main.py | main.py | py | 1,175 | python | en | code | 1 | github-code | 36 |
41721739407 | # -*- coding:UTF-8 -*-
import numpy as np
import xlrd as xlrd
from scipy.stats import norm
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import sys
import importlib
# 参数1 Excel文件位置 参数2 选择要作图的表格 参数3、4、5 xy轴代表含义以及标题文字 参数6列数 函数可以选择某地址文件某一个表格某一列来操作
class Make_figure:
def result_pic(address, E... | 357734432/Supervised-Blockchain-Simulator | Data_Output/Make_figure.py | Make_figure.py | py | 1,617 | python | en | code | 0 | github-code | 36 |
42768275908 | # Module 5
# Programming Assignment 6
# Prob-3.py
# Robert Ballenger
from graphics import *
def main():
win = GraphWin(title="Shooty Shooty Bow Target", height=400, width=400)
# Little bit of shorthand, instead of writing "Point(200, 200)" for the middle of each circle, I just assigned it a vari... | CTEC-121-Spring-2020/mod-4-programming-assignment-Rmballenger | Prob-3/Prob-3.py | Prob-3.py | py | 1,336 | python | en | code | 0 | github-code | 36 |
21577757864 | from imath.Trainer import Trainer
import torch
import imath as pt
import os
import torch.nn as nn
import numpy as np
class VAETrainer(Trainer):
def __init__(self, optim, lant_dim, criterion, **kwargs):
super(VAETrainer, self).__init__(**kwargs)
self.lant_dim = lant_dim
self.Distribute =... | IMath123/imath | Trainer/VAETrainer.py | VAETrainer.py | py | 1,621 | python | en | code | 0 | github-code | 36 |
74850579945 | import sys
import time
import rospy
from array import array
from std_msgs.msg import String
import os
voicePublisher = rospy.Publisher('voiceOutput', String, queue_size=10)
def publishMessage(message):
voicePublisher.publish(message)
def listenNode(data):
print("callback " + data.data)
if data.data:... | LuizHenriqueP/ReadyFramework | readyVoiceOutput.py | readyVoiceOutput.py | py | 708 | python | en | code | 0 | github-code | 36 |
20406219922 | import os
import numpy as np
import tensorflow as tf
ROOT_DIR = os.path.abspath(__file__ + "/../../")
class BaseSpinFoam:
def __init__(self, spin_j, n_boundary_intertwiners, n_vertices):
self.n_boundary_intertwiners = n_boundary_intertwiners
self.n_vertices = n_vertices
self.spin_j = flo... | JosephRRB/GFlowNets_on_SpinFoams | core/environment.py | environment.py | py | 5,633 | python | en | code | 1 | github-code | 36 |
26419246863 | import cv2
import numpy as np
from functions import top_offset
class SceneMoments():
def __init__(self, sections_img, color, min_contour_size=1000, type_object="", offset=True, compl=False):
self.min_contour_size = min_contour_size
self.type_object = type_object
self.bw = np.all... | onmax/Robotics | scene-detection/detection/scene_moments.py | scene_moments.py | py | 3,808 | python | en | code | 0 | github-code | 36 |
74160109863 | cube = lambda x: x ** 3
def fibonacci(n):
result = []
i = 0
a, b = 0, 1
while i < n:
result.append(a)
a, b = b, a + b
i += 1
return result
print(list(map(cube, fibonacci(int(input()))))) | CodingProgrammer/HackerRank_Python | (Python Functionals)Map_and_Lambda_Function.py | (Python Functionals)Map_and_Lambda_Function.py | py | 232 | python | en | code | 0 | github-code | 36 |
71622209064 | import copy
import random
# # ---------------Input File & board dimension----------------/
input_txt = open("input15.txt", "r")
board_dimension = int(input_txt.readline())
board_area = [[0 for i in range(board_dimension)] for j in range(board_dimension)]
for i in range(0, board_dimension):
row = input_txt.readlin... | addyg/AI_Game_Algorithm | ai_program_v5.1.py | ai_program_v5.1.py | py | 11,434 | python | en | code | 2 | github-code | 36 |
6821308185 | import csv
import random
import math
import numpy as np
input = open('data_pool_rabel_sorted.csv', 'r', encoding='utf-8')
input_reader = csv.reader(input)
output = open('data_rabel_pool.csv', 'w', encoding='utf-8')
output_writer = csv.writer(output)
check = 0
num = 0
length = 0
curr = -1
ret = []
for l... | KyeongmoonKim/recognition_of_the_numeral_gesture | data3.py | data3.py | py | 1,030 | python | en | code | 0 | github-code | 36 |
6824189243 | import math
def primeCheck(num):
prime = math.sqrt(num)
for i in range(2,int(prime)) :
if num%i == 0:
return False
return True
def sol(N):
stack = []
for num in range(pow(10,N-1),pow(10,N)) :
if primeCheck(num) :
stack.append(num)
print(stack)
if __name__ == "__main__" :
N = int(input())
sol(N)
| yeonwook1993/algorithm_study | bfs_dfs/2023.py | 2023.py | py | 320 | python | en | code | 0 | github-code | 36 |
16515258502 | """
ARGUMENTS: python3 ParseMetaFilesUpdated.py <path-to-jstor-data> <which-part> <how-many-parts> <output-path>
<how-many-parts>: for parallel processing, this should be the number of workers available to run the program; 1 if not running in parallel.
<which-part>: for parallel processing, this should be a uni... | h2researchgroup/dictionary_methods | code/ParseMetaFilesUpdated.py | ParseMetaFilesUpdated.py | py | 5,612 | python | en | code | 0 | github-code | 36 |
16534298320 | import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
class VizHelp():
# Additional Usefull Display Methods
def plotPredictions(self, predictions, targets, decoder_steps, epochs, file_name, show=True):
stock_name = file_name.split('.')[0].upper()
if '/' in stock_name:
stoc... | rvariverpirate/TRN_StockPrediction | VisualizationHelpers.py | VisualizationHelpers.py | py | 1,429 | python | en | code | 0 | github-code | 36 |
16277554121 | import pygame
from constants import *
import numpy
class Board:
# Initializing the board with screen as an input
def __init__(self, screen) -> None:
self.screen = screen
self.game_array = numpy.zeros((WINDOW_SIZE // CUBE_SIZE, WINDOW_SIZE // CUBE_SIZE))
self.draw_board()
self.tu... | szczepanspl/tic_tac_toe | board.py | board.py | py | 5,668 | python | en | code | 0 | github-code | 36 |
43298614784 | from pypy.module.imp import importing
from pypy.module._file.interp_file import W_File
from rpython.rlib import streamio
from rpython.rlib.streamio import StreamErrors
from pypy.interpreter.error import oefmt
from pypy.interpreter.module import Module
from pypy.interpreter.gateway import unwrap_spec
from pypy.interpret... | mozillazg/pypy | pypy/module/imp/interp_imp.py | interp_imp.py | py | 6,658 | python | en | code | 430 | github-code | 36 |
37077548561 | #!/usr/bin/env python
# coding: utf-8
# 1. Write a Python Program to Find the Factorial of a Number?
# In[7]:
num=int(input("Ente the no to check its factorial"))
factorial=1
#check if no is negative
if num<0:
print("No foractor for negative no")
if num == 0:
print("Factorial of 0 is 1")
if num > 0:
for... | ralfsayyed/Inuron_programming_Assingments | Programming Assignment 4.py | Programming Assignment 4.py | py | 2,042 | python | en | code | 0 | github-code | 36 |
16772279994 | import urllib
import boto3
from botocore.exceptions import ClientError
ec2 = boto3.client("ec2")
def get_my_public_ip():
external_ip = urllib.request.urlopen(
'https://ident.me').read().decode('utf8')
print('Public ip - ', external_ip)
return external_ip
def create_key_pair(name):
try:
... | annatezelashvili/AWS_Python_Automation | Tasks/Task10-11/create_ec2.py | create_ec2.py | py | 3,423 | python | en | code | 0 | github-code | 36 |
35217252222 | from enum import IntEnum
import requests
from urllib.request import urlopen
import urllib
from selenium import webdriver
from bs4 import BeautifulSoup
import http.client
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.writer.excel import ExcelWriter
from openpyxl.cell.cell import ILLEGAL_... | Just-Doing/python-caiji | src/work/20210807/otcuncedu.py | otcuncedu.py | py | 3,301 | python | en | code | 1 | github-code | 36 |
71104422184 | #!/usr/bin/env python
# -*- coding=UTF-8 -*-
# Created at Mar 20 19:50 by BlahGeek@Gmail.com
import sys
if hasattr(sys, 'setdefaultencoding'):
sys.setdefaultencoding('UTF-8')
import logging
from datetime import datetime, timedelta
from treehole.renren import RenRen
import os
from treehole.models import ContentMod... | blahgeek/treehole | treehole/utils.py | utils.py | py | 2,317 | python | en | code | 30 | github-code | 36 |
6697035634 | from models.arch.network import Network
from torch.nn import functional as F
import torch
model = Network(stage=2, depth=8).cuda()
model.set_query_codebook()
model.load_state_dict(torch.load("./pretrained_models/LOLv1.pth"))
x = torch.ones(1, 3, 256, 256).cuda()
with torch.no_grad():
M = F.relu(x - mo... | TaoHuang95/RQ-LLIE | test.py | test.py | py | 1,359 | python | en | code | null | github-code | 36 |
4615311890 | from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name = "home"),
path('shop/', views.shop, name = "shop"),
path('about/', views.about, name = "about"),
path('contact/', views.contact, name = "contact"),
path('faq/', views.faq, name = "faq"),
] | brownlenox/djangostaticfiles | mainapp/urls.py | urls.py | py | 302 | python | en | code | 0 | github-code | 36 |
39647238473 |
from django.urls import path
from .views import newpost_add, post_list, post_detail, post_update,post_delete,about_page, post_like
urlpatterns = [
path('add', newpost_add, name='add'),
path('', post_list, name='list'),
path('detail/<int:id>', post_detail, name='detail'),
path('update/<int:id>', post_u... | yildirimesutx/Django_Blog_Project_102 | blog/urls.py | urls.py | py | 501 | python | en | code | 0 | github-code | 36 |
7795634258 | # -*- coding: utf-8 -*-
# Author: sunmengxin
# time: 10/17/18
# file: 图的遍历.py
# description:
'''
深度优先遍历和广度优先遍历
'''
# 递归遍历
def DFS(i,n,map,visit):
for j in range(n):
if map[i][j] == 1 and visit[j] == 0:
visit[j] = 1
print(j, end='\t')
DFS(j,n,map,visit)
return
... | 20130353/Leetcode | graph/图的遍历.py | 图的遍历.py | py | 1,615 | python | en | code | 2 | github-code | 36 |
29271028676 | from tank_class import Tank
import os
choice = 'Y'
while choice == 'Y':
os.system('clear')
player1 = input('Name of Player 1: ')
player2 = input('Name of Player 2: ')
player3 = input('Name of Player 3: ')
p1, p2, p3 = Tank(player1, 20, 50), Tank(player2, 20, 50), Tank(player3, 20, 50)
all_tanks ... | SubhamK108/Python-3 | Games/The Tank Game/tank_game.py | tank_game.py | py | 1,820 | python | en | code | 0 | github-code | 36 |
74090977062 | import math
from datetime import datetime
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
from firebase_admin import firestore
import parseIntervalFiles as pif
import parseActivityFiles as paf
hervdir = "C:\\Users\\Ju\\GDrive\\Projects\\HeRV\\"
## Firestore co... | jucc/HeRV_analysis | pipeline/convert_csv_firestore.py | convert_csv_firestore.py | py | 3,459 | python | en | code | 1 | github-code | 36 |
17176681083 | import os
import logging
from logging import handlers
from api.common.jsonFormatter import JsonFormatter
# json形式で出力するログファイル
class Api_logger_json():
def __init__(self, name):
super().__init__()
# ログ取得
self.log = logging.getLogger(name + "_json")
if not self.log.hasHandlers():
... | war-bonds-rx78/python_flask_db_sample | api/common/logger_json.py | logger_json.py | py | 1,381 | python | ja | code | 0 | github-code | 36 |
8402296505 | from argparse import ArgumentParser
import json, logging
import seeker.podSeeker as Seeker
import judge.simpleJudge as Judge
import updater.simpleUpdater as Updater
class installed_query_info():
def __init__(self, query_id, src_id, dst_id):
self.query_id = query_id
self.src_id = src_id
sel... | In-Net/NQATP | stimulator/easy_seeker.py | easy_seeker.py | py | 3,891 | python | en | code | 0 | github-code | 36 |
8458106104 | """Princess Peach is trapped in one of the four corners of a square grid. You are in the center of the grid and can move
one step at a time in any of the four directions. Can you rescue the princess?
Input format
The first line contains an odd integer N (3 <= N < 100) denoting the size of the grid. This is followed ... | namhoangle/coding-challenges | bot-save-princess.py | bot-save-princess.py | py | 3,972 | python | en | code | 0 | github-code | 36 |
6128705889 | import random
import unittest
from music21 import base # for _missingImport testing.
from music21 import repeat
from music21 import exceptions21
from music21 import corpus
from music21 import environment
_MOD = 'contour.py'
environLocal = environment.Environment(_MOD)
#-----------------------------------------------... | cuthbertLab/music21-tools | contour/contour.py | contour.py | py | 30,165 | python | en | code | 37 | github-code | 36 |
25952738898 | #encoding utf-8
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
import os
import re
def salvar_email():
path = 'E:/4 - ARQUIVO\PROJETOS\motor\email.xlsx'
arquivo_excel = load_workbook(path)
separados = arquivo_excel... | ricardocvel/buscarEmail_excel- | inteirarExcel.py | inteirarExcel.py | py | 2,400 | python | pt | code | 0 | github-code | 36 |
34729716556 | #!/usr/bin/python3
from twitter import *
import time
import json
with open('./conf.json') as file: conf = json.load(file)
tw = Twitter(auth=OAuth(conf['token'], conf['token_key'], conf['con_sec'], conf['con_sec_key']))
maxcount = 5000
friends = []
followers = []
res = tw.friends.ids(count=maxcount)
cursor = -1
while ... | jdxlabs/twitter_diff | remove_friendsonly.py | remove_friendsonly.py | py | 1,048 | python | en | code | 0 | github-code | 36 |
42350249999 | from flask import jsonify
from pyspark.sql import SparkSession
import matplotlib.pyplot as plt
import pandas as pd
import io
spark = SparkSession \
.builder \
.appName("Tweets Analysis using Python Saprk") \
.getOrCreate()
# spark is an existing SparkSession
df = spark.read.json("importedtweetsdata.json")
... | pujithasak/TweetsAnalysisPythonProject | AnalysisQuery4.py | AnalysisQuery4.py | py | 1,055 | python | en | code | 0 | github-code | 36 |
23411614254 | # -*- coding: utf-8 -*-
from aws_arns.srv.ecr import (
EcrRepository,
)
def test():
arn = "arn:aws:ecr:us-east-1:123456789012:repository/my-repo"
repo = EcrRepository.from_arn(arn)
uri = repo.uri
assert repo.repo_name == "my-repo"
assert EcrRepository.from_uri(uri) == repo
assert (
... | MacHu-GWU/aws_arns-project | tests/srv/test_ecr.py | test_ecr.py | py | 635 | python | en | code | 0 | github-code | 36 |
71075259305 | class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
def ksum(nums,target,k):
ans=[]
if len(nums)==0 or nums[0]*k>target or nums[-1]*k<target:
return ans
if k==2:
return twosum(nums,target)
for i i... | nango94213/Leetcode-solution | 18-4sum/18-4sum.py | 18-4sum.py | py | 1,216 | python | en | code | 2 | github-code | 36 |
42262216968 | import os
import math
import multiprocessing
from tqdm import tqdm
from argparse import Namespace
from typing import Iterable, Optional
mp = multiprocessing.get_context("spawn")
from utils import _create_model_training_folder
import torch
import torch.nn.functional as F
import torchvision
from torch.nn.parameter impo... | kaist-ina/TSPipe | benchmarks/byol/trainer.py | trainer.py | py | 13,650 | python | en | code | 6 | github-code | 36 |
30631149331 | """Python Program for cube sum of first n natural numbers
Print the sum of series 13 + 23 + 33 + 43 + …….+ n3 till n-th term.
Examples:
Input : n = 5
Output : 225
13 + 23 + 33 + 43 + 53 = 225
Input : n = 7
Output : 784
13 + 23 + 33 + 43 + 53 +
63 + 73 = 784"""
# #program1
# n = int(input("Enter t... | nishanthhollar/geeksforgeeks_python_basic_programs | basic_programs/cube_of_squares_of_natural_nos.py | cube_of_squares_of_natural_nos.py | py | 2,091 | python | en | code | 0 | github-code | 36 |
20528044643 | import pika
connection = pika.BlockingConnection( #建立连接
pika.ConnectionParameters(host='localhost')
)
channel = connection.channel() #声明一个管道
#声明QUEUE
channel.queue_declare(queue='hello2',durable=True)
channel.basic_publish(exchange='',
routing_key='hello2',
body='Hello World!',
properties... | chenyaqiao0505/Code111 | RabbitMQ/producter.py | producter.py | py | 572 | python | en | code | 0 | github-code | 36 |
26896963958 | #!/usr/bin/env python3
import sys
import time
import socket
import yaml
from dataclasses import asdict
import ipywidgets.widgets as widgets
from IPython.display import display
print(sys.executable)
from ecat_repl import ZmsgIO
from ecat_repl import FoeMaster
from ecat_repl import CtrlCmd
from ecat_repl import SdoCmd... | alessiomargan/Ecat-repl | ecat_repl/test/ecat_advr.py | ecat_advr.py | py | 1,873 | python | en | code | 0 | github-code | 36 |
37417551271 | import os
from os.path import join
import sys
import json
import numpy as np
# from .read_openpose import read_openpose
import utils.segms as segm_utils
def db_coco_extract(dataset_path, subset, out_path):
# convert joints to global order
joints_idx = [19, 20, 21, 22, 23, 9, 8, 10, 7, 11, 6, 3, 2, 4, 1, 5, 0]... | HongwenZhang/DaNet-DensePose2SMPL | datasets/preprocess/dp_coco.py | dp_coco.py | py | 5,303 | python | en | code | 208 | github-code | 36 |
3829108374 | # coding: utf-8
# 前端测试是否眨眼,用于活体检测 Front-end test blinks for biopsy
from scipy.spatial import distance as dist
from imutils import face_utils
import time
import dlib
import cv2
def eye_aspect_ratio(eye):
# 计算两只眼睛之间的垂直欧式距离
A = dist.euclidean(eye[1], eye[5])
B = dist.euclidean(eye[2], eye[4])
# 计算两眼之间的水... | HollowMan6/Lanck-Face-Recognition-Lock-Competition-Backend-Code | Development-Board/DetectBlinks.py | DetectBlinks.py | py | 4,286 | python | en | code | 22 | github-code | 36 |
41165135533 | # -*- coding: utf-8 -*-
'''
This file is part of Habitam.
Habitam is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Habitam is distr... | habitam/habitam-core | habitam/downloads/balance.py | balance.py | py | 6,509 | python | en | code | 1 | github-code | 36 |
35778628261 | from report import report_sxw
from osv import osv
import pooler
import time
from datetime import datetime
from dateutil.relativedelta import relativedelta
from tools.translate import _
class report_attendance_parser(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(report_attendance_... | aryaadiputra/addons60_ptgbu_2013 | ad_hr_report/report/attendance_report_parser_old.py | attendance_report_parser_old.py | py | 2,235 | python | en | code | 0 | github-code | 36 |
7158973131 | import os
import shutil
from pathlib import Path
from os import system
from shutil import rmtree
import shutil
mi_ruta = Path(Path.home(), '\Programacion-Cursos-Desarrollador\Python\Python-proyecto1\Dia7\Banco')
class Persona:
def __init__(self, nombre, apellido):
self.nombre = nombre
self.apelli... | Alexa-Silvermoon/curso-python-proyectos-udemy-federico | Dia7/ProyectoDelDia7 - mejorada cuenta bancaria.py | ProyectoDelDia7 - mejorada cuenta bancaria.py | py | 3,868 | python | es | code | 0 | github-code | 36 |
10022682639 | import os
import re
import openai
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.environ['OPENAI_API_KEY']
def request_chatgpt(messages: list):
return openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
)
def analyze_toots(mastodon_timelines: list) -> t... | mio256/mastardon | page/chatgpt_func.py | chatgpt_func.py | py | 1,302 | python | en | code | 1 | github-code | 36 |
25236999928 | def count_substrings(string1, string2):
''' Get the number of subsctrings in two strings
'''
answer = 0
for i in range(len(string1)):
result = ''
for j in range(i, len(string1)):
result += string1[j]
if string2.find(result) != -1:
answer += 1
r... | dukelester/geek_for_geek_DSA | strings_dsa.py | strings_dsa.py | py | 428 | python | en | code | 0 | github-code | 36 |
7863927981 | #!/usr/bin/env python3
names= ["thiago",
"joao",
"rafael",
"Rafaela",
"ronaldo",
"joana"]
## estilo funcional
print(*list(filter(lambda nome: nome[0].lower() == "r", names)),sep="\n")
print()
## estilo imperativo
def comeca_b(texto):
return texto[0].lower() == "r"
filtro=... | ThiagoRBM/python-base | composicao.py | composicao.py | py | 396 | python | pt | code | 0 | github-code | 36 |
2286638164 | from collections import Counter
def get_hints(word: str, secret_word: str):
word = word.lower()
result = [""] * len(word)
missing_indexes = []
secrect_counter = Counter(secret_word)
for idx, c in enumerate(word):
if c == secret_word[idx]:
result[idx] = "green"
sec... | pythonfoo/rest-wordle | rest_wordle/utils.py | utils.py | py | 712 | python | en | code | 0 | github-code | 36 |
9211558964 | import sys
import os
import time
import traceback
import pandas as pd
import seaborn as sns
import pydotplus
import matplotlib.pyplot as plt
import numpy as np
from sklearn.tree import export_graphviz
from sklearn import tree
from sklearn.model_selection import train_test_split
from sklearn.model_selection import Gri... | sarah-antillia/SOL4Py_V4 | ml/DecisionTreeClassifier.py | DecisionTreeClassifier.py | py | 8,676 | python | en | code | 0 | github-code | 36 |
70874377705 | from decimal import Decimal
from random import random
from unittest.mock import ANY, Mock
from uuid import UUID, uuid4
from fastapi import FastAPI
from injector import InstanceProvider
from mockito import when
from pytest import fixture, mark
from currency import Currency
from ordering import Service as OrderingServi... | lzukowski/workflow | tests/application/test_api.py | test_api.py | py | 5,764 | python | en | code | 5 | github-code | 36 |
28834678402 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 11 14:34:04 2015
@author: 89965
fonctions de structurelles diverses
"""
import os
import re
import logging
import subprocess
from collections import defaultdict
import psutil
import pyetl.formats.formats as F
import pyetl.formats.mdbaccess as DB
from .outils import charg... | klix2/mapper0_8 | pyetl/moteur/fonctions/traitement_divers.py | traitement_divers.py | py | 26,649 | python | fr | code | 0 | github-code | 36 |
35658691918 | """The filtersets tests module."""
import pytest
from django.db.models.query import QuerySet
from django.http import HttpRequest
from communication.serializer_fields import (ParentMessageForeignKey,
UserReviewForeignKey)
from conftest import OBJECTS_TO_CREATE
pytestmark = ... | webmalc/d8base-backend | communication/tests/serializer_fields_tests.py | serializer_fields_tests.py | py | 1,305 | python | en | code | 0 | github-code | 36 |
3314005552 | import time, json, os, logging, requests
from cumulocityAPI import C8Y_BASEURL, C8Y_TENANT, C8Y_HEADERS, CumulocityAPI
from arguments_handler import get_profile_generator_mode
from oeeAPI import OeeAPI
def try_int(value):
try:
return int(value)
except:
return None
PROFILES_PER_DEVICE = try_i... | SoftwareAG/oee-simulators | simulators/main/profile_generator.py | profile_generator.py | py | 5,006 | python | en | code | 8 | github-code | 36 |
42356364206 | import os
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping
from utils.callbacks import ModelCheckpoint, TimeHistory
from engine.metrics import (jaccard_index, jaccard_index_softmax, IoU_instances,
instance_segmentation_loss, weighted_bce_dice_loss)
def prepare_... | lijunRNA/EM_Image_Segmentation | engine/__init__.py | __init__.py | py | 3,725 | python | en | code | null | github-code | 36 |
5986988615 | from albert import *
import os
import pathlib
import shlex
import subprocess
md_iid = '1.0'
md_version = "1.8"
md_name = "Locate"
md_description = "Find and open files using locate"
md_license = "BSD-3"
md_url = "https://github.com/albertlauncher/python/tree/master/locate"
md_bin_dependencies = "locate"
class Plugin... | m0lw9re/albert | plugins/python/plugins/locate/__init__.py | __init__.py | py | 2,227 | python | en | code | 0 | github-code | 36 |
23400353850 | import cv2
import numpy as np
from matplotlib import pyplot as plt
import os
os.chdir('C:\\Users\\sachi\\.vscode\\GitHubRepos\\OSCV_Exercises')
exetasknum = 1
# Contours can be explained simply as a curve joining all the continuous points (along the boundary), having same color or intensity. The contours are a useful ... | sachingadgil/OSCV_Exercises | OpenCV_Python_Tutorials/017 Contours Getting Started.py | 017 Contours Getting Started.py | py | 1,930 | python | en | code | 0 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.