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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
21246448771 | '''
Peça ao usuário para digitar dez valores numéricos e ordene por ordem crescente esses valores, guardando-os
num vetor. Ordene o valor assim que ele for digitado. Mostre na tela os valores em ordem.
'''
vetor = []
while len(vetor) < 10:
num = int(input(f'Digite o {len(vetor)+1}º número do vetor: '))
vetor.... | higor-gomes93/curso_programacao_python_udemy | Sessão 7.1 - Exercícios/ex38.py | ex38.py | py | 394 | python | pt | code | 0 | github-code | 1 |
40054780648 | # Task 24 - 04/08/2022
""" Write a Python program to input two natural numbers and check whether they
are co-prime or not. """
# Vevan O Narain S6- C
def areCoprime(a, b):
hcf = 1
for i in range(1, a + 1):
if (a % i == 0 and b % i == 0):
hcf = i
print(f"{a} and {b} are co-... | vevanonarain/Practical-Report-File---1 | task24.py | task24.py | py | 559 | python | en | code | 0 | github-code | 1 |
25476839440 | #!/usr/bin/env python3
import re
import json
from pprint import pprint
from argparse import ArgumentParser
from json import JSONDecodeError
from subprocess import call
import urllib
from os.path import expanduser
from urllib.parse import urlparse
import requests
import sys
from past.builtins import raw_input
# call w... | JosXa/twitch-native-streaming | twitch/twitch.py | twitch.py | py | 4,750 | python | en | code | 0 | github-code | 1 |
35268565961 | # A program that will list counties and use probability function to output theres possible frequency.
# Author: Ryan Cox
import numpy as np
import matplotlib.pyplot as plt
# make the array of occurences
possibleCounties = ["Kerry", "Dublin", "Galway", "Cork", "Meath"]
# Random.choice() is a probability function. ... | RYANCOX00/programming2021 | Week08-Plotting/Lab8.11.2.ABSolution.py | Lab8.11.2.ABSolution.py | py | 856 | python | en | code | 0 | github-code | 1 |
12000905328 | # -*- coding: utf-8 -*-
"""Classes for lidar ratio related db tables"""
from ELDAmwl.database.tables.db_base import Base
from sqlalchemy import Column
from sqlalchemy import DECIMAL
from sqlalchemy import INTEGER
from sqlalchemy import text
class ExtBscOption(Base):
"""content of the db table ext_bsc_options
... | actris-scc/ELDAmwl | ELDAmwl/database/tables/lidar_ratio.py | lidar_ratio.py | py | 1,249 | python | en | code | 3 | github-code | 1 |
30569550303 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 29 05:15:41 2022
@author: User
"""
#import required files and modules
import menu
def main():
menu.Title().update_cmd_title()
menu.Title().title_display()
menu.Description().description_display()
menu.MenuItems().menu_display()
menu_item... | 220pmc/Batch-Renamer-for-Windows | Batch Renamer for Windows.py | Batch Renamer for Windows.py | py | 1,605 | python | en | code | 0 | github-code | 1 |
39077417661 | import os
import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
os.system("mode con cols=130 lines=4")
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
headers = {
'User-Agent': user_agent
}
... | ElRizeru/dota2picker | update.py | update.py | py | 2,657 | python | en | code | 0 | github-code | 1 |
7681809043 | # Задайте список из нескольких чисел. Напишите программу,
# которая найдёт сумму элементов списка, стоящих на нечётной позиции.
# Пример:
# - [2, 3, 5, 9, 3] -> на нечётных позициях элементы 3 и 9, ответ: 12
# my_list = [2,3,5,9,3]
# count = 0
# for i in range(1,len(my_list),2):
# count+= my_list[i]
# print(count... | Zabaluna/HW-Python | Sem3/Homework/Task1HW.py | Task1HW.py | py | 677 | python | ru | code | 0 | github-code | 1 |
22644995741 | '''
This module implements the game data and logic and determines if the game was won or lost.
'''
def game_story():
'''
This function prints the story of the game.
'''
print("The Dragon Slayer")
print('''Welcome slayer! We've been waiting so long for you! Thank you so much for coming!
You see tha... | MatinPakfetrat/Assignment-1-Programming-Fundamentals | Game.py | Game.py | py | 4,379 | python | en | code | 0 | github-code | 1 |
28986490606 | import sqlite3
class SQLiteProfileImage():
def __init__(self):
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
dbname = "/sqlite/profile_image.db"
self.conn = sqlite3.conn... | minegishirei/flamevalue | trashbox/django3/app/flamevalue/my_SQLite_Profile.py | my_SQLite_Profile.py | py | 1,326 | python | en | code | 0 | github-code | 1 |
24657287989 | from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=200)
class Product(models.Model):
title = models.CharField(max_length=300)
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=10)
image ... | AbhishekBose89/Asssignment35-Q1-AbhishekBose | shoplane/restapi/models.py | models.py | py | 500 | python | en | code | 0 | github-code | 1 |
37336242441 | from math import pi
import pandas as pd
from bokeh.layouts import gridplot,row
from bokeh.io import output_file, save
from bokeh.palettes import Category20c
from bokeh.plotting import figure
from bokeh.transform import cumsum
from bokeh.palettes import Spectral6
from bokeh.transform import factor_cmap
def chart():
ou... | dj5/Plastic-Waste-Profiling | Profilling tools/chart2.py | chart2.py | py | 1,631 | python | en | code | 0 | github-code | 1 |
72933516193 | # *_* coding : UTF-8 *_*
# author : Leemamas
# 开发时间 : 2021/9/28 0:30
import pygame
class Cointext():
def __init__(self,rect,reward,bshape):
self.images = [pygame.image.load('images/coinText.png').subsurface(i*36, 0, 36, 49) for i in range(0, 11)]
self.rect=rect
self.reward=reward
... | leemamas/fishgame | coinText.py | coinText.py | py | 701 | python | en | code | 8 | github-code | 1 |
13461593976 | from typing import Dict, List, Union
import numpy as np
import torch
from src.utils.utils import shift_lang_token_right
class BatchCollator:
def __init__(self,
is_mlm: bool = False,
shift_lang_token: bool = False,
return_special_masks: bool = False,
... | RistoAle97/ContinualNAT | src/data/collators.py | collators.py | py | 8,618 | python | en | code | 6 | github-code | 1 |
28389679037 | from networks import AdaINGen, VAEGen, NetV2_128x128
from utils import weights_init, get_model_list, vgg_preprocess, load_vgg16, load_vgg19, get_scheduler
from torch.autograd import Variable
import torch
import torch.nn as nn
import os
class FACE_Trainer(nn.Module):
def __init__(self, hyperparameters):
sup... | TheSouthFrog/stylealign | pytorch_code/trainer.py | trainer.py | py | 5,877 | python | en | code | 182 | github-code | 1 |
41617267146 | """ Assignment 6 performance of Mango
"""
from ast import stmt
from pathlib import Path
import csv
import pathlib
from timeit import repeat, timeit as timer
import main
import users
import user_status
import pymongo
import pandas as pd
import random
import string
import time
import socialnetwork_model
... | smichalove/Python320_University_of_Washington | time_mongo.py | time_mongo.py | py | 13,262 | python | en | code | 0 | github-code | 1 |
6275958376 | #!/usr/local/bin/python
# coding: utf-8
"""
в этом файле пример создания собственного перечислимого типа в питоне
так как встроенного механизма нет, перечислимые типы создаются как наследники класса
Enum из модуля enum
"""
import enum
@enum.unique # не пропустит одинаковых значений
class Numbers(enum.IntEnum):
"... | amtsu/team22 | users/sivanov/lessons/lesson_27_enum/incrementing_intenum.py | incrementing_intenum.py | py | 2,382 | python | ru | code | 5 | github-code | 1 |
29673261055 | # -*- coding: utf-8 -*-
"""Server for the Raspi Webapp
Examples:
- get json with curl -> curl -X POST http://0.0.0.0:2828/api/v1/getCrashInfo -d data/1.json
- get image with curl -> curl -X POST http://0.0.0.0:2828/api/v1/getCrashImage -o received_img.png
"""
import sys
sys.path.append('..')
import os
import signal
imp... | tschibu/starthack-asimov | src/server.py | server.py | py | 3,244 | python | en | code | 0 | github-code | 1 |
30334646058 | #!/usr/bin/env python3
import sys
def ex05():
states = {
"Oregon": "OR",
"Alabama": "AL",
"New Jersey": "NJ",
"Colorado": "CO"
}
capital_cities = {
"OR": "Salem",
"AL": "Montgomery",
"NJ": "Trenton",
"CO": "Denver"
}
states_capital ... | RickBadKan/42-mini-piscina | list01/ex05/all_in.py | all_in.py | py | 1,367 | python | en | code | 2 | github-code | 1 |
70983003553 | class Customer:
def __init__(self, name, address, phone_number):
self.name = name
self.address = address
self.phone_number = phone_number
class Job:
def __init__(self, customer, date, duration):
self.customer = customer
self.date = date
self.duration ... | Thestartofyou/lawn | main - 2023-06-15T215017.151.py | main - 2023-06-15T215017.151.py | py | 1,618 | python | en | code | 0 | github-code | 1 |
73033882273 | # -*- coding: utf-8 -*-
'''
A salt module for SSL/TLS.
Can create a Certificate Authority (CA)
or use Self-Signed certificates.
:depends: - PyOpenSSL Python module (0.10 or later, 0.14 or later for
X509 extension support)
:configuration: Add the following values in /etc/salt/minion for the CA module
to funct... | shineforever/ops | salt/salt/modules/tls.py | tls.py | py | 56,256 | python | en | code | 9 | github-code | 1 |
43854526695 | import sys
import glob
import os
import math
import matplotlib.pyplot as plt
def get_number( file_name):
TEMPLATE = "gal_"
file_name = file_name.split("/")[-1]
number_index = file_name.find(TEMPLATE) + len(TEMPLATE)
if number_index == len(TEMPLATE) -1:
return file_name.split(".")[0]
number... | flmachado/UROP_Comp | Compare_Masses.py | Compare_Masses.py | py | 2,649 | python | en | code | 0 | github-code | 1 |
28541279468 | import csv
import matplotlib.pyplot as plt
'''
Get a list of keys from dictionary which has value that matches with any value in given list of values
'''
def getKeysByValues(dictOfElements, value):
listOfKeys = list()
listOfItems = dictOfElements.items()
for item in listOfItems:
if item[1] == valu... | aquarios77/python | 2021-04-08/temp_udz.py | temp_udz.py | py | 1,161 | python | en | code | 0 | github-code | 1 |
33095134638 | import solution
import numpy as np
class Solution(solution.Solution):
def solve(self, test_input=None):
return self.checkRecord(test_input)
def checkRecord(self, n):
"""
:type n: int
:rtype: int
"""
# mod = 10 ** 9 + 7
# alast, alastL, alastLL, last, la... | QuBenhao/LeetCode | problems/552/solution.py | solution.py | py | 1,103 | python | en | code | 8 | github-code | 1 |
24284540158 | """Bolted Entity Manager"""
from collections.abc import Mapping, MutableMapping
import logging
from typing import Any, Optional
import homeassistant.helpers.device_registry as hass_device_registry
import homeassistant.helpers.entity_registry as hass_entity_registry
from homeassistant.helpers.restore_state import (
... | dlashua/bolted | custom_components/bolted/entity_manager.py | entity_manager.py | py | 6,631 | python | en | code | 2 | github-code | 1 |
34056067204 | import os
import sys
import unittest
sys.path.insert(0, os.getcwd())
from pynewtonmath import core, wrapper
class TestWrapper (unittest.TestCase):
def test_expose_endpoints (self):
for op in core.ENDPOINTS:
self.assertTrue(op in dir(wrapper))
print('.', end='', flush=True)
... | benpryke/PyNewtonMath | tests/test_wrapper.py | test_wrapper.py | py | 1,466 | python | en | code | 5 | github-code | 1 |
20111131410 | import os
import sys
from CLS.Vokker import Vokker
class VokkerConsole:
_menue_: list = list()
def __init__(self, vokker: Vokker):
self._vokker_ = vokker
self._menue_()
def _menue_(self):
self._menue_ = [
'',
'',
' Vokabeltrainer',
... | gitrootside/vokker | CLS/VokkerConsole.py | VokkerConsole.py | py | 944 | python | en | code | 0 | github-code | 1 |
9334684847 | def subsetsum(l,n):
s_max = sum(l)//2
s = {0}
for x in l:
for y in s.copy():
if (x+y)<=s_max:
s.add(x+y)
return s
n = int(input())
l = [int(it) for it in input().split(" ")]
l_sum = sum(l)
s = subsetsum(l,n)
diff= l_sum//2-max(s)
if l_sum%2==0:
print(2*diff)... | rajukancharla21/Competitive_Programming | CSES/Introductory_Problems/Apple_Division.py | Apple_Division.py | py | 346 | python | en | code | 0 | github-code | 1 |
22505097089 | N = int(input())
lst = []
for i in range(N):
L, H = map(int,input().split())
lst.append([L,H])
# x축을 기준으로 정렬
lst.sort(key=lambda x: x[0])
# 가장 높은 기둥의 면적을 구하고 미리 더해주기
value = 0
for i in range(len(lst)) :
if lst[i][1] > value :
value = lst[i][1]
idx = i
# 처음 높이는 첫번째 기둥의 높... | Kminwo-o/BaekJoon-Algorithm | 백준/Silver/2304. 창고 다각형/창고 다각형.py | 창고 다각형.py | py | 1,154 | python | ko | code | 0 | github-code | 1 |
31208597289 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
author comger@gmail.com
"""
import sys
import json
sys.path.append('../../')
from datetime import datetime
from pprint import pprint
from kpages import run
def callback(app):
print("Start time: {0}".format(datetime.now().isoformat(" ")))
print("Config Par... | comger/kpages | demos/web/apprun.py | apprun.py | py | 748 | python | en | code | 23 | github-code | 1 |
3428235704 | import difflib
import re
from typing import Literal, TypedDict
import nltk
def segment_sentences_with_nltk(text: str) -> list[str]:
sent_detector = nltk.data.load("tokenizers/punkt/german.pickle")
return list(sent_detector.tokenize(text.strip()))
_PUNCTUATION_IN_MIDDLE_RE = re.compile("([\\w\\s,;:\\-]*)([?... | mulasik/wta | wta/utils/nlp.py | nlp.py | py | 8,344 | python | en | code | 1 | github-code | 1 |
26914970028 | #!/usr/bin/env python3
import os
import click
import hashlib
import imageio
from .jpeg import *
import subprocess as sp
from pathlib import Path
from contextlib import suppress
from multiprocessing import cpu_count
import concurrent.futures
cache_dir = Path.home() / '.cache/glitch-art-display'
cache_dir.mkdir(exist_... | TheTechromancer/glitch-art-display | glitch_art_display/main.py | main.py | py | 8,331 | python | en | code | 12 | github-code | 1 |
29031645023 |
VALUE_TYPE_LIST = ["X","Y","Z","Temperature","Humidity","Current"]
SENSOR_TYPE_DICT = {
0:"Vibration",
1:"Temperature",
2:"Humidity",
3:"TemperatureHumidity",
4:"Current",
"Vibration" :0,
"Temperature":1,
"Humidity":2,
"TemperatureHumidity":3,
"Current": 4
}
SENSOR_VALUE_MAP_D... | HwangJaeMyoung/MQTTServer | MQTTServer/MQTTServer/utils.py | utils.py | py | 505 | python | en | code | 0 | github-code | 1 |
13081443272 | #1
x = [ [5,2,3], [10,8,9] ]
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'}
]
sports_directory = {
'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'],
'soccer' : ['Messi', 'Ronaldo', 'Rooney']
}
z = [ {'x': 10, 'y': 20} ]
... | MVodopich/Lists_And_Dictionaries | lnd.py | lnd.py | py | 2,563 | python | en | code | 0 | github-code | 1 |
72059863395 | from esphome.components import number
from esphome.const import CONF_MAX_VALUE, CONF_MIN_VALUE, CONF_STEP
import esphome.config_validation as cv
import esphome.codegen as cg
from .. import fourheat_config_validation as fhcv
from .. import (
fourheat_ns,
CONF_DATAPOINT,
CONF_FOURHEAT_ID,
CONF_PARSER,
... | leoshusar/4heat-esphome | components/fourheat/number/__init__.py | __init__.py | py | 1,960 | python | en | code | 3 | github-code | 1 |
70873192355 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from os import listdir,path,curdir
from os.path import isfile, join
import re
import shutil
import pandas as pd
from sklearn.model_selection import train_test_split
import csv
import random
root = "/data01/ML/dataset/FACE_CLASSIFIER"
face_image_path = "/data01/ML/dataset/FACE_... | lorenzo-stacchio/You-Only-Crop-Faces | support_scripts/balance_dataset_face_classifier.py | balance_dataset_face_classifier.py | py | 6,301 | python | en | code | 6 | github-code | 1 |
11811149957 | import nested_admin
from django.contrib import admin
from cms.contexts.admin import AbstractCreatedModifiedBy
from . models import NavigationBar, NavigationBarItem, NavigationBarItemLocalization
class NavigationBarItemLocalizationInline(nested_admin.NestedStackedInline):
model = NavigationBarItemLocalization
... | UniversitaDellaCalabria/uniCMS | src/cms/menus/admin.py | admin.py | py | 2,075 | python | en | code | 5 | github-code | 1 |
74474617953 | import unittest
from orm.unit_tests.my_test import Test_MyTest
import orm
if orm.unit_tests.db_type == 'postgres':
class Test_Postgres_Connect(Test_MyTest):
def setUp(self):
self.db = orm.quick_load('postgres', host='localhost', user='graham', database='orm_test_db')
assert self.db.... | graham/gorm | unit_tests/test_postgres_connect.py | test_postgres_connect.py | py | 994 | python | en | code | 0 | github-code | 1 |
19285672725 | dias = int(input())
ano = 0
meses = 0
qdias = 0
while dias != 0 :
if dias >= 365 :
ano += 1
dias -= 365
elif dias >= 30 :
meses += 1
dias -= 30
elif dias <= 29 :
qdias += + 1
dias -=1
print("%i ano (s)\n%i mes (ses)\n%i dia (s)" % (ano, me... | antoniojpsalves/FATEC_ALP | resp_uri/ex1020.py | ex1020.py | py | 334 | python | pt | code | 0 | github-code | 1 |
10927245542 | import requests
from auth import get_auth_data
from req import consumer_key
auth = get_auth_data()
def add_bookmark(url, title):
res = requests.post("https://getpocket.com/v3/add", json={
"url": url,
"title": title,
"consumer_key": consumer_key,
"access_token": auth["access_token"],
})
if res.status_code... | gebeto/python | pocket-py/api.py | api.py | py | 397 | python | en | code | 2 | github-code | 1 |
31278852115 | """
Center crop all the source images down to 512x512
"""
from PIL import Image
from PIL import ImageOps
import os
SOURCE_DIR = "source_images_blur"
OUT_DIR = "cropped_images_blur"
WIDTH = 512
HEIGHT = 512
for f in os.listdir(SOURCE_DIR):
im = Image.open(os.path.join(SOURCE_DIR, f))
# resize image
w, h ... | cpsiff/stable_diffusion | crop.py | crop.py | py | 847 | python | en | code | 0 | github-code | 1 |
34366237651 | # coding=utf-8
"""Constantes of ZETA Games first App"""
import pygame as pg
import numpy as np
from subprocess import Popen, PIPE
from threading import Thread
from subprocess import call
# Personnalisation de la fenêtre
titre_fenetre = "ZETA GAMES"
image_icone = "images/zeta.png"
w_display = 480
h_display = 270
pg.f... | zeta-technologies/workIP | constantes.py | constantes.py | py | 4,460 | python | en | code | 0 | github-code | 1 |
9529021289 | """add original_taxa_id_to_taxa
Revision ID: 6938832cbce2
Revises: 24bc88e66a5b
Create Date: 2020-10-16 04:57:24.178833
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '6938832cbce2'
down_revision = '24bc88e66a5b'
branch_labels = None
depends_on = None
def up... | eODP/api | migrations/versions/6938832cbce2_add_original_taxa_id_to_taxa.py | 6938832cbce2_add_original_taxa_id_to_taxa.py | py | 863 | python | en | code | 0 | github-code | 1 |
70079041635 | # Feel free to change anything in this code, e.g.
# add or remove variables and functions. If you don't
# like it, you can delete it and start from scratch.
import sys
n = int(sys.stdin.readline())
snake = []
for i in range(0, n):
my_list = []
for j in range(0, n):
if i % 2 == 0:
my_list.a... | lauravarga/training | googleTechLearning/snake.py | snake.py | py | 533 | python | en | code | 0 | github-code | 1 |
23854783061 | """
Gene Neighborhoods
___________________
"""
import logging
import click
from dram2.cli.context import DramContext, DEFAULT_KEEP_TMP, __version__
def find_neighborhoods(
annotations, genes_from_ids, distance_bp=None, distance_genes=None
):
# get neighborhoods as dataframes
neighborhood_frames = list(... | rmFlynn/collection_of_typical_ocoli_samples | dram2/neighbors/__init__.py | __init__.py | py | 5,720 | python | en | code | 0 | github-code | 1 |
20472215584 | import torch
from torch import nn
import torch.nn.functional as F
from typing import List, Callable, ClassVar
from collections import namedtuple
from copy import deepcopy
from .nvidia import PartialConv2d as PC2D
class PartiaLConv2d (nn.Conv2d):
def __init__(self, *args, **kwargs):
super(PartiaLConv2d, se... | source-data/ai | toolbox/models.py | models.py | py | 23,355 | python | en | code | 0 | github-code | 1 |
13913436066 | import numpy as np
import random
class Game():
def __init__(self, env, discount=0.95):
self.env = env
self.observations = []
self.history = []
self.rewards = []
self.policies = []
self.discount = discount
self.done = False
self.observation = env.reset()
self.total_reward = 0
de... | geohot/ai-notebooks | muzero/game.py | game.py | py | 2,933 | python | en | code | 936 | github-code | 1 |
70528196195 | import os
from icrawler.builtin.google import GoogleImageCrawler
max_num = 100
data_root = '/home/vdo-data3/Project/Data/celeb'
if not os.path.exists(data_root):
os.mkdir(data_root)
celeb_name = '여자친구'
celeb_folder = os.path.join(data_root, celeb_name)
if not os.path.exists(celeb_folder):
os.mkdir(celeb_folde... | bigh2000/scripts | 4_google_crawler.py | 4_google_crawler.py | py | 461 | python | en | code | 0 | github-code | 1 |
23467172721 | #!/usr/bin/python3
from brownie import Reentrance, Attack
from scripts.deploy import deploy
from scripts.helpful_scripts import get_account
from colorama import Fore
from web3 import Web3 as w3
# * colours
green = Fore.GREEN
red = Fore.RED
blue = Fore.BLUE
magenta = Fore.MAGENTA
reset = Fore.RESET
# * Rinkeby address... | Aviksaikat/Blockchain-CTF-Solutions | ethernaut/Re-entrance_DONE/scripts/attack.py | attack.py | py | 1,759 | python | en | code | 1 | github-code | 1 |
73911033314 | import sys
import os
import json
import glob
sys.path.append(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'../python/ext-libs'))
from six import string_types
cpp = open(sys.argv[1], "w")
cpp.write(
"#include \"qgsexpression.h\"\n"
"\n"
"QHash<QString, QgsExpression::Hel... | nextgis/nextgisqgis | scripts/process_function_template.py | process_function_template.py | py | 4,209 | python | en | code | 27 | github-code | 1 |
7955053783 | from selenium import webdriver
from commom.BaseTest import Base1
from utils.ReadProperties import Read
from commom.WebDriverEngine import WebDriverEngine
from commom.ElementFinder import ElementFinder
import time
from selenium.webdriver.common.keys import Keys
import unittest
from utils.HTMLTestRunnerEN import HTMLTest... | King-BAT/RanZhi | RanZhiPython/testcase/ranzhi_test.py | ranzhi_test.py | py | 3,045 | python | en | code | 0 | github-code | 1 |
37205546104 | # -*- coding: UTF-8 -*-
import pyee
import logging
import asyncio
import coloredlogs
from enum import Enum
from utils import MockTimeout
from models import dict2obj
from client_network import ClientNetwork
# Format colors in loggers
coloredlogs.DEFAULT_FIELD_STYLES['levelname']['color'] = 'yellow'
coloredlogs.install(... | xBrunoMedeiros/wyd-bot | client_game.py | client_game.py | py | 8,848 | python | en | code | 1 | github-code | 1 |
9356613633 | import re
class wordType():
def __init__(self):
word_capture_re = re.compile(r"^(\D*)\d?\s\s(—?[a-z]+\.)")
with open('words.txt' ,'r') as f:
dictionary = f.read().split('\n')
matched_dic = [word_capture_re.search(a) for a in dictionary]
d = {}
matched_dic = [a for... | jhylands/ingredientProductLinker | wordlists/wordType.py | wordType.py | py | 796 | python | en | code | 0 | github-code | 1 |
34000696236 | # Homework Challenge: FizzBuzz
# Print a list of numbers from 0 to 25, including 25.
# If the number is divisible by 3, print the number and "Fizz".
# If the number is divisible by 5, print the number and "Buzz".
# If the number is divisible by both, print the number and "FizzBuzz“
# If the number is divisible by neith... | czamoral2021/CEBD-1100-CODE-WINTER-2021 | CZ_Homework_Challenge/HomeWork_FizzBuzz.py | HomeWork_FizzBuzz.py | py | 1,701 | python | en | code | 0 | github-code | 1 |
73016827554 | import easy_controls as ec
# buttons = [ec.Text_button(), ec.Rect_button(), ec.Ellipse_button(), ec.Image_button()]
buttons = [ec.Text_button(), ec.Rect_button(), ec.Ellipse_button()]
click = False
def setup():
size(500, 500)
buttons[0].custom(width / 2, height / 2 + 45)
buttons[0].zone(250, 250, 335, 300)... | dmitmel/Space_fighters | easy_controls/easy_controls.pyde | easy_controls.pyde | pyde | 790 | python | en | code | 0 | github-code | 1 |
87462737 | # https://skyeong.net/186
import numpy as np
from sklearn.datasets import fetch_openml
mnist = fetch_openml("MNIST_784")
X = mnist.data / 255.0
y = mnist.target
print (X.shape, y.shape)
import pandas as pd
feat_cols = ['pixel'+str(i) for i in range(X.shape[1]) ]
df = pd.DataFrame(X,columns=feat_cols)
df['label']... | humanscape-sean/TSNE-on-Video-Iframes | tsne_mnist_example.py | tsne_mnist_example.py | py | 1,113 | python | en | code | 0 | github-code | 1 |
25588514888 | # import atexit
import time
import json
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_ATTRIBUTION,CONF_TYPE)
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.con... | syjjx/HA_Esxi | ha_vcenter.py | ha_vcenter.py | py | 25,284 | python | en | code | 10 | github-code | 1 |
17340264805 | import re
from datetime import datetime
import requests
from src import utils
from src.connectors import KafkaClient, PostgreSQLConnector
class SitesAvailability:
"""
A class that fetches metrics from various sites & produces records to Apache Kafka.
Also, it consumes produced records from Kafka and sin... | cnatsis/sites-availability | src/SitesAvailability.py | SitesAvailability.py | py | 3,705 | python | en | code | 0 | github-code | 1 |
34640319155 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework import serializers
from database.models import CollectionItemType
from rest.serializers.object_types import items
from . import types
from rest.serializers.object_types import events
from rest.serializers.object_types import mime_ty... | CONABIO-audio/irekua | irekua/rest/serializers/object_types/data_collections/items.py | items.py | py | 2,281 | python | en | code | 0 | github-code | 1 |
74391649314 | # -*- coding: utf-8 -*-
import functools
#写一个函数装饰器,来缓存函数的值
def cache(func):
cache_dict = {}
# @functools.wraps(func)
def wrapper(*args, **kwargs):
key = repr(*args, **kwargs)
if key in cache_dict:
return cache_dict[key]
else:
#使用cache_dict缓存同一个sql的结果
... | hello-wn/python-basic-scripts | 20180425/use_decorator_cacheValue.py | use_decorator_cacheValue.py | py | 943 | python | en | code | 0 | github-code | 1 |
40888591974 | # ---
# jupyter:
# jupytext:
# cell_metadata_json: true
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.4.2
# kernelspec:
# display_name: Python [conda env:anaconda-spark30_prev2]
# langu... | Hoeze/firefly | scripts/AggregateVEP.py | AggregateVEP.py | py | 15,105 | python | en | code | 0 | github-code | 1 |
2529084280 | import tensorflow as tf
import cPickle
import numpy as np
def assign_as_blocks_v2(a,b):
shape1 = tf.shape(a)
shape2 = tf.shape(b)
m1 = shape1[0]
n1 = shape1[1]
m2 = shape2[0]
n2 = shape2[1]
p1 = tf.tile(a,[1,n2])
p2 = tf.reshape(tf.tile(tf.expand_dims(b, 1... | upadhysh/GANs-for-NEWS-recomendation | dis_model.py | dis_model.py | py | 6,233 | python | en | code | 1 | github-code | 1 |
22193624498 | import openai
from src.models import ModelFinder
from src.ai.config import CODE_DEFAULT_MAX_TOKENS, CODE_DEFAULT_TEMPERATURE
class CodePromptResult:
def __init__(self, result: str, used_tokens: int) -> None:
self.result = result
self.used_tokens = used_tokens
def code_prompt(
input: str,
... | AgustinMDominguez/Prompt | prompter/src/ai/code.py | code.py | py | 825 | python | en | code | 0 | github-code | 1 |
69997512993 | from notifypy import Notify
from PySimpleGUI import PySimpleGUI as sg
# 1 ciclo pomodoro = 25 min = 1500 segundos
# OK exibir tempo restante do ciclo na tela
# OK exibir quantidade de ciclos
# OK ao finalizar ciclo, tocar som de alerta COM notificação
# Após 1 ciclo, realizar pausa de 5 min = 300 segundos
# - ao fin... | dan-alvares/Pomodoro-Notipyer | pomodoro.py | pomodoro.py | py | 3,585 | python | pt | code | 0 | github-code | 1 |
37869013076 | import numpy as np
import pandas as pd
import cv2
from sklearn.model_selection import train_test_split
import tensorflow as tf
import keras
from keras.models import Model
from keras.models import load_model
from keras.layers import Input, Dense, Concatenate
from keras.layers import Dense, GlobalAveragePooling2D, Dropou... | anton500nb/ship_detection | model.py | model.py | py | 9,000 | python | en | code | 0 | github-code | 1 |
29568221843 | # -*- coding: utf-8-*-
'''
First script
'''
from pathlib import Path
import sys
import argparse
pathSearch = Path('.').resolve().as_posix()
sys.path.append(pathSearch)
# -----------------------------------------
description='''This is a description of what the script does.
This script:
- is to show how the 'argp... | kemal332/entry | testScript.py | testScript.py | py | 1,390 | python | en | code | null | github-code | 1 |
2110189508 | from LockerAssignment.repository import locker_repository
from LockerAssignment.controller import unlock_controller, request_controller, cancel_controller, quit_controller
class LockerSystem:
optionControllers: dict
locker_repository: locker_repository.LockerRepository
def __init__(self):
self.lo... | DennisSnijder/HU-PROG-1 | LockerAssignment/main.py | main.py | py | 2,012 | python | en | code | 0 | github-code | 1 |
21097040793 | # Hash-backed maps
from queue import Queue
dictionary = {
"harry": 101,
"garry": 102,
"larry": 103
}
print(dictionary["harry"])
dictionary["larry"] = 104
# all keys
for x in dictionary:
print(x)
# all values
for x in dictionary:
print(dictionary[x])
print("-----------------------")
# Queue
# Init... | slashharsh/Python | Coding/Python_essentials.py | Python_essentials.py | py | 955 | python | en | code | 0 | github-code | 1 |
24877020550 | # coding: utf-8
"""
Ctypes wrapper module for BUSMUST CAN Interface on win32/win64 systems.
Authors: busmust <busmust@126.com>, BUSMUST Co.,Ltd.
"""
# Import Standard Python Modules
# ==============================
import ctypes
import logging
import sys
import time
try:
# Try builtin Python 3 Windows API
f... | Aceinna/acenav-cli | src/aceinna/devices/widgets/can/interfaces/bmcan/canlib.py | canlib.py | py | 13,564 | python | en | code | 2 | github-code | 1 |
986799681 | import os
import sys
import shutil
import time
import random
import torch
import logging
from pathlib import Path
import numpy as np
import statistic
from torch import multiprocessing
from torch.nn import functional as F
import nibabel as nib
from tensorboardX import SummaryWriter
from skimage.measure import label
de... | DeepMed-Lab-ECNU/BCP | code/pancreas/pancreas_utils.py | pancreas_utils.py | py | 9,038 | python | en | code | 84 | github-code | 1 |
13597188904 | import pandas as pd
import numpy as np
from tensorflow.keras.models import model_from_json
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array
df = pd.read_csv('../data/sample.csv')
# Model reconstruction from JSON file
with open('../data/model_archi... | Abhishek150598/Cell_classifier | src/predict.py | predict.py | py | 1,042 | python | en | code | 0 | github-code | 1 |
38367714869 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 21 13:23:27 2017
Plots two mass spectra on one set of axes and notates m/z of the peak(s)
with the highest relative intensity.
@author: emeryusher
"""
# import python modules for plotting etc.
import numpy as np
import matplotlib.pyplot as plt
fro... | idpemery/random-python-scripts | MS_ref_overlay.py | MS_ref_overlay.py | py | 2,275 | python | en | code | 0 | github-code | 1 |
20148737612 | #!/usr/bin/env python3
from enum import Enum
from copy import deepcopy
import sys
import readline # make input() use readline <3
CODE_BASE_ADDR = 0x1000 # where code is loaded
MEMORY_SIZE = 0xFFFF # How big memory is
INSTR_PTR_LOC = 0x0
STACK_PTR_LOC = 0x1
BASE_PTR_LOC = 0x2
class InstructionFamily(Enum):
IMM = ... | Hypersonic/CyberTronix64k | ct64k_dbg.py | ct64k_dbg.py | py | 21,766 | python | en | code | 9 | github-code | 1 |
23829749926 | try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
config = {
'description': 'SNAPS OpenStack Installer',
'author': 'Steve Pisarski',
'url': 'https://github.com/cablelabs/snaps-openstack',
'download_url': 'https://github.com/cablelabs/snaps-ope... | cablelabs/snaps-openstack | setup.py | setup.py | py | 667 | python | en | code | 9 | github-code | 1 |
31891970363 | from termcolor import cprint
from tkinter import *
from ttkthemes import themed_tk
from tkinter import ttk , messagebox, filedialog
from PIL import Image, ImageTk
vendara = ['Vendara', 14]
root = themed_tk.ThemedTk()
root.geometry('900x600+500+200')
root.title('Admission-helper: Administrator Version')
root.set_theme(... | Advik-B/Admission-helper | main.py | main.py | py | 2,112 | python | en | code | 3 | github-code | 1 |
11981080026 | from decimal import Decimal
from django.db import models
from django_countries.fields import CountryField
class Partner(models.Model):
uid = models.AutoField(primary_key=True)
partner_id = models.CharField(
max_length=3,
unique=True,
error_messages={"unique": "This Partner ID is alrea... | yezz123/My-Business | partners/models.py | models.py | py | 2,687 | python | en | code | 45 | github-code | 1 |
32958345548 | from argparse import ArgumentParser
from time import sleep
from src.netreq import setContractAddress, requestPrice, requestSymbol
from src.grapher import setGraphSymbol, startGraphThread,addPrice, initanim
from src.contracts import contract_list
import threading
def priceThread():
while True:
price = reque... | gAtrium/acpy | acpy.py | acpy.py | py | 1,591 | python | en | code | 0 | github-code | 1 |
7580183535 | # BOJ_18870
# 좌표 압축
import sys
def solution():
n = int(sys.stdin.readline())
arr = [[i] for i in range(n)]
in_arr = list(map(int, sys.stdin.readline().split()))
for i in range(n):
arr[i].append(in_arr[i])
arr[i].append(0)
arr.sort(key=lambda x: x[1])
for i in range(1, n):
... | wilderif/PS | BOJ/BOJ_18870.py | BOJ_18870.py | py | 565 | python | en | code | 0 | github-code | 1 |
27104480429 | import sys
filename = sys.argv[1]
lines = []
with open(filename) as f:
lines = f.read().splitlines()
print("starting part1")
def unique(pkt,sze):
i = 0
while i < len(pkt)-sze:
if len(set(pkt[i:i+sze])) == sze:
return i+sze
i+=1
return(-1)
for pkt in lines:
print(unique... | benjm/aoc2022 | day06/solution.py | solution.py | py | 399 | python | en | code | 0 | github-code | 1 |
72625343714 | import json
import csv
import requests
from bs4 import BeautifulSoup
# ▒█▀▄▒█▀▄ lab. PR | FAF | FCIM | UTM | Fall 2023
# ░█▀▒░█▀▄ FAF-212 Cristian Brinza lab2 homework
print('')
print('▒█▀▄▒█▀▄ lab. PR | FAF | FCIM | UTM | Fall 2023')
print('░█▀▒░█▀▄ FAF-212 Cristian Brinza lab2 homework ')
print('')
# User-Ag... | CristianBrinza/UTM | year3/pr/lab2/homework.py | homework.py | py | 7,543 | python | en | code | 3 | github-code | 1 |
1954882437 | import Person
from Node import Node
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def add(self, e):
newNode = Node(e)
if self.size == 0:
self.head = newNode
self.tail = newNode
else:
... | xoth42/CS160 | Lab/6/LinkedList.py | LinkedList.py | py | 4,085 | python | en | code | 0 | github-code | 1 |
845849150 | # _*_ coding:utf-8 _*_
# __author__ : 'aj'
# __date__ : '2017/12/12 下午5:59'
from .models import AskUser, CourseComponent, UserFavorite, UserMessage, UserCourse
import xadmin
class AskUserAdmin(object):
list_display = ['name', 'mobile', 'cursor_name', 'add_time']
filter_fields = ['name', 'mobile', 'cursor_na... | WuliQiangWu/django_study | apps/operation/adminx.py | adminx.py | py | 1,458 | python | en | code | 0 | github-code | 1 |
30020287097 | import os
from random import randint
from functools import partial
from datetime import datetime
from config.log_config import LogConfig
from config.pong_enum import PathEnum, ButtonNamesEnum
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.boxlay... | ivan1dze/kivy | main.py | main.py | py | 10,431 | python | en | code | 0 | github-code | 1 |
24203756592 | # uniq
import sys
if __name__ == '__main__':
prevLine = "?"
firstTime = True
for line in sys.stdin:
#strip CR, LF
line = line.strip('\n')
line = line.strip('\r')
# print 1st always
if firstTime :
prevLine = line
firstTime = Fa... | sylabtechnologies/October_test | SQLTest/03_Uniq.py | 03_Uniq.py | py | 464 | python | en | code | 0 | github-code | 1 |
22518135513 | import os
# os.environ['CUDA_VISIBLE_DEVICES'] = "0" # in case you are using a multi GPU workstation, choose your GPU here
import tqdm
import pytorch_lightning as pl
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.nn.functional as F
import pandas as pd
from datasets import ... | microsoft/LMOps | promptist/aesthetic/train_predictor.py | train_predictor.py | py | 5,077 | python | en | code | 2,623 | github-code | 1 |
10744024261 | import sys
args = sys.argv
x = int(args[1])
y = str(args[2])
cnt = 0
for i in range(2**x):
s = ''
for j in range(x):
if((i >> j) & 1):
s += 'M'
else:
s += 'V'
if y in s:
cnt += 1
print(cnt)
| mnanri/4atcoder | atcoder/others/cpad1.py | cpad1.py | py | 223 | python | en | code | 0 | github-code | 1 |
20192955923 | row = int(input("Enter how many rows you want: "))
sum1 = 0
sum2 = 0
sum3 = 0
InputMatrix = []
for i in range(0,row):
a = []
for j in range(0,3):
val = int(input())
a.append(val)
InputMatrix.append(a)
print("This is the Matrix you have inserted: ")
for i in range(0,row):... | SadbinShakil/Worst_Way_To_Solve_CodeForces_Problems | Young_Physicist.py | Young_Physicist.py | py | 1,141 | python | en | code | 1 | github-code | 1 |
6897367210 | import argparse
import ast
import io
import os.path
import shlex
import shutil
import subprocess
import sys
import textwrap
import urllib.parse
def get_url_filename(url, suffix):
filename = urllib.parse.urlparse(url).path
filename = filename.split('/')[-1]
if not filename.endswith(suffix):
raise E... | vstinner/pythonci | pythonci/_ci.py | _ci.py | py | 12,377 | python | en | code | 4 | github-code | 1 |
23325323640 | from unittest import TestCase
import detection
from config import *
import traceback
class TestDetection(object):
def test_detect_embedding_based_process_monitor(self):
# monitor = detection.DetectionMonitor(VIDEO_CONFIG_DIR / 'video.json', STREAM_SAVE_DIR, CANDIDATE_SAVE_DIR)
monitor = detection... | LuletterSoul/DolphinDetection | test/test_detection.py | test_detection.py | py | 1,699 | python | en | code | 6 | github-code | 1 |
73902094113 | class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self, head=None, tail=None):
self.head = head
self.tail = tail
# umiesci nowy wezel na poczatku listy
def push(self, value):
new_node = Nod... | MadPapa/AiSD | linked_list/linked_list.py | linked_list.py | py | 4,916 | python | en | code | 0 | github-code | 1 |
18722144626 | """
@package square_connect.report.management.commands.get_recent_transactions
Gets the most recent transactions from the primary storefronts and adds any selected items to the report database.
We recommend that you run it in a cron job.
"""
from django.core.management.base import BaseCommand, CommandError
from django... | TrianglePlusPlus/howitzer | square_connect/square_connect/report/management/commands/get_recent_transactions.py | get_recent_transactions.py | py | 1,410 | python | en | code | 1 | github-code | 1 |
29110585681 | #-*- encoding: UTF-8 -*-
import urllib
from AlyMoly.reporte.excepciones import AbstractClassException
from AlyMoly.settings import REPORT_HOST, REPORT_PORT, REPORT_APP, REPORT_DIR,\
NOMBRE_SUCURSAL, CANTIDAD_PRODUCTOS_MAS_VENDIDOS,\
CANTIDAD_PROMOCIONES_MAS_VENDIDAS
from AlyMoly... | CreceLibre/alymoly | AlyMoly/reporte/clases.py | clases.py | py | 10,496 | python | es | code | 0 | github-code | 1 |
31669588144 | # -*- coding: utf-8 -*-
# !/usr/bin/env python
# @Time : 2019-08-06 16:16
# @Author : lidong@immusician.com
# @Site :
# @File : base.py
import requests
from UnitTest.settings import HOST, PORT, HEADERS
class BaseResponse:
def __init__(self):
pass
class BaseRequest:
def __init__(self, host... | Fushengliangnian/PracticeEssays | UnitTest/base.py | base.py | py | 1,821 | python | en | code | 2 | github-code | 1 |
19194610924 | #YAPI Rewrite - Yet Another Package Manager
#Imports
import modules.config_import as config_import
import modules.installer as installer
import gui.interface as interface
import modules.search as search
import json
import sys
import os
try:
os.chdir(os.path.dirname(__file__)) #Change file location if outside of YA... | Wabri/rewrite | yapi.py | yapi.py | py | 1,975 | python | en | code | 3 | github-code | 1 |
15889711723 | import os
import sys
import importlib
import datetime
import time
import shutil
import numpy as np
import pandas as pd
from pathlib import Path
from evidence.post_processing import postprocess
# UltraNest imports
try:
from ultranest import ReactiveNestedSampler
import ultranest.stepsampler
except ImportError:... | nicochunger/evidence | evidence/ultranest/__init__.py | __init__.py | py | 14,333 | python | en | code | 2 | github-code | 1 |
8343142681 | from bs4 import BeautifulSoup
import requests
country = raw_input("Enter the country:")
#print(country)
site_to_scrape = "https://en.wikipedia.org/wiki/List_of_national_capitals_and_largest_cities_by_country"
r = requests.get(site_to_scrape)
data = r.text
soup = BeautifulSoup(data)
print("Capital: "+soup.find('a',ti... | deathBlad3/capitalCities | capitalCity.py | capitalCity.py | py | 373 | python | en | code | 0 | github-code | 1 |
27390989814 | import sys
student_file = 'lab7.py'
f = open(student_file)
lines = f.readlines()
f.close()
lines = [line.strip() for line in lines]
lines = ['' if line.startswith('#') else line for line in lines]
code_clean = True
for i in range(len(lines)):
if 'import' in lines[i] and not lines[i].endswith('math'):
... | TyuiX/UndergradCodingHomeWork | lab7_tester.py | lab7_tester.py | py | 2,691 | python | en | code | 0 | github-code | 1 |
20838574752 | from cases import *
import pandas as pd
import scipy.io
import sys
def compare_cases():
coefs=scipy.io.loadmat("../data/timeseries.mat")
trend_coefs=pd.read_csv("../data/trends.csv")
season_coefs=pd.read_csv("../data/season.csv")
num_years=1
start_year=2020
num_simulations=100
seed=0
par... | schraderSimon/NorwayGermanyProject | code/testfunctions.py | testfunctions.py | py | 4,835 | python | en | code | 0 | github-code | 1 |
71927427553 | '''
Guilherme Araújo Mendes de Souza - 156437
UNIFESP - ICT
AED 2
'''
import time
def separa(p, r, v):
c = v[r]
j = p
for k in range(p, r):
if v[k] <= c:
t = v[j]
v[j] = v[k]
v[k] = t
j += 1
v[r] = v[j]
v[j] = c
return j
... | Gu1lh3rm3-Arauj0/Algoritmos-e-Estruturas-de-Dados-II | Trabalho 1/Quicksort.py | Quicksort.py | py | 915 | python | pt | code | 0 | github-code | 1 |
43444307075 | from datetime import datetime, timedelta
import random
import re
import wsgiref.handlers
import cgi
import base64
from google.appengine.api import xmpp
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.ereporter import report_gen... | AdamClements/MrsDoyle | app/mrsdoyle.py | mrsdoyle.py | py | 9,138 | python | en | code | 14 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.