seq_id stringlengths 7 11 | text stringlengths 156 1.7M | repo_name stringlengths 7 125 | sub_path stringlengths 4 132 | file_name stringlengths 4 77 | file_ext stringclasses 6
values | file_size_in_byte int64 156 1.7M | program_lang stringclasses 1
value | lang stringclasses 38
values | doc_type stringclasses 1
value | stars int64 0 24.2k ⌀ | dataset stringclasses 1
value | pt stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
41373317914 | from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
username = models.CharField(max_length=100)
email = models.EmailField(unique=True)
fecha_nacimiento = models.CharField(max_length=10, blank=True, null=... | isabellaaguilar/ProyectoFinal-Turisteo-Cultural | backend_api/api/models.py | models.py | py | 2,026 | python | en | code | 0 | github-code | 6 |
2795680906 | #PCA => Principal componet analysis using HSI
import math
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.decomposition import KernelPCA
class princiapalComponentAnalysis:
def __init__(self):
pass
def __str__(self):
pass
def pca_c... | davidruizhidalgo/unsupervisedRemoteSensing | package/PCA.py | PCA.py | py | 6,139 | python | es | code | 13 | github-code | 6 |
8665123714 | # -*- coding: utf-8 -*-
import os
import boto3
import settings
from jsonschema import validate, ValidationError
from cognito_trigger_base import CognitoTriggerBase
from user_util import UserUtil
from private_chain_util import PrivateChainUtil
class CustomMessage(CognitoTriggerBase):
def get_schema(self):
... | AlisProject/serverless-application | src/handlers/cognito_trigger/custommessage/custom_message.py | custom_message.py | py | 5,666 | python | ja | code | 54 | github-code | 6 |
3940897296 | import numpy as np
import torch
from torchvision import models
import torch.nn as nn
# from resnet import resnet34
# import resnet
from torch.nn import functional as F
class ConvBnRelu(nn.Module):
def __init__(self, in_planes, out_planes, ksize, stride, pad, dilation=1,
groups=1, has_bn=True, norm... | Winterspringkle/EIANet | models/master.py | master.py | py | 5,598 | python | en | code | 0 | github-code | 6 |
30011949474 | from flask import Blueprint, request, abort
from epmanage.lib.auth import AuthController, AuthException
auth_component = Blueprint('auth_component', __name__)
@auth_component.route('/', methods=['POST'])
def auth_do():
"""Perform authentication"""
try:
return AuthController.get_token_agent(request.j... | PokeSec/EPManage | epmanage/auth/auth.py | auth.py | py | 642 | python | en | code | 1 | github-code | 6 |
73730902266 | import tensorflow as tf
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import pandas as pd
from NS_model_tf import Sampler, Navier_Stokes2D
if __name__ == '__main__':
def U_gamma_1(x):
num = x.shape[0]
return np.tile(np.arr... | PredictiveIntelligenceLab/GradientPathologiesPINNs | Lid-driven Cavity/NS.py | NS.py | py | 6,568 | python | en | code | 134 | github-code | 6 |
35694932356 | # pylint: disable=E1111
from faker import Faker
from src.infra.entities import Pet as PetModel
from src.infra.config.db_config import DBConnectionHandler
from src.infra.entities.pet import AnimalTypes
from .pet_repository import PetRepository
faker = Faker()
pet_repository = PetRepository()
db_connection_handle = DB... | YuryTinos/backend-python | src/infra/repo/pet_repository_test.py | pet_repository_test.py | py | 1,976 | python | en | code | 0 | github-code | 6 |
11878624496 | """
Given two integers r and c, indicating the number of rows and columns, print a two-dimensional matrix such that the elements of the matrix are in an increasing sequence from 1 to rXc, in a row-major order.
Input Format:
First line of the input contains two space separated integers indicating the rows and col... | HrideshSingh/PythonPrograms | Matrix.py | Matrix.py | py | 712 | python | en | code | 0 | github-code | 6 |
11485171714 | #epidemics.py
import networkx as nx
import random
class Model_ep:
def __init__(self, dyngraph, infected):
self.G = dyngraph
self.I = infected
self.S = []
self.R = []
self.E = []
self.beta = 0.5
self.gamma = 0.5
# self.model = model
self.states = {}
self.nodes = []
self.nodestate = zip(self.nodes... | farzana0/graph-epidemics | epidemics.py | epidemics.py | py | 1,553 | python | en | code | 0 | github-code | 6 |
11932429947 | from module.program import program
from module.convert import convert
from module.openFileJson import openFileJson
def main():
condition = True
while condition :
question = int(input('Pilih menu berikut :\n1. Convert File\n2. Automated Post-Test\nPilih Salah satu :\n'))
if question == 1 :
... | bangef/pz | python/post-test/main.py | main.py | py | 756 | python | en | code | 0 | github-code | 6 |
73019294587 | #!/bin/python3
import sys
import csv
from pysam import VariantFile
import subprocess
vcf_in = VariantFile(sys.argv[1])
multiVcf = VariantFile(sys.argv[2])
new_header = vcf_in.header
# new_header.generic.add("Multi allelic variants added from Pisces.")
vcf_out = VariantFile(sys.argv[3], 'w', header=new_header)
for re... | clinical-genomics-uppsala/pomfrey | src/variantCalling/multiallelicAdd.py | multiallelicAdd.py | py | 612 | python | en | code | 0 | github-code | 6 |
39249804904 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
ans = []
def preorder(root):
if root is not None:
ans.append(root.val)
if root.left:
preorder(root.left)
if roo... | midnightbot/snapalgo | snapalgo/template_generator/preorder.py | preorder.py | py | 375 | python | en | code | 2 | github-code | 6 |
19795243462 | import csv
from collections import defaultdict, OrderedDict
import itertools
import json
class clicknode:
node_count = itertools.count()
group_count = itertools.count()
group_map = {}
def __init__(self, **nodedict):
group = nodedict['REGION_VIEW_ID']
if group not in clicknode.group_map:
clicknode.group_ma... | arbazkhan002/Clix | clickparser.py | clickparser.py | py | 5,102 | python | en | code | 0 | github-code | 6 |
37516858475 | import os
import tarfile
import time
import shutil
from scipy.io import loadmat
import csv
DEVKIT_FILE_NAME = "ILSVRC2012_devkit_t12.tar.gz"
TRAIN_FILE_NAME = "ILSVRC2012_img_train.tar"
VAL_FILE_NAME = "ILSVRC2012_img_val.tar"
TEST_FILE_NAME = "ILSVRC2012_img_test_v10102019.tar"
def untar(file, target_dir="", is_show... | lizhouyu/ImageNet-Parser | imagenet.py | imagenet.py | py | 5,306 | python | en | code | 0 | github-code | 6 |
43967535036 |
def fasta_from_SAR_dict(sar_dict,fa_file):
""" makes a multi fasta with candidates from SAR dictionary """
with fa_file as f:
for data in sar_dict.values():
f.writelines(">{}\n".format(data["description"]))
f.writelines("{}\n".format(data["sequence"]))
def gff3_from_SAR_dict(sa... | TAMU-CPT/galaxy-tools | tools/SAR/file_operations.py | file_operations.py | py | 6,173 | python | en | code | 5 | github-code | 6 |
41244789670 | from datetime import date
ano_atual = date.today().year
nascimento = int(input('Digite seu ano de nascimento: '))
idade = ano_atual - nascimento
if idade == 18:
print('Se alistar')
elif idade < 18:
saldo = 18 - idade
print('ainda faltam {} anos(s) para se alistar'.format(saldo))
ano = ano_atual + sa... | andrematos90/Python | CursoEmVideo/Módulo 2/Desafio 039B.py | Desafio 039B.py | py | 570 | python | pt | code | 0 | github-code | 6 |
71971270909 | import tempfile
import os
import posixpath
import stat
import logging
import collections
from kubeflow.fairing import utils as fairing_utils
from kubeflow.fairing.preprocessors.base import BasePreProcessor
from kubeflow.fairing.builders.append.append import AppendBuilder
from kubeflow.fairing.deployers.job.job import ... | kubeflow/fairing | kubeflow/fairing/frameworks/lightgbm.py | lightgbm.py | py | 14,637 | python | en | code | 336 | github-code | 6 |
7748783174 | import cv2
from cvzone.HandTrackingModule import HandDetector
import numpy as np
import pyfirmata
cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)
if not cap.isOpened():
print("Camera couldn't access")
exit()
detector = HandDetector(detectionCon=0.7)
port = "COM7"
board = pyfirmata.Arduino(port)
... | rizkydermawan1992/virtualdragdrop | drag and drop.py | drag and drop.py | py | 1,936 | python | en | code | 5 | github-code | 6 |
37617555944 | from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import HttpResponse
from .models import Product
from math import ceil
# Create your views here.
def index(request):
#products = Product.objects.all()
#n = len(products)
allProds = []
catprods = Pr... | a22616/Django-project-2 | shopcart/shop/views.py | views.py | py | 1,244 | python | en | code | 0 | github-code | 6 |
8384182801 | from __future__ import absolute_import
import sys
from optparse import OptionParser
import sumolib # noqa
from functools import reduce
def parse_args():
USAGE = "Usage: " + sys.argv[0] + " <netfile> [options]"
optParser = OptionParser()
optParser.add_option("-o", "--outfile", help="name of output file")... | ngctnnnn/DRL_Traffic-Signal-Control | sumo-rl/sumo/tools/generateBidiDistricts.py | generateBidiDistricts.py | py | 3,730 | python | en | code | 17 | github-code | 6 |
36618145736 | #!/usr/bin/env python3
import copy
import json
import logging
import os
import psutil
import shutil
import sys
import tempfile
from datetime import datetime
# import pysqlite3
from joblib import Parallel, delayed, parallel_backend
from tabulate import tabulate
from . import utils
from .config import Config
class P... | beherap/pipelinewise | pipelinewise/cli/pipelinewise.py | pipelinewise.py | py | 55,124 | python | en | code | 0 | github-code | 6 |
41983296819 | """
This is the name of the park to be used as an app-wide constant
"""
PARK_NAME = "Copington Adventure Theme Park"
TICKET_PRICES = {
"child": 12,
"adult": 20,
"senior": 11,
}
WRISTBAND_PRICE = 20
MAXIMUM_PARK_CAPACITY = 500
| alii/copington-ticket-theme-park | utils/constants.py | constants.py | py | 241 | python | en | code | 2 | github-code | 6 |
21393275553 | s = {'x', 'y', 'b', 'c', 'a'}
for item in s:
print(item)
# the order of elements is unknow.
class Squares:
def __init__(self, length):
self.length = length
self.i = 0
def __iter__(self):
print("calling __iter__")
self.i = 0
return self
... | Hopw06/Python | Python_Deep_Dive/Part 2/4.IterablesAndIterators/1.IteratingCollections.py | 1.IteratingCollections.py | py | 680 | python | en | code | 0 | github-code | 6 |
29465188143 | # Take an array and remove every second element from the array.
# Always keep the first element and start removing with the next element.
# Example:
# ["Keep", "Remove", "Keep", "Remove", "Keep", ...] --> ["Keep", "Keep", "Keep", ...]
# None of the arrays will be empty, so you don't have to worry about that!
def re... | tuyojr/code_wars-hacker_rank-leetcode | code_wars/remove_every_other.py | remove_every_other.py | py | 1,136 | python | en | code | 0 | github-code | 6 |
12970955601 | import socket
import time
def SendRec(mode,namefile):
client = socket.socket()
client.connect(('127.0.0.1',1222))
print("Connect to server!")
client.send(mode)
print("sent mode to server!")
time.sleep(3)
client.send(namefile)
print("sent name of file to server!")
time.sleep(3)
... | MDoroudgarian/fileserverpy | client/client.py | client.py | py | 1,096 | python | en | code | 1 | github-code | 6 |
32188154157 | # 6-5.py 파이썬의 장점을 살린 퀵 정렬 소스코드
array = [5, 7, 9, 0, 3, 1, 6, 2, 4, 8]
def quick_sort(array):
# 리스트의 길이가 1이하라면 반환
if len(array) <= 1:
return array
pivot = array[0] # 피벗 <- 첫번째 원소
tail = array[1:] # 피벗 이후의 리스트
left_side = [x for x in tail if x <= pivot] # 분할된 왼쪽
right_side = [x for... | kcw0331/python-for-coding-test | thisiscodingtest/정렬(파이썬의장점을살린퀵정렬).py | 정렬(파이썬의장점을살린퀵정렬).py | py | 636 | python | ko | code | 0 | github-code | 6 |
15917640785 | from django.urls import path
from . import views
app_name = 'main'
urlpatterns = [
path('category_list/', views.category_list, name='category_list'),
path('delete_category/<int:category_id>/', views.delete_category, name='delete_category'),
path('update_category/<int:category_id>/', views.update_c... | elumes446/Store-Management-System | Store Managment System/main/urls.py | urls.py | py | 1,173 | python | en | code | 0 | github-code | 6 |
28130211082 | ## import that shit babyyy
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton,QStackedWidget,QScrollArea, QProgressBar, QHBoxLayout, QLineEdit
from PyQt5.QtCore import QObject, QThread, pyqtSignal,Qt
# from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg
from os.path impor... | BadCodeswJamie/Sponitor | sponitor.py | sponitor.py | py | 68,332 | python | en | code | 0 | github-code | 6 |
24128542933 | import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import numpy as np
import pickle
with open("/home/ekin/Desktop/workspace/RotatetObjectDetectionReview/test_data/gt_area.pickle", 'rb') as handle:
gt_area = pickle.load(handle)
np.sort(gt_area)
'''
plt.hist(gt_area, bins='auto', edgecolor='black')
... | ikoc/RotatetObjectDetectionReview | src/kMeansOfArea.py | kMeansOfArea.py | py | 1,058 | python | en | code | 0 | github-code | 6 |
11194307443 | from typing import Tuple, Optional
import albumentations as A
import cv2
import numpy as np
import torch
import torchvision
from torch.utils.data import Dataset
import os
from PIL import Image
from tqdm import tqdm
import pandas as pd
import pywt
import logging
from utils.image_utils import random_crop_with_transforms... | AlexeySrus/WPNet | research_pipelines/supersampling_with_wavelets/dataloader.py | dataloader.py | py | 4,411 | python | en | code | 0 | github-code | 6 |
30114979232 | import itertools
import pandas as pd
import math
from pathlib import Path
def composite_SD(means, SDs, ncounts):
'''Calculate combined standard deviation via ANOVA (ANalysis Of VAriance)
See: http://www.burtonsys.com/climate/composite_standard_deviations.html
Inputs are:
means, the array of... | superyang713/Synthetic_Data_Generation | utils.py | utils.py | py | 2,363 | python | en | code | 0 | github-code | 6 |
3814572161 | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import numpy as np
df = pd.read_csv('mail_data.csv')
# Data Preprocessing
df['Ca... | bhar1gitr/ML_Spam-Ham_Detector | pandassss.py | pandassss.py | py | 1,653 | python | en | code | 0 | github-code | 6 |
18846943134 | import logging
from concurrent import futures
from threading import Timer
from functools import partial
import cloud.blockstore.public.sdk.python.protos as protos
from .error_codes import EResult
from .error import ClientError, _handle_errors, client_error_from_response
from .grpc_client import GrpcClient
from .http... | ydb-platform/nbs | cloud/blockstore/public/sdk/python/client/discovery.py | discovery.py | py | 13,730 | python | en | code | 32 | github-code | 6 |
72165174909 | # -*- coding:utf-8 -*-
# ! usr/bin/env python3
"""
Created on 28/12/2020 9:16
@Author: XINZHI YAO
"""
import os
import argparse
def pubtator_split(pubtator_file: str, num_per_file: int,
save_path: str):
if not os.path.exists(save_path):
os.mkdir(save_path)
split_... | YaoXinZhi/BioNLP-Toolkit | Split_PubTator_File.py | Split_PubTator_File.py | py | 1,971 | python | en | code | 2 | github-code | 6 |
19923413937 | from random import randint
from time import sleep
from operator import itemgetter
jogadores = {'jogador1': randint(1, 6),
'jogador2': randint(1, 6),
'jogador3': randint(1, 6),
'jogador4': randint(1, 6)}
ranking = list()
for k, v in jogadores.items():
print(f'O {k} tirou o dad... | samuelfranca7l/PythonExercises | exercicios/PythonExercicios_Desafio091.py | PythonExercicios_Desafio091.py | py | 511 | python | pt | code | 0 | github-code | 6 |
17139183231 | #https://leetcode.com/problems/find-the-duplicate-number/
"""Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one repeated number in nums, return this repeated number.
You must solve the problem without modifying the array nums and uses only ... | Eswar133/Practice | Find the Duplicate Number.py | Find the Duplicate Number.py | py | 794 | python | en | code | 0 | github-code | 6 |
33937878041 | """
Simple animation for your shell
"""
from field import Field
import time
import random
from saver import Ball, Saver
class MaskSaver(Saver):
def __init__(self, balls=int(random.random() * 100), trail=" ", mask=None):
self.field = Field(title="Term Saver")
self.balls = [Ball(x=int(random.random(... | cameronbriar/curses | examples/saver.mask.py | saver.mask.py | py | 2,985 | python | en | code | 0 | github-code | 6 |
1447221561 | from django.shortcuts import render
from .forms import ProductCreationForm
from .models import Product
from django.contrib import messages
import random
# Create your views here.
def create(request):
if request.method == 'POST':
form = ProductCreationForm(request.POST, request.FILES)
if form.is_v... | Thorium0/IntelRobotics-webserver | products/views.py | views.py | py | 1,284 | python | en | code | 0 | github-code | 6 |
15191647327 | import matplotlib.pyplot as plot
from pymongo import MongoClient
import numpy as np
from sys import argv
import random
from constants import CONNECTION_STRING, DATABASE_NAME, CLUSTER_COLLECTION_NAME, GENRE_K_DICT
from q2 import get_k_g, main as q2_main, client as client2
from q3 import main as q3_main, client as clien... | GautamGadipudi/bd-assignment-8 | q5.py | q5.py | py | 2,250 | python | en | code | 0 | github-code | 6 |
71359830907 | from decimal import Decimal
import ffmpeg
import math
import gc
def get_aspect_ratio(width, height):
gcd = math.gcd(width, height)
lhs = int(width / gcd)
rhs = int(height / gcd)
return f"{lhs}x{rhs}"
def get_raw_duration(video):
duration_raw = None
# check framerate at index 0 and 1, because... | bennischober/MetaDataScraper | src/media/read_media.py | read_media.py | py | 3,958 | python | en | code | 0 | github-code | 6 |
35846798880 | import sys
import cv2 as cv
__doc__ = """Wrapper to create new classifiers from OpenCV or other libraries.
"""
class NormalBayes(object):
"""Wraps a trained OpenCV Normal Bayes Classifier.
More info: http://docs.opencv.org/modules/ml/doc/normal_bayes_classifier.html
"""
def __init__(self):
... | mmikulic/ProjektRasUzo | src/classifier.py | classifier.py | py | 4,064 | python | en | code | 0 | github-code | 6 |
11314663313 | from django.contrib.auth import get_user_model
from django.db import models
User = get_user_model()
class Group(models.Model):
title = models.CharField('название группы', max_length=200)
slug = models.SlugField('слаг', unique=True)
description = models.TextField('описание')
class Meta:
verbo... | zzstop/hw05_final | posts/models.py | models.py | py | 2,692 | python | en | code | 0 | github-code | 6 |
2872612166 | from flask import Flask, render_template, redirect, url_for, request
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, FloatField
from wtforms.validators import DataRequired
import requests
db = SQLAlchemy()
app =... | mgardner1011/UdemyProjects | movie_ranking_site/main.py | main.py | py | 3,878 | python | en | code | 0 | github-code | 6 |
12680443626 | import os
import warnings
import pandas as pd
from sklearn.preprocessing import StandardScaler
from torch.utils.data import Dataset
from utils.timefeatures import time_features
warnings.filterwarnings('ignore')
class MyDataset(Dataset):
def __init__(self, root_path, data_path, data, flag, seq_len, label_len, p... | ForestsKing/TSF-Library | data_provider/data_loader.py | data_loader.py | py | 4,041 | python | en | code | 4 | github-code | 6 |
36060788445 | from utils.parse_json import parse_json
from utils.save_json import save_json
import logging
def put_command(sala: str, nivel: int, chave: str):
data = parse_json('src/json/comandos.json')
data[sala][0]['outputs'][nivel]['status'] = chave
save_json('src/json/comandos.json', data)
def get_command(sala: s... | AntonioAldisio/FSE-2022-2-Trabalho-1 | src/utils/troca_comando.py | troca_comando.py | py | 1,900 | python | en | code | 0 | github-code | 6 |
29799264733 | # -*- coding: utf-8 -*-
# https://blog.csdn.net/Tifficial/article/details/78116862
import os
import time
import tkinter.messagebox
from tkinter import *
from tkinter.filedialog import *
from PIL import Image, ImageTk
import pygame
class create_UI():
def __init__(self):
pass
def create_button(self,... | anna160278/tkinter-examples | examples/aaa/tst.py | tst.py | py | 2,443 | python | en | code | 0 | github-code | 6 |
43702400504 | from django.conf.urls import include, url
from . import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^yolog/$', views.yolo_index, name='yolo_index'),
url(r'^result/$', views.result, name='result'),
url(r'^list/$', views.Restauran... | hassanabidpk/searchrestaurant | django/searchrestaurant/search/urls.py | urls.py | py | 781 | python | en | code | 129 | github-code | 6 |
17953957335 | import numpy as np
from collections import Counter
def euclideanDistance(x, y):
return np.sqrt(np.sum((x-y)**2))
class KNN:
def __init__(self, k=3):
self.k = k
def fit(self, X_train, y_train):
self.X_train = X_train
self.y_train = y_train
def predict(self, X):
pre... | Helyousfi/Machine-learning | KNN.py | KNN.py | py | 1,573 | python | en | code | 0 | github-code | 6 |
9928969059 | import numpy as np
import matplotlib.pyplot as plt
import cPickle
def plot_statistics(statistics, legends, title="", ylabel="", xlim=None, ylim=None, writeto="default.jpeg"):
plt.figure(num=None, figsize=(10, 6), dpi=80, facecolor='w', edgecolor='k')
plt.xlabel("Number of epochs")
plt.ylabel(ylabel)
p... | adbrebs/dogs_vs_cats | results/utilities.py | utilities.py | py | 3,026 | python | en | code | 5 | github-code | 6 |
21354510025 | #
# @lc app=leetcode.cn id=337 lang=python3
#
# [337] 打家劫舍 III
#
from util import TreeNode
# @lc code=start
from functools import lru_cache
class Solution:
def rob(self, root: TreeNode) -> int:
nums = []
@lru_cache(None)
def dfs(node: TreeNode, can: bool) -> int:
if ... | Alex-Beng/ojs | FuckLeetcode/337.打家劫舍-iii.py | 337.打家劫舍-iii.py | py | 811 | python | en | code | 0 | github-code | 6 |
73000139069 | import configparser
from wireguard_keys import *
PUB_KEY = '...' # здесь должен быть указан public key
if __name__ == "__main__":
try:
with open('curr_ip.txt', 'r') as f:
IP_N = int(f.readline())
except FileNotFoundError:
IP_N = int(input('не найден последний IP, введите его вручную: '))
#n... | if13/utils | wireguard config generator/wireguard_export_lan.py | wireguard_export_lan.py | py | 1,671 | python | ru | code | 0 | github-code | 6 |
16593223409 | #Challenge MeLi 2022 - Lautaro Stroia
from database import *
from google_api import *
def main():
#Database
try:
db = DataBaseHandler()
db.run()
except Exception:
print("Error with database")
return
#Google API service
gapi_handler = GoogleAPIHandler()
try:
files = gapi_handler.get_drive_files()... | rg273/Challenge-MeLi-2022 | main.py | main.py | py | 1,219 | python | en | code | 0 | github-code | 6 |
36201897714 | from PIL import Image
from picamera.array import PiRGBArray
from picamera import PiCamera
from botocore.exceptions import ClientError
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from time import sleep, time
import sys
from uuid import uuid4
import os
import RPi.GPIO as GPIO
import json
import boto3
... | scriptkiddyisme/mysmartbin | Raspberry Pi/smartbin.py | smartbin.py | py | 8,967 | python | en | code | 0 | github-code | 6 |
20649229622 | import pyswarms as ps
from pyswarms.utils.functions import single_obj as fx
from pyswarms.utils.plotters.plotters import plot_contour, plot_surface
from pyswarms.utils.plotters.formatters import Mesher, Designer
# Run optimizer
options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
optimizer = ps.single.GlobalBestPSO(n_particles=... | igorpustovoy/inteligencja_obliczeniowa | lab04/zad3/3.py | 3.py | py | 960 | python | en | code | 0 | github-code | 6 |
27535933658 | import torch
from torch import nn
import torch.nn.functional as F
from timm.models.layers import to_2tuple, DropPath, trunc_normal_
import math
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
super().__init__()
out_feature... | fym1057726877/Defense | TransGAN/TransGanModel.py | TransGanModel.py | py | 26,999 | python | en | code | 0 | github-code | 6 |
10420483101 | """
.. moduleauthor:: Martí Congost <marti.congost@whads.com>
"""
from typing import Any, Optional, Set, Tuple
from httplib2 import Http
from base64 import urlsafe_b64encode
from json import loads, dumps
from cocktail.modeling import overrides
from .exceptions import CacheKeyError
from .cachekey import CacheKey
from ... | marticongost/cocktail | cocktail/caching/restcachestorage.py | restcachestorage.py | py | 4,258 | python | en | code | 0 | github-code | 6 |
9988555176 | import traceback, re, json, logging
from ..file_utilities.filepath import Filepath
from ..entitlements.entitlement_manager import Entitlement_Manager
from .file_manager import File_Manager
from ..client_config import COLLECTIONS_WITH_BAD_LEVEL_IMAGES, UNLOCK_ALL_BUDDIES
from .. import shared
logger_errors = logging.... | colinhartigan/valorant-inventory-manager | server/src/inventory_management/buddy_manager.py | buddy_manager.py | py | 6,398 | python | en | code | 150 | github-code | 6 |
41345912194 | import json
from functools import wraps
import requests
from service_now_api_sdk.settings import (
SERVICENOW_API_PASSWORD,
SERVICENOW_API_TOKEN,
SERVICENOW_API_USER,
SERVICENOW_URL,
)
def headers_replace(f):
@wraps(f)
def decorated_function(*args, **kwargs):
headers ... | people-analytics-tech/service-now-api-sdk | service_now_api_sdk/sdk/servicenow/helpers/client.py | client.py | py | 3,159 | python | en | code | 1 | github-code | 6 |
20281068214 | op = 'S'
num = []
cont5 = 0
while True:
if op in 'Nn':
print(f'Foram digitados {len(num)} valores: {num}')
num.sort(reverse = True)
print(f'Lista de valores ordenada de forma decrescente: {num}')
if 5 in num:#verifica se tem o valor 5 na lista
print('O valor 5 foi encont... | JoooNatan/CursoPython | Mundo03/Exs/Ex081.py | Ex081.py | py | 536 | python | pt | code | 0 | github-code | 6 |
41061708200 | from PySide6.QtWidgets import (
QWidget,
QToolBar,
QLabel,
QLineEdit,
QTextEdit,
QVBoxLayout,
QHBoxLayout,
)
import core.terminal_commands as tc
class WidgetGitUtils(QWidget):
"""
A custom QWidget that provides a user interface for Git utilities.
This widget contains a toolba... | sanyokkua/dev_common_tools_py | ui/widgets/widget_git_utils.py | widget_git_utils.py | py | 4,017 | python | en | code | 1 | github-code | 6 |
33480868557 | from django.shortcuts import render
from .models import Hardware, Software, Employees
from rest_framework import generics
from .serializers import HardwareSerializer, SoftwareSerializer, EmployeesSerializer
from django.db.models.query import Q
# Create your views here.
class CreateHardware(generics.CreateAPIView):
... | vuedatavivek/productsample | crm_project/organization/views.py | views.py | py | 1,292 | python | en | code | 0 | github-code | 6 |
44663849656 | import re
import sys
def parse_word(w):
return w.replace(" ","_")
def parse_word_contained(w):
x = re.match("(\d+) (\w+ \w+) bags?",w)
if x is None:
print(w)
num = x.group(1)
word = parse_word(x.group(2))
return (word,num)
def parse_contained(str):
if str == "no other bags":
... | smagill/aoc2020 | day7.py | day7.py | py | 1,730 | python | en | code | 0 | github-code | 6 |
22416435881 | import sys
import numpy as np
class gridmap2d(object):
"""
@brief 2D matrix for grid map
@param mapsize: (width, height) of the 2d grid map; unit is m
@param resolution: unit is m
@param dtype: data type
"""
def __init__(self, mapsize = (50.0, 50.0),
resolution = 0.1, ... | democheng/PythonRobotics | SLAM/gridmap2d.py | gridmap2d.py | py | 1,980 | python | en | code | 15 | github-code | 6 |
37366659638 | #!/usr/bin/env python3
from pylab import *
from numpy import *
import matplotlib.cm as cm
from common import *
idx_vec = range(1, num_k+1)
if with_FVD_solution == True :
if num_k > 1 :
fig, ax = plt.subplots(2, num_k, figsize=(9, 5.5))
else :
fig, ax = plt.subplots(1, 2, figsize=(9, 5.5))
... | zwpku/EigenPDE-NN | plot_scripts/plot_2d_evs_nn_and_FVD.py | plot_2d_evs_nn_and_FVD.py | py | 3,318 | python | en | code | 3 | github-code | 6 |
457933717 | '''
rest_framework reverse 补丁
'''
from rest_framework import relations
original_reverse = relations.reverse
def hack_reverse(alias, **kwargs):
namespace = kwargs['request'].resolver_match.namespace
if bool(namespace):
name = "%s:%s" % (namespace, alias)
return original_reverse(name, **kwargs)
... | dowhilefalse/Donation-Platform | api/__init__.py | __init__.py | py | 771 | python | en | code | 3 | github-code | 6 |
23873826885 | import cv2
import time
import numpy as np
import supervision as sv#this is a Roboflow open source libray
from ultralytics import YOLO
from tqdm import tqdm #this is a tool for visualising progress bars in console. Remove for production code as might slow things down
COLORS = sv.ColorPalette.default()
#Define entry a... | tobieabel/demo-v3-People-Counter | Demo v3.py | Demo v3.py | py | 10,021 | python | en | code | 0 | github-code | 6 |
13954591653 | '''● Realizar una función, tal que resuelva el cuadrado de los N primeros números
naturales.
● Realizar una función, tal que realice una sumatoria desde 1 hasta un número
N ingresado por el usuario.
● Realizar una función, tal que realice el factorial de un número N ingresado
por el usuario.'''
def factorial(x):
i... | eSwayyy/UCM-projects | python/lab/ppt9_(funciones)/ejercicio2_ppt9.py | ejercicio2_ppt9.py | py | 788 | python | es | code | 1 | github-code | 6 |
28792809187 | scores = input("enter list of student scores: ").split()
for n in range(0, len(scores)):
scores[n] = int(scores[n])
maxScore = 0
for score in scores:
if score > maxScore:
maxScore = score
print("the max score is : ",maxScore)
| Mohamed-Rirash/100-days-python-challenge | day5/heiest_score.py | heiest_score.py | py | 245 | python | en | code | 0 | github-code | 6 |
3836899158 | from benchmark_task_manager import *
import itertools
iteration = 1
TM = [0,2]
toggle = itertools.cycle(TM)
while True:
t1 = time.time()
z = next(toggle)
eval('TaskManager{0}()._schedule()'.format(z))
groupid = z
elapsed = time.time() - t1
with open("tm_dump", "w") as fid:
fid.write("{0}... | fosterseth/awx-junk-drawer | serve_TM_data.py | serve_TM_data.py | py | 405 | python | en | code | 0 | github-code | 6 |
29464951423 | # Implement a pseudo-encryption algorithm which given a string S and an integer N concatenates
# all the odd-indexed characters of S with all the even-indexed characters of S, this process
# should be repeated N times.
# Examples:
# encrypt("012345", 1) => "135024"
# encrypt("012345", 2) => "135024" -> "30415... | tuyojr/code_wars-hacker_rank-leetcode | code_wars/alternating_split.py | alternating_split.py | py | 2,792 | python | en | code | 0 | github-code | 6 |
26246603211 | # Cmput 455 sample code
# Boolean Negamax for TicTacToe, with transposition table
# Written by Martin Mueller
from game_basics import EMPTY, BLACK, WHITE, opponent, winnerAsString
from tic_tac_toe import TicTacToe
from transposition_table_simple import TranspositionTable
from boolean_negamax_tt import negamaxBoolean
i... | wllmwng1/CMPUT455_Assignment_2 | TicTacToe/tic_tac_toe_solve_with_tt.py | tic_tac_toe_solve_with_tt.py | py | 1,054 | python | en | code | 1 | github-code | 6 |
44966506931 | # import cv2
#
# filename="imgmirror.jpg"
# img= cv2.imread('image.jpg')
# res= img.copy()
# for i in range(img.shape[0]):
# for j in range(img.shape[1]):
# res[i][img.shape[1]-j-1]= img[i][j]
#
# cv2.imshow('image', res)
# cv2.imwrite(filename,res)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# import cv2
#... | nicolafeby/Self-driving-car-robot-cnn | testcamex.py | testcamex.py | py | 7,221 | python | en | code | 0 | github-code | 6 |
5503849048 | def get_set():
return set(map(int, input().split()))
def is_super_set(main, sets):
for set in sets:
if not main.issuperset(set):
return False
return True
A = get_set()
queries = int(input())
sets = []
for _ in range(queries):
sets.append(get_set())
print(is_super_set(A, sets))... | Nikit-370/HackerRank-Solution | Python/is-strict-superset.py | is-strict-superset.py | py | 321 | python | en | code | 10 | github-code | 6 |
19797979191 | import functools
from typing import Callable, Union
from aiohttp import web
from .exceptions import AuthRequiredException, ForbiddenException, AuthException
def login_required(func):
"""
If not authenticated user tries to reach to a `login_required` end-point
returns UNAUTHORIZED response.
"""
... | mgurdal/aegis | aegis/decorators.py | decorators.py | py | 1,714 | python | en | code | 13 | github-code | 6 |
16638837739 | # !/usr/bin/python
# -*- coding: utf-8 -*-
"""
__author__ = 'qing.li'
"""
from django import template
from django.conf import settings
import re
from collections import OrderedDict
from django.conf import settings
register = template.Library()
@register.inclusion_tag('rbac/menu.html')
def menu(request):
menu_ord... | QingqinLi/nb_crm | rbac/templatetags/rabc.py | rabc.py | py | 2,027 | python | en | code | 0 | github-code | 6 |
72162560509 | import sqlite3 as lite
import sys
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class CrawlerPipeline(object):
def __init__(self):
con = lite.connect('crawler... | yaoxiuh/WebCrawler | crawler/pipelines.py | pipelines.py | py | 1,056 | python | en | code | 0 | github-code | 6 |
17533905717 | rows, columns = [int(x) for x in input().split()]
a = [[x for x in input().split()] for _ in range(rows)]
while True:
command = input().split()
action = command[0]
if action == 'END':
break
if action != 'swap' or len(command) != 5:
print("Invalid input!")
continue
# better i... | emilynaydenova/SoftUni-Python-Web-Development | Python-Advanced-Sept2023/Exercises/03.Multidimensional_lists/Multidimensional_lists_First/06.Matrix_shuffling.py | 06.Matrix_shuffling.py | py | 1,452 | python | en | code | 0 | github-code | 6 |
19160774674 | import sys, os
from turtle import home
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../')
import time
import pytest
import allure
from allure_commons.types import AttachmentType
from Tests.test_Base import BaseTest
from Locators.Locators import Locators
from Config.config import ... | sawrav-sharma/py_new_dd | Tests/test_HomePage.py | test_HomePage.py | py | 2,879 | python | en | code | 0 | github-code | 6 |
36540773216 | # Import libraries
from requests import get
from json import dumps
# Your own local host's url
URL = "http://127.0.0.1:5000/"
# Names of active pages
mine_block = "mine_block"
get_chain = "get_chain"
is_valid = "is_valid"
# Define function for to check if API works and use the API.
def check_request_a... | mrn01/Blockchain_Project | blockchain_davidcoin/Module 1 - Create a Blockchain/use_your_own_API.py | use_your_own_API.py | py | 795 | python | en | code | 0 | github-code | 6 |
71449750907 | from multiprocessing import Process, Lock, Queue, Semaphore
import time
from random import random
buffer = Queue(10)
empty = Semaphore(2) # 缓存空余数
full = Semaphore(0) # 缓存占用数
lock = Lock()
class Consumer(Process):
def run(self):
global empty, buffer, full, lock
while True:
full.acqu... | haidongsong/spider_learn | zhang_xiaobo_spider_practice/producer_custom.py | producer_custom.py | py | 1,177 | python | en | code | 0 | github-code | 6 |
1965038380 | # -*- coding: utf-8 -*-
import json
import requests
import os
import time
import log21
from kafka import KafkaConsumer
access_token = os.environ.get("ACCESS_TOKEN")
kafka_host = os.environ.get("KAFKA_HOST")
kafka_port = os.environ.get("KAFKA_PORT", "9092")
kafka_topic = os.environ.get("KAFKA_TOPIC")
def dingtalk_robo... | zxzmcode/oTools | python/Alnot/Dingtalk/kafka_to_Dingtalk/dingtalk.py | dingtalk.py | py | 1,832 | python | en | code | 0 | github-code | 6 |
14716216800 | import torch
from torch import nn
import torch.nn.functional as F
from models.Segformer import mit_b0,mit_b1,mit_b2#,mit_b3,mit_b4,mit_b5
class SK(nn.Module):
def __init__(self, in_channel, mid_channel, out_channel, fuse, len=32, reduce=16):
super(SK, self).__init__()
len = max(mid_channel // reduc... | RuipingL/TransKD | train/CSF.py | CSF.py | py | 10,763 | python | en | code | 10 | github-code | 6 |
39463845510 |
import time
import picamera
import sqlite3
import signal
import os
import shutil
pidDB = sqlite3.connect('/home/pi/System/PID.db')
pidCursor = pidDB.cursor()
actualPID = os.getpid()
print("I'm PID " + str(actualPID))
pidCursor.execute("""UPDATE PID SET value = ? WHERE name = ?""", (actualPID, "camera"))
pidDB.commit(... | jeremyalbrecht/Alarm-RPI | camera.py | camera.py | py | 1,001 | python | en | code | 0 | github-code | 6 |
9003224390 | import json
from django.http import HttpResponse
__author__ = 'diraven'
class HttpResponseJson(HttpResponse):
def __init__(self, data=None, is_success=False, message=''):
response_data = {
'data': data,
'message': message,
'success': is_success
}
super(H... | diraven/streamchats2 | base/classes/HttpResponseJson.py | HttpResponseJson.py | py | 411 | python | en | code | 0 | github-code | 6 |
26664521611 | from rsa_class import RSAUtil
def main():
# 寫入與真實使用的金鑰並不相同,因為檔案是有加入 passphrase 作保護
RSA = RSAUtil()
RSA.new_keys(2048)
RSA.save_key("private","./keys/authorize_private.bin")
RSA.save_key("public","./keys/authorize_public.pem")
if __name__ == "__main__":
main() | kangaroo-0000/cythonize-in-one-click | rsa_authorize/utils/rsa/generator.py | generator.py | py | 337 | python | en | code | 1 | github-code | 6 |
6196779715 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2022/9/12 2:08 下午
# @Author : LiangJun
# @Filename : test_demo2.py
import unittest
from ddt import ddt, data
test_datas = [
{'id': 1, 'title': '测试用例1'},
{'id': 2, 'title': '测试用例2'},
{'id': 3, 'title': '测试用例3'}
]
@ddt
class TestDemo(unittest.Te... | lj5092/py14_Test_Open | py14_04day/dome/test_demo2.py | test_demo2.py | py | 427 | python | en | code | 0 | github-code | 6 |
16566955673 | # 도시 분할 계획
# n개의 집과 m개의 도로가 있는 마을이 있는데, 이 마을을 두개의 마을로 분할하고 도로를 최소 비용으로 설치할 경우를 구하라.
# 내 답안1
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
graph = []
parent = [i for i in range(n+1)]
for _ in range(m):
a, b, c = map(int, input().split())
graph.append((c,a,b))
graph.sort()
def find_... | dngus1683/codingTestStudy | 알고리즘/Disjointset /백준 / python/1647.py | 1647.py | py | 829 | python | ko | code | 0 | github-code | 6 |
26041286196 | from __future__ import annotations
import itertools
import logging
import os
from typing import Callable, Iterable, cast
from packaging.utils import canonicalize_name as canonicalize_project_name
from pants.backend.python.goals.lockfile import synthetic_lockfile_target_name
from pants.backend.python.macros.common_fi... | pantsbuild/pants | src/python/pants/backend/python/macros/common_requirements_rule.py | common_requirements_rule.py | py | 6,084 | python | en | code | 2,896 | github-code | 6 |
26986909966 | # -*- coding: utf-8 -*-
import pytest
from nameko.testing.utils import get_extension
from nameko.testing.waiting import wait_for_call
from nameko_grpc.client import Client
from nameko_grpc.entrypoint import GrpcServer
class TestCloseSocketOnClientExit:
@pytest.fixture(params=["server=nameko"])
def server_typ... | nameko/nameko-grpc | test/test_connection.py | test_connection.py | py | 1,178 | python | en | code | 57 | github-code | 6 |
72946561467 | #! -*- coding=utf-8 -*-
import os
import sys
filepath = os.path.abspath(__file__)
sys.path.append(os.path.dirname(os.path.dirname(filepath)))
import threading
import time
from datetime import datetime
from multiprocessing import Process
from machines.machineVPN import MachineVPN
# from machines.machineWujiVPN impor... | cash2one/brush-1 | slave/scripts/test/testht.py | testht.py | py | 3,824 | python | en | code | 0 | github-code | 6 |
7807511248 | import unittest
from metagame_balance.vgc.competition import get_pkm_points, STANDARD_TOTAL_POINTS
from metagame_balance.vgc.util.generator.PkmRosterGenerators import RandomPkmRosterGenerator
class TestEncodingMethods(unittest.TestCase):
def test_random_roster_generator(self):
gen = RandomPkmRosterGener... | nianticlabs/metagame-balance | test/TestRandomRosterGenerator.py | TestRandomRosterGenerator.py | py | 587 | python | en | code | 3 | github-code | 6 |
40646452965 | import numpy as np
import array
def ros2dict(msg):
if type(msg) in (str, bool, int, float):
return msg
output = {}
for field in msg.get_fields_and_field_types():
value = getattr(msg, field)
if type(value) in (str, bool, int, float):
output[field] = value
elif ... | foxpoint-se/eel | src/eel/eel/utils/radio_helpers/ros2dict.py | ros2dict.py | py | 602 | python | en | code | 0 | github-code | 6 |
13543436023 | import pandas as pd
import numpy as np
import scipy.stats as stats
import pylab as pl
import re
import seaborn as sns
import matplotlib.pyplot as plt
import random
sns.set(font_scale = 1.5)
pd.set_option('display.max_columns', 15)
pd.set_option('display.max_rows', 40)
filepath = '\\Coding\\DataAnalystI... | avielchow/Property-Assessment-Analysis | Analysis.py | Analysis.py | py | 5,400 | python | en | code | 0 | github-code | 6 |
28868669946 | import unittest
from babarbackend.models import *
from babarbackend.api import *
class UserTestCase(unittest.TestCase):
"""
"""
def setUp(self):
self.manager = TaskManager()
def tearDown(self):
User.objects.all().delete()
def testCreateUser(self):
username = 'sara'
... | codergirl/babar | babarbackend/tests.py | tests.py | py | 862 | python | en | code | 0 | github-code | 6 |
18523322737 | import xlrd
import xlwt
from featureComp import *
from createmat import *
def findRank(path2):
for i in range(1,39):
path3=path2+str(i)+'.xlsx'
matchday=xlrd.open_workbook(path3)
sheet1=matchday.sheet_by_index(0)
#print path3,'\n'
for j in range(1,21):
team_rank[sheet1.cell(j,2).value.strip()].append... | kushg18/football-match-winner-prediction | main.py | main.py | py | 2,107 | python | en | code | 3 | github-code | 6 |
31534303974 | ## LESSON 6 Q1: AUDITING - ITERATIVE PARSING/SAX PARSE using ITERPARSE
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Your task is to use the iterative parsing to process the map file and
find out not only what tags are there, but also how many, to get the
feeling on how much of which data you can expect to have i... | rjshanahan/Data_Wrangling_with_MongoDB | Lesson 1_Udacity_MongoDB_CSV+JSON.py | Lesson 1_Udacity_MongoDB_CSV+JSON.py | py | 1,349 | python | en | code | 2 | github-code | 6 |
31629715534 | from flask import Flask, render_template, redirect, request
from flask import Blueprint
from models.visit import Visit
import repositories.visit_repository as visit_repository
import repositories.country_repository as country_repository
import repositories.user_repository as user_repository
visits_blueprint = Bluepri... | paolaguerralibrero/bucket_list_python_project_w5 | controllers/visit_controller.py | visit_controller.py | py | 1,562 | python | en | code | 0 | github-code | 6 |
43599317125 | from __future__ import division
import h5py
import numpy as np
'''
PARAMETERS
'''
#savefig()
outFile='all_data.hdf5'
def main():
f=h5py.File(outFile,'r')
ds = f['data'][:,0:6,:]
data = f['interpo']
import_features=['Weight_Index', 'Waist(CM)', 'Hip(CM)', 'Waist_Hip_Ratio','systolic_pressure', 'diastolic_pressure'... | taylorsmith-UKY/diabetes | get_path.py | get_path.py | py | 4,368 | python | en | code | 0 | github-code | 6 |
8411903253 | url = "http://dantri.com.vn/"
output_file_name = "news.xlsx"
#Step 1: Download information on the Dantri website
from urllib.request import urlopen
from bs4 import BeautifulSoup
#1.1: Open a connection
conn = urlopen(url)
#1.2: read
raw_data = conn.read() #byte
#1.3: Decode
html_content = raw_data.decode('utf-8... | taanh99ams/taanh-lab-c4e15 | Lab 2/dan_tri_extract.py | dan_tri_extract.py | py | 1,322 | python | en | code | 0 | github-code | 6 |
70204805949 | import requests
from fake_useragent import UserAgent
import re
import base64
import sys
from fontTools.ttLib import TTFont
from lxml import etree
import pymysql
# Unicode => ASCII => hex
from unicode_to_hex import get_hex_back
# 继承重写TTFont,直接使用字节串数据,避免在动态字体加密中重复打开关闭woff文件
class MyTTFont(TTFont):
"""
主要目的:实现直接... | xiaohao-a/58_ershouche_font | 58ershouche.py | 58ershouche.py | py | 6,376 | python | zh | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.