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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
26924932220 | import os, sys
import json
import xml.etree.ElementTree as ET
labels_trad = {
'bras levés' : 'arms_raised',
'combat' : 'fighting',
'action' : 'action',
'aucune' : 'none',
'se lever' : 'stand_up',
'se baisser' : 'bend_down',
's\'assoir' : 'sit_down',
'se coucher' : 'lie_down',
'chuter' : 'falling',
'déplacement' : 'mo... | anessabiri/test_version_nogit_15 | transforms/cvat_to_coco.py | cvat_to_coco.py | py | 6,034 | python | en | code | 0 | github-code | 50 |
28078196972 | # -*- coding: utf-8 -*-
"""
@Author 坦克手贝塔
@Date 2023/5/17 10:01
"""
from typing import List
"""
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
"""
"""
思路:用列表把所有的值都存起来,再反序即可
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
... | TankManBeta/LeetCode-Python | 剑指Offer_06_easy.py | 剑指Offer_06_easy.py | py | 691 | python | en | code | 0 | github-code | 50 |
13420508024 | from django.shortcuts import render, HttpResponse, redirect
from .forms import MovimentacaoForm, LoginForm, PoupancaForm
from .models import Movimentacao, Carteira, Poupanca
from django.contrib import messages
from django.contrib.auth import login, logout
from usuario.models import Usuario
# Create your views here... | annydomingos/Supple | financeiro/views.py | views.py | py | 6,435 | python | pt | code | 1 | github-code | 50 |
16486696564 | import os
raw_directory = '/home/julius/ScienceBowl/ScienceBowlFormat/raw'
new_directory = '/home/julius/ScienceBowl/ScienceBowlFormat/new'
def get_new_filename(short_filename):
short_to_long = {
'astr': 'astronomy',
'genr': 'general_science',
'biol': 'biology',
'chem': 'chemistry... | juliustao/ScienceBowlFormat | format.py | format.py | py | 6,198 | python | en | code | 1 | github-code | 50 |
72917307674 | class Node:
def __init__(self, data,seatno,present):
self.data = data
self.seatno=seatno
self.next = None
self.prev = None
self.present=present
class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, new_d... | tanmay6414/Python | DSA_in_python/dequeue.py | dequeue.py | py | 1,950 | python | en | code | 0 | github-code | 50 |
19031455400 | import streamlit as st
from main import get_graph, get_download_graph
def graph():
pattern = st.text_input("Слово, которое мы хотим найти в сообщениях")
time_from = st.text_input("от какого времени (указывать в формате год-месяц-день)")
time_to = st.text_input("по какое время мы хотим найти (указывать в ф... | artem12345-png/CV | message_graph/server.py | server.py | py | 1,252 | python | ru | code | 0 | github-code | 50 |
22617246797 | from .HTTPClient import HTTPClient
def autoFillFeatures(options=None):
features = options.get('features', []) if options else []
if options and 'question' in options and 'question_answer' not in features:
features.append('question_answer')
return features
class SceneXClient(HTTPClient):
def __... | standardgalactic/jinaai-py | jinaai/clients/SceneXClient.py | SceneXClient.py | py | 2,028 | python | en | code | null | github-code | 50 |
18553789292 | from django.urls import path, include
from .views import (
telegram_index, viber_index, ChannelListView,
ChannelDetailView, ChannelFullDetailView, ChannelCreateView,
ChannelUpdateView, ChannelDeleteView, BotUpdateView,
BotCreateView, root_view, ajax_channels_update,
ajax_get_channels, channel_list_... | wykyee/old-bot | bots_management/urls.py | urls.py | py | 2,745 | python | en | code | 0 | github-code | 50 |
10733655437 |
from MovieLens import MovieLens
from surprise import KNNBasic
import heapq
from collections import defaultdict
from operator import itemgetter
import socket
def simpleUserCFGive(id):
testSubject = str(id)
k = 10
# Load our data set and compute the user similarity matrix
ml = MovieLens(... | neerajrp1999/Movie-App-Including-recommender-system | SimpleUserCF/SimpleUserCF/SimpleUserCF.py | SimpleUserCF.py | py | 3,023 | python | en | code | 0 | github-code | 50 |
16558263898 | import gzip
import itertools
import os
import time
import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker
from imicrobe.uproc_results.uproc_models import SampleToUproc, Uproc
def main():
# connect to database on server
# e.g. mysql+pymysql://load:<password>@localhost/load
db_uri = os.environ.ge... | hurwitzlab/imicrobe-data-loaders | imicrobe/load/uproc_results/load_pfam_table.py | load_pfam_table.py | py | 6,158 | python | en | code | 0 | github-code | 50 |
29011691648 | """An interface for interacting with the num2vid config.json."""
import json
from .errors import ConfigPathError, ConfigReadError
class Config:
"""An interface for interacting with the num2vid config.json.
:attr _path: path to the current instance's config json.
:type _path: str
:attr _config: pytho... | jacobmartinez3d/num2vid | num2vid/config.py | config.py | py | 2,504 | python | en | code | 0 | github-code | 50 |
26255326658 | #!/usr/bin/env python
from twisted.internet import reactor
from coherence.upnp.core import DIDLLite
from coherence.upnp.core.ssdp import SSDPServer
from coherence.upnp.core.msearch import MSearch
from coherence.upnp.core.device import Device, RootDevice
from coherence.extern import louie
class DevicesListener(object... | kpister/prompt-linter | data/scraping/repos/hufman~coherence_experiments/ssdp.py | ssdp.py | py | 2,768 | python | en | code | 0 | github-code | 50 |
10539216817 | #!/usr/bin/python
# coding: UTF-8
# original code URL https://github.com/xkumiyu/chainer-GAN-CelebA
# revised by Nakkkkk(https://github.com/Nakkkkk)
import numpy
import chainer
from chainer import cuda
import chainer.functions as F
import chainer.links as L
def add_noise(h, sigma=0.2):
xp = cuda.get_array_modu... | Nakkkkk/chainer-GAN-CelebA-anime-annotated | net.py | net.py | py | 9,311 | python | en | code | 0 | github-code | 50 |
21021275299 | from ..crawler import TableCrawler
from ..entities import Party
from ..utils import parse_vote_count
URL = 'https://www.cec.gov.tw/pc/zh_TW/L4/n00000000000000000.html'
TOTAL_SEATS = 34
def calculate_round_1(vote_counts):
total_vote_count = sum(vote_counts.values())
result = sorted(
((name, TOTAL_SEA... | uranusjr/electionpeeker | electionpeeker/sources/national.py | national.py | py | 1,167 | python | en | code | 1 | github-code | 50 |
18525853716 | from util import *
from bs4 import BeautifulSoup
import json
years = [
['2017', 'http://www.fortunechina.com/fortune500/c/2017-07/20/content_286785.htm'],
['2016', 'http://www.fortunechina.com/fortune500/c/2016-07/20/content_266955.htm'],
['2015', 'http://www.fortunechina.com/fortune500/c/2015-07/22/conte... | 19js/Nyspider | www.fortunechina.com/fortune500.py | fortune500.py | py | 6,154 | python | en | code | 16 | github-code | 50 |
23814910118 | import csv
from datetime import datetime
DEGREE_SYBMOL = u"\N{DEGREE SIGN}C"
def format_temperature(temp):
"""Takes a temperature and returns it in string format with the degrees
and celcius symbols.
Args:
temp: A string representing a temperature.
Returns:
A string contain the ... | SheCodesAus/she-codes-python-weather-project-Rosie-Gul-codes | weather.py | weather.py | py | 7,592 | python | en | code | 0 | github-code | 50 |
31158236285 | # -*- coding: utf-8 -*-
"""
Created on Wed May 16 23:39:51 2012
@author: Maxim
"""
def getRandPrefix(fileExt = "", addSymbol = ""):
from random import randrange
from time import gmtime, strftime
Time = int(strftime("%H%M%S", gmtime()))
NamePrefix = str(Time+randrange(0,1e6,1)) + addSy... | mishin/maxim-codes | getRandPrefix.py | getRandPrefix.py | py | 470 | python | en | code | 0 | github-code | 50 |
43247112469 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import datetime
import math
import sys
sys.path.append('/lib/python2.7/site-packages')
import random
import numpy as np
import tensorflow as tf
def print_debug(msg):
... | adamrocker/ishinomakihackathon2017 | al/app/al.py | al.py | py | 21,938 | python | en | code | 0 | github-code | 50 |
41877022835 | #Emrich-Micahel Perrier
#Lab 16
from random import randrange
def roll():
num = randrange(1,7)
return num
def main():
ones = 0
twos = 0
threes = 0
for i in range (30):
num1 = roll()
print(num1, end=" ")
if num1 == 1:
ones += 1
elif num1 == 2:
... | emrichmp/Python-Programs | DiceCounter.py | DiceCounter.py | py | 801 | python | en | code | 0 | github-code | 50 |
29340197096 | #!/usr/bin/python3
import sys
import io
if len(sys.argv)<3:
print('Podaj nazwe pliku txt wej i wyj oraz liczbe - 1 > Z Windows -> Unix')
print('2 Z Unix > Windows')
sys.exit(1)
with open(sys.argv[1], 'r') as file_input:
content = file_input.read()
if int(sys.argv[2]) == 1:
with open(sys.argv[1],... | TryUnder/DeTryRepo | University/Developer_Environment/Bash/Python/Zad_8.2.py | Zad_8.2.py | py | 499 | python | en | code | 0 | github-code | 50 |
71074366556 | # -*- coding: utf-8 -*-
from environment import GraphicDisplay, Env
class ValueIteration:
def __init__(self, env):
# 환경 객체 생성
self.env = env
# 가치 함수를 2차원 리스트로 초기화
self.value_table = [[0.0] * env.width for _ in range(env.height)]
# 감가율
self.discount_factor = 0.9
... | rlcode/reinforcement-learning-kr | 1-grid-world/2-value-iteration/value_iteration.py | value_iteration.py | py | 2,586 | python | ko | code | 351 | github-code | 50 |
32592412403 | import sys
def isPrime(n):
if n==1:
return False
else:
for i in range(2, int(n**0.5)+1):
if n%i == 0:
return False
return True
A,B = map(int,sys.stdin.readline().split())
answer = []
for x in range(A,B+1):
if isPrime(x):
answer.append(x)
for x in... | san9w9n/2020_WINTER_ALGO | 1929.py | 1929.py | py | 359 | python | en | code | 0 | github-code | 50 |
23751705994 | import customtkinter as ctk
class LoadingBox(ctk.CTk):
def __init__(self, title: str = "Loading..."):
super().__init__()
self.title(title)
self.geometry("400x150")
self.resizable(False, False)
self.base_frame = ctk.CTkFrame(self)
self.base_frame.pack(fill="both", ex... | Tremirre/CassandraRentalApp | rental/ui/loading.py | loading.py | py | 887 | python | en | code | 0 | github-code | 50 |
18304840633 | from openerp.osv import fields,osv
from openerp.tools import sql
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
import time
from datetime import datetime, date
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, float_compare
class tms_expense_anal... | jesramirez/tmsv8 | tms_analysis/tms_expense_analysis.py | tms_expense_analysis.py | py | 4,475 | python | en | code | 2 | github-code | 50 |
10733485967 |
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
from Image_Event import TakeRating
import getRecomentation as gR
from ClientR import *
root = Tk()
root.geometry('1000x700')
def page1R():
frame_2R.pack_forget()
frame_3R.pack_forget()
frame_4R.pack_forget()
fra... | neerajrp1999/Movie-App-Including-recommender-system | Login/ClienPage/Home.py | Home.py | py | 10,394 | python | en | code | 0 | github-code | 50 |
3210927870 | import unittest
class MajorityElement(unittest.TestCase):
"""
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times.
You may assume that the majority element always exists in the array.
"""
def majority_element(sel... | EugeneStill/PythonCodeChallenges | majority_element.py | majority_element.py | py | 863 | python | en | code | 0 | github-code | 50 |
8542534731 | from COCODataUtility import COCODataCategories, COCODataImage, COCODataAnnotation, COCODataWriter
categories = COCODataCategories()
categories.add_category("Cabinet_Handle")
categories.add_category("Cabinet_Door")
data_writer = COCODataWriter(categories)
image = COCODataImage(360, 640, 'angle13_Color.png')
segmentat... | JanusMaple/COCOData_Writer | COCODataUtility_Demo.py | COCODataUtility_Demo.py | py | 1,701 | python | en | code | 2 | github-code | 50 |
32752491690 | import json
from pprint import pprint
from bs4 import BeautifulSoup
# Read database data - after it has been encoded in json
json_data = open('db.json')
data = json.load(json_data)[0]['hubot:storage']
macros = json.loads(data)['macros']
json_data.close()
# Sort the data alphabetically
macros = sorted(macros, key=lamb... | ericluii/hubot-webserver | macro_html_gen.py | macro_html_gen.py | py | 1,854 | python | en | code | 1 | github-code | 50 |
26584824757 | from confluent_kafka import Consumer, Message
from django.conf import settings
KAFKA_RUNNING: bool = True
def kafka_consumer_run() -> None:
conf = {
"bootstrap.servers": settings.KAFKA_BOOTSTRAP_SERVER,
"group.id": settings.KAFKA_GROUP_ID,
"auto.offset.reset": settings.KAFKA_OFFSET_RESET... | luizSilva976/django_kafka | django_kafka/consumer.py | consumer.py | py | 2,091 | python | en | code | null | github-code | 50 |
11053824580 | from odoo.tests.common import TransactionCase
class TestSaleProject(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.analytic_account_sale = cls.env['account.analytic.account'].create({
'name': 'Project for selling timesheet - AA',
'code': ... | anhjean/beanbakery_v15 | addons/sale_project/tests/test_sale_project.py | test_sale_project.py | py | 8,446 | python | en | code | 5 | github-code | 50 |
22331897062 | # mathesis.cup.gr course with title "Introduction to Python"
# Project: Tic Tac Toe
import random
import time
marker = {'Player 1': 'X', 'Player 2': 'O', }
def display_board(board):
#it prints the tic tac toe's state
cell = 0
for i in range(3):
firstLine = '+'
for j in range(53):
... | theomeli/Mathesis-apps | tic tac toe/tic_tac_toe.py | tic_tac_toe.py | py | 5,744 | python | en | code | 0 | github-code | 50 |
27275885645 | import json
def get_command_help_string(serverid, userlevel, commandname):
with open('servers.json', 'r') as f:
servers = json.load(f)
servername = servers[f'sid{serverid}']['servername']
disabledcommands = servers[f'sid{serverid}']['disabledcommands']
try:
customcommands = servers[f'... | Tiyenti/unobtainibot | commandhelp.py | commandhelp.py | py | 14,255 | python | en | code | 1 | github-code | 50 |
7469977931 | from korea_public_data.core.choices import ResponseType
from korea_public_data.core.vars import default as var
from korea_public_data.core.consts import data as const
from korea_public_data.data.base import PublicDataBase
class GetCovid19InfStateJson(PublicDataBase):
"""공공데이터활용지원센터_보건복지부 코로나19 감염 현황"""
def __... | lee-lou2/korea-public-data | data/data_go_kr/covid_infection_status.py | covid_infection_status.py | py | 1,384 | python | en | code | 18 | github-code | 50 |
70425535517 | """ personalize neural architectures using data from test subjects
This script retrains a pretrained neural network using additional data from test subjects. The pretrained network resulted
from a PPG based training by the script 'ppg_training_mimic_iii.py'. Additional data can be the first 20 % of the test
subject's ... | Fabian-Sc85/non-invasive-bp-estimation-using-deep-learning | ppg_personalization_mimic_iii.py | ppg_personalization_mimic_iii.py | py | 12,573 | python | en | code | 96 | github-code | 50 |
9445686087 | from django.shortcuts import render, redirect
from bs4 import BeautifulSoup
import requests
# Create your views here.
def home(request):
if request.method == "POST":
url = request.POST.get("href")
# Check url is under ptt domain
if url[0:22] != "https://www.ptt.cc/bbs":
url ... | MatsuiLin101/ml101-site | appPttParser/views.py | views.py | py | 2,170 | python | en | code | 0 | github-code | 50 |
8148804844 | import os
import json
import dotenv
import openai
import streamlit as st
from streamlit_chat import message
# .env file must have OPENAI_API_KEY and OPENAI_API_BASE
dotenv.load_dotenv()
openai.api_type = "azure"
openai.api_base = os.getenv("OPENAI_API_BASE")
openai.api_version = "2023-03-15-preview"
openai.api_key = ... | hyssh/azure-openai-quickstart | quickstart-learnfast/creative-product-naming-assistant/app.py | app.py | py | 4,098 | python | en | code | 2 | github-code | 50 |
39512273388 | import math
with open('14/input2.txt', 'rt') as fp:
lines = fp.readlines();
class Reaction:
def __init__(self, formula):
self.components = {}
components, output = formula.split('=>')
self.parseComponents(components)
self.quantity, self.reagent = output.strip().split(' ')
... | dshookowsky/adventOfCode | 2019/14/14a.py | 14a.py | py | 1,188 | python | en | code | 0 | github-code | 50 |
29621436523 | # -*- coding:utf-8 -*-
import json
import os.path as osp
class DatasetLoader:
def __init__(self, qas_path, owl_path):
self.owl_path = owl_path
self.qas_path = qas_path
self.owls = dict() # {scene_name: owl_contents}
self.qas = self.load_qa_scenario(qas_path)
# qas: {'FloorPl... | donghyeops/3D-SGG | VeQA/dataset_loader.py | dataset_loader.py | py | 2,304 | python | en | code | 2 | github-code | 50 |
72088335514 | from collections import defaultdict
from typing import Union
class Graph:
""" Undirected graph data structure """
def __init__(self, connections):
self.graph = defaultdict(set)
self.add_connections(connections)
def add_connections(self, connections):
""" Add connections (list of ... | BunnyNoBugs/Classroom-Year-3 | midterm_test/graph_representation.py | graph_representation.py | py | 2,843 | python | en | code | 2 | github-code | 50 |
16549532158 | import requests
import warnings
def results_to_names(results, include_synonyms=True):
"""Takes OLS term query returns list of all labels and synonyms"""
out = []
for t in results['_embedded']['terms']:
out.append(t['label'])
if include_synonyms and t['synonyms']:
out.extend(t['... | HumanCellAtlas/matrix_semantic_map | src/matrix_semantic_map/OLS_tools.py | OLS_tools.py | py | 5,445 | python | en | code | 1 | github-code | 50 |
71057046876 | #!/usr/bin/env python
import sys
import re
# Simple Python script that takes PlatformIO's compiler errors and maps them to
# output that can be understood by the Actions runner.
re_err = re.compile(r"^([^:]+):([0-9]+):([0-9]+): error: (.*)$")
# Parameters are strings of the form
# path_prefix:replacement_prefix:line... | fhessel/esp32_https_server | extras/ci/scripts/pio-to-gh-log.py | pio-to-gh-log.py | py | 1,157 | python | en | code | 292 | github-code | 50 |
40241578160 | import FWCore.ParameterSet.Config as cms
externalLHEProducer = cms.EDProducer("EmbeddingLHEProducer",
src = cms.InputTag("selectedMuonsForEmbedding","",""),
vertices = cms.InputTag("offlineSlimmedPrimaryVertices","","SELECT"),
particleToEmbed = cms.int32(15),
rotate180 = cms.bool(False),
mirror = ... | cms-sw/cmssw | TauAnalysis/MCEmbeddingTools/python/EmbeddingLHEProducer_cfi.py | EmbeddingLHEProducer_cfi.py | py | 448 | python | en | code | 985 | github-code | 50 |
16164098320 | from os import sep
with open(f'inputs{sep}day_3.txt') as rf:
lines = [line.strip() for line in rf.readlines()]
class Claim:
def __init__(self, owner=None, origin=None, span=None):
self.owner = owner
self.origin = origin
self.x = int(origin[0])
self.w = int(span[0])
self... | Nathansbud/AdventOfCode | 2018/day_3.py | day_3.py | py | 1,832 | python | en | code | 1 | github-code | 50 |
29596572847 | from gevent import monkey
monkey.patch_all()
import logging
logging.basicConfig(level=logging.DEBUG)
logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.getLogger("blockchain").setLevel(logging.DEBUG)
logging.getLogger("channel_manager").setLevel(logging.DEBUG)
log = logging.getLogger(__name__)
from micr... | ilhanu/ether-academy | Code_research/microraiden/docker/uwsgi/app/app.py | app.py | py | 2,702 | python | en | code | 0 | github-code | 50 |
26489706317 |
######################################################################################
### Gene set enrichment analysis with GSEAPY
######################################################################################
### Author: Carlos Arevalo
### Email: carevalo0170@gmail.com
### PROGRAM DESCRIPTION
### Program ... | caeareva/DM-DASE | gsea/compute_gsea_program.py | compute_gsea_program.py | py | 13,621 | python | en | code | 0 | github-code | 50 |
34088264915 | import os
import discord
from dotenv import load_dotenv
import logging
from services import get_matches_by_date
from random import choice
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
intents = discord.Intents.default()
intents.mes... | IgnacioCurti/discord_bot | bot.py | bot.py | py | 1,204 | python | en | code | 0 | github-code | 50 |
72061712156 | import sys
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
n, m = map(int, input().split())
A = [[] for _ in range(n+1)]
visited = [False]*(n+1)
def dfs(v):
visited[v] = True
for i in A[v]:
if not visited[i]: # 아직 방문 안한애들 방문
dfs(i)
for _ in range(m):
s, e = map... | cherrie-k/algorithm-python | 백준/Silver/11724. 연결 요소의 개수/연결 요소의 개수.py | 연결 요소의 개수.py | py | 562 | python | ko | code | 0 | github-code | 50 |
13299875084 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 17 14:22:17 2018
@author: Soumya
"""
import cv2
import numpy as np
original_img = cv2.imread('img2.jpg')
original_img = cv2.resize(original_img, (600,923))
resized_img = cv2.resize(original_img, (300,600))
box_vector ='0 0.10083333333333333 0.65... | rounakskm/Annotation-Detector | box_draw.py | box_draw.py | py | 1,842 | python | en | code | 0 | github-code | 50 |
18525716526 | import json
import re
import time
from bs4 import BeautifulSoup
import requests
import openpyxl
import random
import threading
import os
def get_headers():
pc_headers = {
"X-Forwarded-For": '%s.%s.%s.%s' % (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)),
... | 19js/Nyspider | www.adidas.com.cn/adidas.py | adidas.py | py | 7,820 | python | en | code | 16 | github-code | 50 |
1376076143 | import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from gym import spaces
from gym_rlf.envs.rlf_env import RLFEnv, MIN_PRICE, MAX_PRICE
from gym_rlf.envs.Parameters import LotSize, TickSize, sigma, kappa, alpha, factor_alpha, factor_sensitivity, factor_sigma, p_e, M, K
# Stable... | sophiagu/RLF | gym-rlf/gym_rlf/envs/apt_env.py | apt_env.py | py | 4,557 | python | en | code | 7 | github-code | 50 |
20548981126 | def equilibrium(A):
for i in range(len(A)):
sl = 0
for il in range(i):
sl += A[il]
for ir in range(i+1, len(A)):
sl -= A[ir]
if sl == 0:
return i
return -1
def equilibrium_optimised(A):
if len(A)==1:
return 1
left_sum = 0
... | shivang98/DS-Algo-Practice | equilibrium_index.py | equilibrium_index.py | py | 573 | python | en | code | 0 | github-code | 50 |
30913849710 | # Pedir un numero y devolver los numeros primos desde el 0 hasta el ingresado por el usuario
def numeros_primos(num):
for i in range(2, num - 1):
if num % i == 0: return False
return True
def primos_hasta(num):
primos = []
for i in range(3, num + 1):
resultado = numeros_primos(i)
... | fedemoretto11/apuntes-python | Ejercicios practicos 2/ejercicio_practico_2.py | ejercicio_practico_2.py | py | 425 | python | es | code | 1 | github-code | 50 |
21078475346 | from flask import Blueprint, Flask, redirect, render_template, request
import repositories.human_repository as human_repo
import repositories.zombie_repository as zombie_repo
import repositories.biting_repository as biting_repo
from models.biting import Biting
bitings_blueprint = Blueprint("bitings", __name__)
import ... | fionaberkery/zombie_land | controllers/bitings_controller.py | bitings_controller.py | py | 1,896 | python | en | code | 0 | github-code | 50 |
36106666135 | # remove duplicate elememts from list
list_l=[1,3,7,5,6,4,7,8,6,4]
list_set=set(list_l)
print(list(list_set))
# dynamic
list_l=[]
list_b=int(input())
for i in range(list_b):
list_c=int(input("enter the values"))
list_l.append(list_c)
print(list_l)
# read N lines of input and create a nest... | mathekeerthana/Capstone | Lists.py | Lists.py | py | 768 | python | en | code | 0 | github-code | 50 |
38139517895 | import tkinter as tk
from PIL import Image, ImageTk
from lib.modString import addString, minusString
class drop:
"""
@ parent: frame that the "drop" is on
@ name: string representing the drop's name
@ raid_boss: the boss that drops 'drop'
@ r, c: position in the grid
@ cur count
@ total count
#################... | villestring/GBF-Blue-chest-counter | lib/drop.py | drop.py | py | 1,993 | python | en | code | 0 | github-code | 50 |
21943173149 | from datetime import datetime
class ParserBS():
item_order = 1
current_page = 1
sequential_errors = 0
def get_all_specifications(self, page, url):
specification_elements = page.select('div#detailSpecContent div#Specs fieldset dl')
specifications = dict()
try:
fo... | eduardosbcabral/HWParts-Crawler | beautiful_soup/parser_bs.py | parser_bs.py | py | 3,566 | python | en | code | 0 | github-code | 50 |
74417402076 | import matplotlib.pyplot as plt, numpy as np, pandas as pd
# general functions for plotting
# Tim Tyree
# 7.23.2021
def PlotTextBox(ax,text,text_width=150.,xcenter=0.5,ycenter=0.5,fontsize=20, family='serif', style='italic',horizontalalignment='center',
verticalalignment='center', color='black',use_turnoff_axis=T... | timtyree/bgmc | python/lib/viewer/bluf/plot_func.py | plot_func.py | py | 2,515 | python | en | code | 0 | github-code | 50 |
22541760133 | '''
将上周没有航班信息的机场数据在下周在爬取一遍
'''
import codecs
import pandas as pd
import csv
import requests
import re
import json
import pymysql as py
def readCSV2List(filePath):
try:
file=open(filePath,'r',encoding="gb18030")# 读取以utf-8
context = file.read() # 读取成str
list_result=context.split("\n")# 以回... | kidword/spider | 机场抓取信息/检查.py | 检查.py | py | 3,166 | python | en | code | 2 | github-code | 50 |
42198469647 | #!/usr/bin/env python3
import sys
import os.path
import re
read_mapped = 0
total_reads = 0
def load_annotations(infile):
ret = {}
with open(infile, 'r') as f:
data = f.read().split('\n')
for line in data:
if not line:
continue
entries = line.split(',')
ret.setdefault(entries[0], entries[1:])
ret... | lakinsm/meta-marc-publication | scripts/count_num_classified_resfams.py | count_num_classified_resfams.py | py | 4,101 | python | en | code | 1 | github-code | 50 |
37324197795 |
from turtle import*
def drSquare(le, color):
shape("turtle")
pencolor(color)
for i in range(4):
forward(le)
left(90)
# mainloop()
# drSquare(100,"red")
for i in range(30):
drSquare(i * 5, 'red')
left(17)
penup()
forward(i * 2)
pendown()
| huyhieu07/nguyenhuyhieu-c4e-16-labs- | lab03/nhap.py | nhap.py | py | 293 | python | en | code | 0 | github-code | 50 |
43598959090 | from flask import Flask,request,abort
import dataset
import json
import datetime
app=Flask(__name__)
db = dataset.connect('sqlite:///data/nobel_winners.db')
@app.route('/api/winners')
def get_country_data():
print('Request args:'+str(dict(request.args)))
query_dict={}
for key in ['country','category','year']:
ar... | nationcall/dataviz | D3/data_viz_JS_py/flask_serve/server_sql.py | server_sql.py | py | 804 | python | en | code | 0 | github-code | 50 |
18259038033 | #from player import Player
#tim = Player("Tim")
from enemy import Enemy , Troll, Vampyre, Vampyreking
dracula = Vampyreking("Dracula")
print(dracula)
dracula.take_damage(12)
print(dracula)
#random_monster = Enemy("Basic Enemy",12,1)
#print(random_monster)
#random_monster.take_damage(4)
#print(rand... | sarangp323/counting_freq | python_oops/inherit.py | inherit.py | py | 892 | python | en | code | 0 | github-code | 50 |
18161154203 | from config_joker import Config, JsonFileSource
def example():
config = Config(
sources=[
JsonFileSource(
file_path='./examples/json/config.json',
config_path='external_config_key[0].config'
)
]
)
print(config.required(key='external_k... | joaopedromgoulart/config-joker | examples/json/example_config_json.py | example_config_json.py | py | 373 | python | en | code | 0 | github-code | 50 |
40775602339 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 11 14:34:06 2021
@author: bhs89
"""
import turtle
import random
turtle.clearscreen()
tt = turtle.Turtle()
scr = turtle.Screen()
image1 = 'muji.gif'
image2 = 'brown-line.gif'
image3 = 'kakao_lion.gif'
scr.addshape(image1)
scr.addshape(image2)
scr.adds... | Bae-hong-seob/2021-2-University_2_2 | 빅데이터언어/실습/racing.py | racing.py | py | 815 | python | en | code | 0 | github-code | 50 |
22497232452 | # -*- coding: utf-8 -*-
import logging
import math
import os
import random
import time
import urllib
from collections import Counter
import requests
os.makedirs("logs", exist_ok=True)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1',
'Referer': 'http://google.c... | superseal/raisin | raisin/utils.py | utils.py | py | 2,483 | python | en | code | 0 | github-code | 50 |
24314432477 | import os
import torch
import pickle as pkl
from collections import Counter
from torchtext.vocab import Vocab
from eval import Model, load_checkpoint, load_vocabs
from model import get_pbg, save_vocab
BASE_PATH = './models/unified'
def unify_ents(e1, e2):
e = set(e1).union(set(e2))
e.remove('<unk>')
e.re... | rahular/coref-rl | wiki/reward/combine_models.py | combine_models.py | py | 2,120 | python | en | code | 9 | github-code | 50 |
39291268405 | import dash
from dash import dcc, html
import dash_bootstrap_components as dbc
app = dash.Dash(__name__,external_stylesheets=[dbc.themes.SLATE],use_pages=True)
server=app.server
app.config.suppress_callback_exceptions=True
sidebar=dbc.Nav(
[
dbc.NavLink(
[
html.Div(page["name"],... | DuaneIndustries/CoffeeRoasteryDash | app.py | app.py | py | 1,355 | python | en | code | 0 | github-code | 50 |
32115819718 | import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Main(QMainWindow):
def __init__(self, parent = None):
QMainWindow.__init__(self, parent)
self.InitUi()
def InitUi(self):
ql = QLabel(self)
ql.setText("<font color=\"blue\">... | MinTimmy/Data_Structure | First_semester/Demo1/all/test7.py | test7.py | py | 522 | python | en | code | 0 | github-code | 50 |
23889431271 | #!/usr/bin/env python2.7
from __future__ import print_function
import sys, os, glob, logging
from argparse import ArgumentParser
from BaseSpacePy.api.BaseSpaceAPI import BaseSpaceAPI
from BaseSpacePy.model.QueryParameters import QueryParameters as qp
list_options = qp({'Limit': 1024})
logging.basicConfig(
lev... | Teichlab/basespace_fq_downloader | download_fq_from_basespace.py | download_fq_from_basespace.py | py | 1,886 | python | en | code | 4 | github-code | 50 |
18356819426 | import pathlib
import pytest
BASE_PATH = pathlib.Path('docssrc/source/')
def plot(path):
_path = BASE_PATH / path
name = _path.name
_path = _path.parent
def wraps(fn):
@pytest.mark.skipif(
(_path / (name + '.png')).exists()
and (_path / (name + '.svg')).exists(),
... | Peilonrayz/dice_stats | docssrc/source/_plots/env.py | env.py | py | 665 | python | en | code | 3 | github-code | 50 |
28077578353 | # int, float, str, bool
# int -> str; str -> int
# float -> str; str -> float
j = 7
k = str(j)
a = float(input())
b = float(input())
print(a + b, a - b, a * b, a / b, a ** b)
c = 7
d = 8.4
print(c + d, type(c + d))
# bool: True, False
# все что пустое и все что 0 => False, все остальное - True
print(bool("123"), b... | GerasimovRM/MMSP | lesson2/1.py | 1.py | py | 401 | python | ru | code | 0 | github-code | 50 |
25192773855 | from flask import Blueprint, jsonify, request
from models import Departement, Role, RoleSchema, User, db
#blueprint setup
role = Blueprint('role',__name__)
@role.route('/AddRole', methods = ['POST'])
def AddRole():
req_Json = request.json
name = req_Json['name']
nameDepartement= req_Json['nameDeparteme... | sofieneMoka/GED_APP_BACKEND | views/role.py | role.py | py | 2,105 | python | en | code | 1 | github-code | 50 |
24800009720 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
from utils import CSV
import time
from connections import Mysql
from interfaces import Field
############ Etapa 1
mysqlClient = Mysql()
# utilCsv = CSV()
tableName="planilha_dyego"
dm1Name="dm1_dyego"
dm2Name="dm2_dyego"
whereEmptyName="nome = ''"
whereEmptyEmail="email = ... | dyegocaldeira/bigdata | app-rds.py | app-rds.py | py | 2,815 | python | en | code | 0 | github-code | 50 |
9875537328 | import random
class GeneratingRandomness:
def __init__(self):
self.min_num = 100
self.result_string = ''
self.check = ["000", "001", "010", "011", "100", "101", "110", "111"]
self.balance = 1000
def take_input(self):
list_collector = []
while True:
... | sergo8/Generating_Randomness | Generating Randomness/task/predictor/predictor.py | predictor.py | py | 3,547 | python | en | code | 0 | github-code | 50 |
70173602715 | import faiss # make faiss available
import numpy as np
import time
def IVFPQMultiGpu(config):
print("IVFPQMultiGpu, ", config)
d = config['dimension'] # dimension
nb = config['db_size'] # database size
nq = config['query_num'] ... | egliu/faiss-quick-demo | src/gpufaiss/ivfpqmultigpu.py | ivfpqmultigpu.py | py | 1,827 | python | en | code | 0 | github-code | 50 |
40843949822 | def is_prime(num):
return primes[num]
def calc_score(num, name):
if name == "daewoong":
enemy = "gyuseong"
else:
enemy = "daewoong"
if not is_prime(num):
if len(maximum_3num[enemy]) < 3:
score[enemy] += 1000
else:
score[enemy] += min(maximum_3num... | hellouz818/AlgorithmStudy | 김원호/5회차/소수게임.py | 소수게임.py | py | 1,376 | python | en | code | 1 | github-code | 50 |
14832397675 | rows, columns = [int(x) for x in input().split(', ')]
matrix = []
total_sum = 0
for row_index in range(rows):
matrix.append([int(x) for x in input().split(', ')])
for col_index in range(columns):
total_sum += matrix[row_index][col_index]
print(total_sum)
print(matrix) | Pavlina-G/Softuni-Python-Advanced | 04. Multidimensional lists/Lab/01_2sum_matrix_elements.py | 01_2sum_matrix_elements.py | py | 296 | python | en | code | 0 | github-code | 50 |
11201796104 | # Python
from __future__ import annotations
from dataclasses import KW_ONLY, dataclass
from dataclasses import field as set_field
from typing import TYPE_CHECKING
# SD-WebUI
from modules import sd_models, sd_vae
# Local
from sd_advanced_grid.utils import clean_name, get_closest_from_list, logger, parse_range_float, ... | micky2be/a1111-sd-advanced-grid | sd_advanced_grid/grid_settings.py | grid_settings.py | py | 9,531 | python | en | code | 1 | github-code | 50 |
26268082638 | import os
import re
from pathlib import Path
import openai
import pandas
import numpy as np
import tiktoken
EMBEDDING_MODEL = "text-embedding-ada-002"
EMBEDDING_CTX_LENGTH = 8191
EMBEDDING_ENCODING = "cl100k_base"
MAX_EMBEDDINGS = 1536
MAX_TOKENS = 1600
GPT_MODEL = "gpt-3.5-turbo"
def get_embedding(text, model=EM... | kpister/prompt-linter | data/scraping/repos/liamchzh~circleci-docs-assistant/doc-assistant.py | doc-assistant.py | py | 5,549 | python | en | code | 0 | github-code | 50 |
72147729114 |
from django.urls import path
# from . import views
from das_admin import views
urlpatterns = [
path('index',views.index,name='index'),
path('',views.login,name='login'),
path('register',views.register,name='register'),
path('profile',views.profile,name='profile'),
path('patient_list',views.patient... | mayuri0610/python | PROJECT/Self Project/Dr.Appoinment System/CORE/das_admin/urls.py | urls.py | py | 1,952 | python | en | code | 0 | github-code | 50 |
10678997325 | #!/usr/bin/env python3
import random
import sys
import common
LENGTH = 4
COLORS = ['R', 'V', 'B', 'J', 'N', 'M', 'O', 'G']
def choices(e, n):
"""Renvoie une liste composée de n éléments tirés de e avec remise
On pourrait utiliser random.choices, mais cette fonction n'est pas
disponible dans les versions... | Margob29/mastermind | common.py | common.py | py | 4,405 | python | fr | code | 0 | github-code | 50 |
8943094478 | # program to execute all dependancies of task before execution of task itself
class Task:
def __init__(self, name, dependancies = None):
self.name = name
self.dependancies = dependancies
self.state = False
def execute(self):
if self.dependancies is not None:
for task in self.dependancies:
if task.s... | ch374n/python-programming | recursion/dependancies.py | dependancies.py | py | 629 | python | en | code | 0 | github-code | 50 |
41426028197 | from math import sqrt
import numpy as np
def proj_length(v, v_on):
on_norm = np.linalg.norm(v_on)
v_len = np.linalg.norm(v)
projection_len = 0
rejection_len = 0
if on_norm > 0.01:
projection_len = np.dot(v, v_on) / on_norm
if v_len > abs(projection_len):
rejection_le... | halt9k/bounded-ellipsoid | src/bounded_ellipsoid_alg.py | bounded_ellipsoid_alg.py | py | 2,041 | python | en | code | 2 | github-code | 50 |
16106954536 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#pip install orjson
#pip install tqdm
#pip install scipy
import json
import re
import numpy as np
#from tqdm import notebook
import collections
from tqdm import tqdm
from scipy import sparse
# In[2]:
#"data/stopword.list"
def get_stop_words(path):
stop_word... | 814yk/Yelp-Rating-Prediction | CTF_DF.py | CTF_DF.py | py | 11,329 | python | en | code | 1 | github-code | 50 |
38133489680 |
import tkinter as tk
from tkinter import *
win = tk.Tk()
win.geometry('')
win.title('.:.Calculator.:.')
win.geometry('400x600+550+100')
win.resizable(0, 0)
screentxt = ''
def my_btndot():
global screentxt
screentxt += str('.')
lbl.config(text=screentxt)
def my_btn0():
global screentxt
screen... | yazdanghasemi/Tools_For_Restuarant | Calculator_version1.py | Calculator_version1.py | py | 4,950 | python | en | code | 0 | github-code | 50 |
33168831099 | import RPi.GPIO as GPIO
leftWheelPins = ((11, 13, 15), (12, 16, 18))
rightWheelPins = ((33, 35, 37), (36, 38, 40))
def setupWheels():
for pins in leftWheelPins + rightWheelPins:
GPIO.setup(pins[0], GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(pins[1], GPIO.OUT)
GPIO.setup(pins[2], GPIO.OUT)
def... | Sohan-Dillikar/Raspberry_Pi_Bluetooth_RC_Car | Main_Code/wheels.py | wheels.py | py | 2,511 | python | en | code | 0 | github-code | 50 |
46965044858 | import requests
import json
class Networks:
polka = ["polkadot", 10]
kusama = ["kusama", 12]
westend = ['westend', 12]
address = "13mAjFVjFDpfa42k2dLdSnUyrSzK8vAySsoudnxX2EKVtfaq"
current_network = Networks.polka
url = "https://api.subquery.network/sq/ef1rspb/fearless-wallet"
headers = {'Content-Type': ... | novasamatech/substrate-history-comparer | old/history_elements_calc.py | history_elements_calc.py | py | 938 | python | en | code | 0 | github-code | 50 |
8971051726 | from tkinter import *
from quiz_brain import QuizBrain
THEME_COLOR = "#375362"
TEXT_FONT = ("Arial", 20, "italic")
class QuizInterface:
def __init__(self, quiz_brain: QuizBrain):
self.quiz = quiz_brain
self.window = Tk()
self.window.title("Quizzler")
self.window.config(padx=20, ... | angelov-g/100-days-of-code | intermediate-plus/gui-quiz/ui.py | ui.py | py | 2,334 | python | en | code | 2 | github-code | 50 |
32497366630 | import sys
import ctypes
from datetime import datetime
from os import makedirs, remove
from os.path import basename, splitext, join, exists
from numpy import concatenate, copy
from numpy.lib.stride_tricks import as_strided
import spacepy
from spacepy import pycdf
TIME_VARIABLE = 'Epoch'
VARIABLES = ['BY_GSM', 'BZ_GSM'... | ESA-VirES/VirES | preprocessing/average_omni_hr_1min.py | average_omni_hr_1min.py | py | 8,107 | python | en | code | 2 | github-code | 50 |
30243598632 | # using size to predict price
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
import pandas as pd
from sklearn.metrics import mean_squared_error
def myCode():
data = pd.read_csv("./houses.csv")
# Needs to reshape to be a 2D array with values.reshape(-1,1)
x = data.iloc[... | FinnianHBLR/Datascience-projects | week4.py | week4.py | py | 2,156 | python | en | code | 0 | github-code | 50 |
8441423009 | '''
Write a program to determine whether an employee is owed any overtime.
You should ask the user how many hours the employee worked this week,
as well as the hourly wage for this employee.
If the employee worked more than 40 hours, you should print a message
which says the employee is due some additional pay, as wel... | sauuyer/python-practice-projects | day5-overtime-calculator.py | day5-overtime-calculator.py | py | 2,082 | python | en | code | 0 | github-code | 50 |
28590685007 | from arclet.alconna import Alconna, Args, CommandMeta
from arclet.alconna.graia import Match, alcommand
from bce.option import Option
from bce.public.api import balance_chemical_equation
from graia.ariadne.app import Ariadne
from graia.ariadne.message.chain import MessageChain
from graia.ariadne.message.element import ... | linyunze/RainAa | module/balance.py | balance.py | py | 1,426 | python | en | code | 0 | github-code | 50 |
21554328390 | from PyQt5 import QtCore, QtWidgets, QtGui
from collections import deque
from ..const import *
class logViewerWidget:
def __init__(self, parent: QtWidgets.QWidget, name: str, pos: QtCore.QRect):
self.widget = QtWidgets.QTextBrowser(parent)
self.widget.setGeometry(pos)
self.widget.setObjec... | s-ktmy/nitfc-openCampus_2020 | src/Widget/logViewerWidget.py | logViewerWidget.py | py | 725 | python | en | code | 0 | github-code | 50 |
22058705964 | #!/bin/python
import sys
from collections import Counter
def makingAnagrams(s1, s2):
c1 = Counter(s1)
c2 = Counter(s2)
for x in set(c1).intersection(set(c2)):
curr = min(c1[x],c2[x])
c1[x] -= curr
c2[x] -= curr
return sum(c1.values())+sum(c2.values())
# Complete this functio... | thesharpshooter/hackerrank | strings/makingAnagrams.py | makingAnagrams.py | py | 420 | python | en | code | 0 | github-code | 50 |
44098013268 | from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from MainPageCalculator import Calculator
def test_calculator():
browser = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
c... | Julia2810/homeworks | ДЗ7/Task_2/test_result_on_calculator.py | test_result_on_calculator.py | py | 611 | python | en | code | 0 | github-code | 50 |
33763552438 | import torch
import torch.nn as nn
import torch.nn.functional as F
from cwlayers import CWConv2d, CWLinear
class MnistCwConv(nn.Module):
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonline... | sytelus/NNExp | NNExp/pytorch/mnist/mnist_cwconv.py | mnist_cwconv.py | py | 1,342 | python | en | code | 1 | github-code | 50 |
4095520800 | """
Summation of primes
Problem 10
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
import math
def is_prime(x):
if x%2 == 0 and x!=2:
return False
for i in range(3, int(math.sqrt(x))+1, 2):
if x%i == 0:
return False
... | reddynt/project-euler-solutions | 10-summation of primes.py | 10-summation of primes.py | py | 469 | python | en | code | 0 | github-code | 50 |
72825087835 | import csv
import operator
import pdb
import os
import argparse
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--tsv_file', type=str, required=True, help='Please set a tsv file you want to parsse.')
args = parser.parse_args()
return args
def main(filename, root_path):
wit... | Hyon0930/MusicTechPapers | src/organise_papers.py | organise_papers.py | py | 7,714 | python | en | code | 1 | github-code | 50 |
40085189624 | import argparse
from dataclasses import dataclass
import os.path
import re
import sys
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors impo... | flofriday/scripts | bdmaker/bdmaker.py | bdmaker.py | py | 6,472 | python | en | code | 0 | github-code | 50 |
30723639812 | from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from research_models import *
from pandas import read_excel
import numpy
engine = create_engine('sqlite:///research.db')
Session = sessionmaker(bind=engine)
session = Session()
def load_funding_resource(input_... | likit/sandbox | load_data.py | load_data.py | py | 3,544 | python | en | code | 0 | github-code | 50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.