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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
8056494388 | from constants import *
import numpy as np
def load_data(filepath, coeffs=ALL_COEFFS):
"""
:param filepath: Path for the file to read, either the TRAIN_FILE or TEST_FILE
:return:
Organizes the data in the input file into a list of matrices. Each matrix is the data for a spoken digit,
where the co... | tylerfeldman321/Predicting-Spoken-Digits | parse_data.py | parse_data.py | py | 2,492 | python | en | code | 1 | github-code | 36 |
946372462 | pkgname = "openscenegraph"
pkgver = "3.6.5"
pkgrel = 0
build_style = "cmake"
configure_args = [
# avoid lib64
"-DLIB_POSTFIX="
]
hostmakedepends = ["cmake", "ninja", "pkgconf"]
makedepends = [
# no ffmpeg here, not compatible with ffmpeg 6
"mesa-devel",
"libcurl-devel",
"giflib-devel",
"libr... | chimera-linux/cports | contrib/openscenegraph/template.py | template.py | py | 1,122 | python | en | code | 119 | github-code | 36 |
10600300959 | from aperr002v01 import APERR002V01
from ap8 import AP8
from asi import Rec
from math import log10, sqrt, sin, cos
from tkinter import Tk, E, W, StringVar, IntVar, END
from tkinter import ttk
class S1855(APERR002V01):
def input_widgets(self):
super().input_widgets()
self.root.label_coeffa.destroy(... | Amantay777/asi | s1855.py | s1855.py | py | 7,852 | python | en | code | 0 | github-code | 36 |
34082247012 | import traceback
import logger as log
import pandas as pd
from datetime import (
datetime
)
from database import (
DrugsMetaCollection,
IngredientsCollection,
LyophilizedCollection
)
from dash import (
html,
dcc
)
class MongoData(object):
def __init__(self):
self._ingredients_db_ob... | ashwani1310/Lyophilized-Drugs-Analysis-Tool | ui_data.py | ui_data.py | py | 12,601 | python | en | code | 2 | github-code | 36 |
8680864840 | """The module contains test functions to test Tankerkoenig API wrapper."""
import tempfile
import os
from unittest import TestCase
from unittest.mock import MagicMock, patch
from homemonitoring.tankerkoenig import TankerKoenig
class TestTankerKoenig(TestCase):
"""TestTankerKoenig contains the test cases for th... | BigCrunsh/home-monitoring | homemonitoring/tests/tankerkoenig_test.py | tankerkoenig_test.py | py | 2,091 | python | en | code | 2 | github-code | 36 |
36244286092 | #!/usr/bin/env python
import boto3
import subprocess
#output = subprocess.call(['/home/ansadmin/nagaratest/docker.sh'])
import time
ec2 = boto3.resource('ec2')
import yaml
config = yaml.load(open('config.yml'))
ec2 = boto3.resource('ec2')
instance = ec2.create_instances(
ImageId = config['ImageId'],
MinCount =... | hotkey123/test | nagaratest/final_create_instance.py | final_create_instance.py | py | 1,161 | python | en | code | 0 | github-code | 36 |
34928053014 | import requests
from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
import re
with open('raw_kaggle_huffpost.json', 'r') as file:
entries = file.read().lower().split("\n")
d... | the-super-toys/ml-there-will-be-news | fetch-dataset.py | fetch-dataset.py | py | 4,295 | python | en | code | 1 | github-code | 36 |
74050784104 | import unittest
from parlai.core.agents import create_agent
from parlai.core.params import ParlaiParser
from parlai.core.worlds import create_task
from parlai.core.teachers import DialogTeacher, register_teacher
import parlai.utils.testing as testing_utils
@register_teacher('teacher1')
class Teacher1(DialogTeacher):
... | facebookresearch/ParlAI | tests/test_multiworld.py | test_multiworld.py | py | 4,408 | python | en | code | 10,365 | github-code | 36 |
8695479767 | import re
import unitydoc
#rename_command = re.compile("^!rename +(.+)$")
#valid_name = re.compile("^[A-Za-z_]+$")
def response(self, prefix, command, params, trailing):
if command == 'PRIVMSG' and params == self.channel and trailing.startswith('!define'):
self.send("PRIVMSG {} :{}".format(self.channel,
... | cheery/ircbot | driver.py | driver.py | py | 2,590 | python | en | code | 0 | github-code | 36 |
14114648700 | import sys
from collections import deque
def bfs(node):
queue = deque()
queue.append(node)
visited[node] = True
while len(queue) != 0:
cur_node = queue.popleft()
for linked_node in adj[cur_node]:
if not visited[linked_node]:
visited[linked_node] = True
... | nashs789/JGAlgo | Week02/Q11724/Q11724_Inbok.py | Q11724_Inbok.py | py | 786 | python | en | code | 2 | github-code | 36 |
74207450663 | import argparse
import logging
from .system import system_parser
from .network import network_parser
from .stress import stress_parser
log_debug = logging.getLogger("debugLog")
def get_parser(parent=None):
# connection with main parser
if not parent:
anomaly_inject = argparse.ArgumentParser(descripti... | Ydjeen/openstack_anomaly_injection | openstack_anomaly_injection/anomaly_injection/config/argparser/argparser.py | argparser.py | py | 5,377 | python | en | code | 0 | github-code | 36 |
25460261702 | import logging
from markdown.extensions import Extension
from markdown.inlinepatterns import Pattern
from markdown.util import etree
logger = logging.getLogger(__name__)
def build_url(label, base, end):
""" Build a url from the label, a base, and an end. """
return '%s%s%s' % (base, label, end)
def build_... | ghtyrant/mdwiki | mdwiki/backend/extensions/mdwikilinks.py | mdwikilinks.py | py | 2,780 | python | en | code | 1 | github-code | 36 |
18909708203 | """
Description:
A tool for translating transcript coordinates to reference coordinates using the CIGAR string.
Contributors:
20210119 - Larry Clos II (drlclos@gmail.com)
Assumptions:
- For a given genetic sequence (transcript) the sequence coordinate and index are the same and start at zero (0).
- CIGAR defines the... | LClos/bfx_tools | genetic_coordinates/cigar_translate.py | cigar_translate.py | py | 9,659 | python | en | code | 0 | github-code | 36 |
72596155945 | from command.command import Command
from data_base.dna_collection_manager import DnaCollectionManager
class CreationCommand(Command):
def __init__(self):
self.__dna_collection = DnaCollectionManager()
def get_dna_collection(self):
return self.__dna_collection
def _save_sequence(self, arg... | AyalaGottfried/DNA-Analyzer-System | command/creation_commands/creation_command.py | creation_command.py | py | 706 | python | en | code | 2 | github-code | 36 |
17411415924 | """mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... | miyanda2/Driver-Qr | mysite/urls.py | urls.py | py | 2,046 | python | en | code | 0 | github-code | 36 |
17436736893 | import argparse
import torch
from tqdm import tqdm
import matplotlib.pyplot as plt
import os
from torchvision import transforms
import dataset
from torch.utils.data import DataLoader
from utils.metric import get_overall_valid_score
from utils.generate_CAM import generate_validation_cam
from utils.pyutils impo... | xmed-lab/OEEM | classification/train.py | train.py | py | 6,342 | python | en | code | 29 | github-code | 36 |
41201687151 | import numpy as np
import cv2
from .bound_eggs import fit_rectangles
def clutch_dataset(contours: np.ndarray, label: str, num_eggs: int) -> np.ndarray:
"""
Create classification dataset from contours
:param num_eggs: number of eggs
:param contours: Contours to fit ellipses to
:param label: Label f... | RomeBits/BirdEggSpecies | src/dataset.py | dataset.py | py | 1,005 | python | en | code | 0 | github-code | 36 |
41787908029 | #from django.shortcuts import render
# Create your views here.
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import generics
from animals.models import Categories, Status, Tags, Animal, AnimalForm
from api.serializers import AnimalSerializer
from djan... | nejcRazpotnik/pet_store_djangoAPI | backend/petStore/api/views.py | views.py | py | 3,732 | python | en | code | 0 | github-code | 36 |
40328938266 | from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.multioutput import MultiOutputClassifier
from data.tokenizer import tokenize
from sklearn.preprocessing import OneHotEncoder
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.model_selection import GridSearch... | DietzRep/disaster_response_pipeline_project | models/model_factory.py | model_factory.py | py | 3,650 | python | en | code | 0 | github-code | 36 |
22353413985 | from typing import Any, Dict, List
import numpy as np
import transformers
import mlrun
from mlrun.serving.v2_serving import V2ModelServer
class HuggingFaceModelServer(V2ModelServer):
"""
Hugging Face Model serving class, inheriting the V2ModelServer class for being initialized automatically by the
model... | mlrun/mlrun | mlrun/frameworks/huggingface/model_server.py | model_server.py | py | 5,513 | python | en | code | 1,129 | github-code | 36 |
9915604425 | line_numbers = int(input())
my_list = []
for number in range(line_numbers):
current_string = input()
my_list.append(current_string)
print(my_list)
#################################### TASK CONDITION ############################
"""
2. Courses
On the first line, you will receive a s... | qceka88/Fundametals-Module | 11 List - Lab/02course.py | 02course.py | py | 858 | python | en | code | 8 | github-code | 36 |
44008099598 | import pygame
from pygame.locals import *
from random import randint as rand
pygame.init()
screen = pygame.Surface((500, 100))
window = pygame.display.set_mode((screen.get_width() * 2, screen.get_height() * 2))
def constrain(val, lo, hi):
# Because these things are useful :)
if val <= lo:
return lo
... | ninjafrostpn/PythonProjects | Bending/Bending(old interface).py | Bending(old interface).py | py | 14,805 | python | en | code | 0 | github-code | 36 |
27980503870 | #!/usr/bin/env python2
"""
Minimal Example
===============
Generating a square wordcloud from the US constitution using default arguments.
"""
from os import path
from wordcloud import WordCloud, STOPWORDS
d = path.dirname(__file__)
# Read the whole text.
text = open(path.join(d, 'titles.txt')).read()
# Generate a... | schollz/scholar-pull | makeCloud.py | makeCloud.py | py | 769 | python | en | code | 0 | github-code | 36 |
38285183708 | import mock
import pytest
from fc.qemu.exc import MigrationError
from fc.qemu.incoming import (
IncomingAPI,
IncomingServer,
authenticated,
parse_address,
)
def test_authentication_wrapper():
@authenticated
def test(cookie):
return 1
context = mock.Mock()
context.cookie = "as... | flyingcircusio/fc.qemu | src/fc/qemu/tests/test_migration.py | test_migration.py | py | 2,712 | python | en | code | 4 | github-code | 36 |
75034720424 | """
URL configuration for config project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home'... | ualex90/PWLService | config/urls.py | urls.py | py | 1,870 | python | en | code | 0 | github-code | 36 |
25304954617 | """
Author: Diego Pinheiro
github: https://github.com/diegompin
"""
from itertools import cycle
from maracatu.src.plotting.plot_base import PlotBase
# import pandas as pd
# from dataintensive.src import Joint
# from dataintensive.src import BinsDataFrame
# from dataintensive.src import Parameter
# from dataintensive.... | diegompin/maracatu | maracatu/src/plotting/curves.py | curves.py | py | 4,421 | python | en | code | 0 | github-code | 36 |
43676904102 | import numpy as np
import cv2
from PIL import Image, ImageFilter
import training_vs2
weights = np.load('weights.npy')
biases = np.load('biases.npy')
def imageprepare(argv):
im = Image.open(argv).convert('L')
width = float(im.size[0])
height = float(im.size[1])
newImage = Image.new('L', (28, 28),... | tpvt99/detect-gomoku-using-neural-network | test.py | test.py | py | 2,093 | python | en | code | 1 | github-code | 36 |
5840512827 | from django.http import HttpResponse
from django.http import JsonResponse
from bs4 import BeautifulSoup
import requests
def index(request):
url = "https://air-quality.com/place/india/delhi/a32ed7fc?lang=en&standard=aqi_us"
req = requests.get(url)
soup = BeautifulSoup(req.content, 'html.parser')
val =... | amanpreets01/pollutantAPI | mysite/polls/views.py | views.py | py | 622 | python | en | code | 0 | github-code | 36 |
40689277223 | with open("2020\Day_13\input") as f:
data = f.read().splitlines()
#data = ['939', '7,13,x,x,59,x,31,19']
eta = int(data[0])
timetable = [int(d) for d in data[1].split(',') if d !='x']
arrivals = {t:t*(eta//t+1) for t in timetable}
nextBusId = min(arrivals, key=arrivals.get)
print('Solution:', nextBusId * (arri... | furbank/AdventOf | 2020/Day_13/part1.py | part1.py | py | 349 | python | en | code | 0 | github-code | 36 |
11303967232 | import logging
import musicbrainzngs
from retrying import retry
from ..constants import SAMPLE_RATE
logger = logging.getLogger(__name__)
class MusicbrainzLookup(object):
@retry(stop_max_attempt_number=5, wait_exponential_multiplier=100)
def query(self, disc_id):
logger.debug('Retrieving disc meta ... | pisarenko-net/cdp-sa | hifi_appliance/meta/musicbrainz.py | musicbrainz.py | py | 2,585 | python | en | code | 0 | github-code | 36 |
22354713255 | import base64
import os
import typing
import unittest
import deepdiff
import fastapi.testclient
import kubernetes
import pytest
import sqlalchemy.orm
import mlrun.common.schemas
import mlrun.errors
import mlrun.runtimes.pod
import server.api.utils.singletons.k8s
import tests.api.runtimes.base
from mlrun.datastore imp... | mlrun/mlrun | tests/api/runtimes/test_spark.py | test_spark.py | py | 29,207 | python | en | code | 1,129 | github-code | 36 |
31802246209 | # /usr/bin/python3.6
# -*- coding:utf-8 -*-
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
flag = True
def buffer(self, root):
if not self.flag:
return 0
... | bobcaoge/my-code | python/leetcode/110_Balanced_Binary_Tree.py | 110_Balanced_Binary_Tree.py | py | 853 | python | en | code | 0 | github-code | 36 |
6141052989 |
import pandas as pd
import os
names = []
PATH = 'names/'
for fn in sorted(os.listdir(PATH)):
if not fn.endswith('.txt'): continue
df = pd.read_csv(PATH + fn, names=['name', 'gender', 'count'])
df['year'] = int(fn[-8:-4])
names.append(df)
# make a single DataFrame from a list of DataFrames
names = pd... | cusyio/datenanalyse-in-python | einstieg/firstletter_statistics.py | firstletter_statistics.py | py | 1,125 | python | en | code | 11 | github-code | 36 |
28856693359 | import yaml
import json
from typing import Sequence
from types import SimpleNamespace
from itertools import combinations, permutations
from sympy import symbols, Symbol
from sympy.logic.boolalg import BooleanFunction, And, Or, Not
import numpy as np
import torch
from torch import nn, Tensor
from dataset import collat... | noahleegithub/neurosat-cs4950 | ranking_models.py | ranking_models.py | py | 4,281 | python | en | code | 0 | github-code | 36 |
70521690663 | import time
from django.core import cache
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
from xiaochengxu import settings
class CountipMiddle(MiddlewareMixin):
# 在视图执行前调用
def process_request(self,request):
# 获取客户端ip
x_forwarded_for = re... | zhoujialefanjiayuan/liu-lian | xiaochengxu/middleware/fanpa.py | fanpa.py | py | 1,113 | python | en | code | 0 | github-code | 36 |
3438132850 | # Заполнение массива по матрице путей
def Graf_go():
N = 0
with open('input.txt', 'r') as f:
for s in f:
N += 1
arr = []
with open('input.txt', 'r') as f1:
for s in f1:
arr.append(s)
for i in range(len(arr)):
arr[i] = arr[i].split()
return arr
def... | t0r8ern1t/ASD-4-sem | 3/main.py | main.py | py | 1,254 | python | en | code | 0 | github-code | 36 |
16557260156 | import subprocess
import shlex
import sys
MEM_REQUESTS = {'Appliances': 4, 'Electronics': 20, 'Home_and_Kitchen': 20, 'Movies_and_TV': 8, 'Books': 64}
DATASETS = ['Appliances', 'Electronics', 'Home_and_Kitchen', 'Movies_and_TV', 'Books']
EPOCHS = [10]
SIZES = [2000, 5000]
SEED = 420
#HIDDEN_DIMS = [200, 300]
#DROPOUT_... | nick-bowman/ood-amazon-sentiment | run_pretraining_jobs.py | run_pretraining_jobs.py | py | 2,331 | python | en | code | 0 | github-code | 36 |
23585423225 | """
EEGNet
edit by hichens
"""
import numpy as np
from sklearn.metrics import roc_auc_score, precision_score, recall_score, accuracy_score
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.optim as optim
import sys; sys.path.append("..")
from utils.options imp... | hehichens/Cognitive | models/EEGNet.py | EEGNet.py | py | 3,378 | python | en | code | 6 | github-code | 36 |
26402106184 | import os
import sys
import random
import pygame
import sqlite3
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton
from PyQt5.QtWidgets import QInputDialog
pygame.init()
db = sqlite3.connect('clicker.db')
cur = db.cursor()
clock = pygame.time.Clock()
display_width = 1920
display_height = 108... | babysheesh/clicker | кликер2.0/main.py | main.py | py | 49,547 | python | en | code | 0 | github-code | 36 |
949535902 | pkgname = "ffmpeg"
pkgver = "6.0"
pkgrel = 5
build_style = "configure"
configure_args = [
"--prefix=/usr",
"--enable-shared",
"--enable-static",
"--enable-gpl",
"--enable-version3",
"--enable-runtime-cpudetect",
"--enable-openssl",
"--enable-librtmp",
"--enable-postproc",
"--enab... | chimera-linux/cports | main/ffmpeg/template.py | template.py | py | 4,987 | python | en | code | 119 | github-code | 36 |
35464732320 | from server.helpers import resource_path
SECRET_KEY = "DEVELOPMENT-KEY-CHANGE-ASAP"
SQLALCHEMY_DATABASE_URI = "sqlite://"+resource_path("/database/database.db")
SQLALCHEMY_TRACK_MODIFICATIONS = False
DEBUG = True
#=========================================================
# JavaScript Web Token
#==============... | kristofgilicze/TempHum-Supervisor-Sys | backend/server/config.py | config.py | py | 473 | python | en | code | 0 | github-code | 36 |
39725412461 | from app import db
import jinja2
from datetime import date
from flask import current_app, url_for
from flask_login import UserMixin, current_user, login_manager
class Admin(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(60))
password = db.Co... | run-nerver/student_info_system | app/models/pro.py | pro.py | py | 11,598 | python | en | code | 82 | github-code | 36 |
30582925697 | # -*- coding: utf-8 -*-
"""
Group 8 Final Project - Automatic Image Colorization
Ahmed Nasrallah, Touseef Ali, Hitesh Kumar
"""
#%%
import keras
from keras.preprocessing import image
from keras.engine import Layer
from keras.layers import Conv2D, Conv3D, UpSampling2D, InputLayer, Conv2DTranspose, Input... | hitsasu/image-colorization | code/color.py | color.py | py | 4,440 | python | en | code | 0 | github-code | 36 |
21781904654 | """
There is two kind of logger structure. Appart from the tensorBoardOutputLogger
and tensorBoardScoreLogger(which I am planning to deprecate or leave there as example
using the main two loggers that I will exlpain now)
Data Type | logger_function | usage&strategy
--- | --- | ---
included in Trainer,loss | create_tb_... | evcu/exp.bootstrp | experiments/exp_loggers.py | exp_loggers.py | py | 4,172 | python | en | code | 2 | github-code | 36 |
42340587356 | #We will write python code do download the following data:
#http://lab14.billkuker.com/data/squad.json
import socket
hostName = "lab14.billkuker.com"
fileName = "/data/story.txt"
#Connect to the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((hostName, 80))
#Convert the connec... | CU-CIS-2210-Python/CIS-2210-Lab14 | fetchAndParse.py | fetchAndParse.py | py | 1,710 | python | en | code | 0 | github-code | 36 |
29698007156 | import pandas as pd
import ppscore as pps
import streamlit as st
import plotly.express as px
from utils.helpers import (plot_binary_feature,
plot_feature_distribution,
define_lr_pipeline,
get_cross_val_score)
from utils.constants import ... | diegoglozano/interpretable-ml | modules/introduction.py | introduction.py | py | 3,220 | python | en | code | 0 | github-code | 36 |
42302144729 | try:
myFile = open("mydata2.txt", encoding="utf-8") #opening a remote file
except FileNotFoundError as bam:
print("The file does not exist")
print(bam.args) #explains error
else:
print("File :", myFile.read()) #prints file c... | PriscahC/Python_programming | Lesson11/test.py | test.py | py | 485 | python | en | code | 0 | github-code | 36 |
73335280743 | # coding: utf-8
"""
Test webservices
"""
import sys
import os
PROJECT_HOME = os.path.abspath(
os.path.join(os.path.dirname(__file__), '../../../'))
sys.path.append(PROJECT_HOME)
import json
import unittest
from flask import url_for
from flask_testing import TestCase
from httmock import urlmatch, HTTMock
from tug... | adsabs/tugboat | tugboat/tests/tests_unit/test_webservices.py | test_webservices.py | py | 2,331 | python | en | code | 0 | github-code | 36 |
23485747896 |
x = 4
while x > 0:
print("x is now", x)
x -= 1
names = ["Fred", "Jim", "Sheila"]
for name in names:
print(name)
x = range(1, 10, 2)
print(x)
print(type(x))
for i in x:
print(i)
x = range(1, 10)
for i in x:
for j in range(1, i):
print(i, j)
names = {"Fred" : "Jones", "Jim" : "Smith", "S... | tekiegirl/SafariPython | Loops.py | Loops.py | py | 623 | python | en | code | null | github-code | 36 |
69815063464 | import requests
import json
TMDB_API_KEY ='2ee130f2ba9bf221b6fe5107cffcac46'
def get_movie_genre():
request_url = f"https://api.themoviedb.org/3/genre/movie/list?api_key={TMDB_API_KEY}&language=en"
genres = requests.get(request_url).json()
for genre in genres['genres']:
fields = {
... | uttamapaksa/MOVISION | db data/makegenre.py | makegenre.py | py | 710 | python | en | code | 0 | github-code | 36 |
22397199213 | import os
from datetime import datetime
from celery import Celery
from celery.schedules import crontab
from celery.utils.log import get_task_logger
# 1-s terminal celery -A MainWater beat
# 2-s terminal celery -A MainWater worker --loglevel=info
logger = get_task_logger(__name__)
# Set the default Django ... | dillag/countersAPI | MainWater/MainWater/celery.py | celery.py | py | 1,497 | python | en | code | 0 | github-code | 36 |
38802468088 | import numpy as np
import cv2
import os
import time
import crop
import sys
from PIL import Image
def mean(x):
return sum(x) / len(x)
def showimage(name, image):
cv2.imshow(name, image)
cv2.waitKey(0)
cv2.destroyAllWindows()
def grouping(img):
print('the grouping part')
image = cv2.imread... | kaustubhdeokar/FinalTrendzlinkImage | gradient.py | gradient.py | py | 5,348 | python | en | code | 0 | github-code | 36 |
3321900706 | import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**2 + (np.sin(9*x))**2
n=8
xi = [i/n for i in range(n+1)]
yi = [f(xi[i]) for i in range(n+1)]
#tabela das diferenças divididas:
T = [yi]
for j in range(n+1):
T += [[(T[j][i+1]-T[j][i])/(xi[i+1+j]-xi[i]) for i in range(n-j)]]
... | MotaBruno/Analise-Numerica-projetos | ex2-pol.py | ex2-pol.py | py | 1,317 | python | en | code | 0 | github-code | 36 |
7921292233 | import pytest
from scripts.create_type_file import get_properties, create_connection_by_url, get_metadata_param
test_data = [
["wss://rpc.polkadot.io", "Polkadot"],
["wss://kusama-rpc.polkadot.io", "Kusama"],
["wss://westend-rpc.polkadot.io", "Westend"],
["wss://statemine.api.onfinality.io/public-ws", ... | zktony/nova-utils | tests/test_type_creation.py | test_type_creation.py | py | 1,386 | python | en | code | null | github-code | 36 |
18794196909 | """
Backend implementation for parsing the LCLS Questionnaire.
"""
import functools
import logging
import re
from typing import Optional
from psdm_qs_cli import QuestionnaireClient
from ..errors import DatabaseError
from .json_db import JSONBackend
logger = logging.getLogger(__name__)
class RequiredKeyError(KeyErr... | pcdshub/happi | happi/backends/qs_db.py | qs_db.py | py | 15,490 | python | en | code | 10 | github-code | 36 |
20445071495 | import logging as l
import sys
import os
import json
logger = l.getLogger("Transformer")
logger.setLevel(l.DEBUG)
formatter = l.Formatter('%(asctime)s | %(levelname)s | %(message)s')
stdout_handler = l.StreamHandler(sys.stdout)
stdout_handler.setLevel(l.INFO)
stdout_handler.setFormatter(formatter)
fh = l.FileHandle... | BastienEstia/SCDashBoard | pipline/Transformer.py | Transformer.py | py | 7,956 | python | en | code | 0 | github-code | 36 |
34202592392 | #!/usr/bin/env python
import click
from intercom.models import Location
from intercom.repositories import CustomerRepository
from intercom.services import get_customers_close_to_office
@click.command()
@click.option('--dataset', default='dataset/customers.txt', help='Path to the dataset.')
@click.option('--max-dist... | Wicker25/intercom-test | cli.py | cli.py | py | 941 | python | en | code | 0 | github-code | 36 |
5114478980 | import pandas as pd
def GetOutput(genes, readcount):
out = {}
ENSG = list(genes.keys())
out["ENSG"] = ENSG
out["Gene"] = [genes[item].genename for item in ENSG]
out["chrom"] = [genes[item].chrom for item in ENSG]
out["start"] = [genes[item].start for item in ENSG]
out["end"] = [genes[item].... | liuchuwei/trv | utils/get_output.py | get_output.py | py | 698 | python | en | code | 0 | github-code | 36 |
74520952744 | """
Usage: import the module, or run from
the command line as such:
python3 process_util.py --input=/path/to/input/file --output=/path/to/output/file --chunksize=chunksize
"""
import os
import sys
import itertools
import numpy as np
import pandas as pd
from sqlalchemy import create_engine
DEFAULT_... | emaksOne/preprocess_data | process_util.py | process_util.py | py | 14,141 | python | en | code | 0 | github-code | 36 |
4065634528 | """
Module to detect new parkrun events and coordinate the notification system.
Notifications are sent out via gmail, with credentials stored in a credentials.toml
file.
"""
import mimetypes
import smtplib
from datetime import datetime
from email.message import EmailMessage
from pathlib import Path
from typing import O... | jmoro0408/parkrun | email_new_events.py | email_new_events.py | py | 7,229 | python | en | code | 0 | github-code | 36 |
40517757437 | import os
import glob
import time
from datetime import datetime
from argparse import ArgumentParser
import pandas as pd
import matplotlib.pyplot as plt
import torch
import numpy as np
from agents.PPO import PPO
from environment.drl_environment import DRLEnvironment
def train():
env_name = "DRL"
has_cont... | AgileCodeCO/airsim-drl-reinforcement-learning | main.py | main.py | py | 13,673 | python | en | code | 4 | github-code | 36 |
26976749261 | from sys import stdin, setrecursionlimit
setrecursionlimit(10**7)
def addatBottom(stack , x):
if(len(stack) == 0):
stack.append(x)
return stack
num = stack[-1]
stack.pop()
addatBottom(stack , x)
stack.append(num)
return
def reverseStack(stack):
if(len(stack) == 0):
return stack
num = stack[-1]
stack... | Manoj-895/DSA-Python | Stack/reverseAstackByrecurssion.py | reverseAstackByrecurssion.py | py | 374 | python | en | code | 0 | github-code | 36 |
7504826492 | from datetime import datetime
import time
import json
from master import Master
import os
LOCAL_PATH = os.path.join(os.getcwd(), "filesys", "colonyData.json")
# ANSI color codes
RED = '\033[0;31m'
GREEN = '\033[0;32m'
YELLOW = '\033[0;33m'
NC = '\033[0m' # No color, to reset
class UI:
def __init__(self):
... | Olliyard/DWARVES | Master/Archived/ui - Copy.py | ui - Copy.py | py | 17,234 | python | en | code | 1 | github-code | 36 |
39155415013 | import nltk
from nltk.stem.lancaster import LancasterStemmer
stemmer = LancasterStemmer()
import numpy
import tflearn
import tensorflow
import random
import json
import pickle
with open('intents.json') as file:
data = json.load(file)
# If preprocessed data present no need to do again
try:
with open("data.pic... | docmhvr/AI_chatbot | main.py | main.py | py | 3,802 | python | en | code | 1 | github-code | 36 |
32413118307 | from flask import Flask, render_template, redirect, url_for
from flask_bootstrap import Bootstrap
from flask_ckeditor import CKEditor
from datetime import date
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
ckeditor = CKEditor(app)
Bootstrap(app)
app.config['SQLALCHEMY_DATABASE_URI'] = os.env... | matic56789/TriBap | main.py | main.py | py | 1,194 | python | en | code | 0 | github-code | 36 |
16044333714 | from config import *
import numpy as np
from os import listdir
from os.path import join, isdir
from tqdm import tqdm
import cv2
from tensorflow.keras.utils import to_categorical
import random
def create_dataset(dataset_path: str, data_aug: bool):
"""
Parameters
----------
dataset_path
path to ... | serginogues/cnn_lstm_activity_recognition | utils.py | utils.py | py | 5,139 | python | en | code | 0 | github-code | 36 |
38006333091 | # scp ./move_jetbot_17_11.py jetson@192.168.0.240:/home/jetson/Documents/jetbot-master/notebooks/collision_avoidance
# scp -r jetson@192.168.0.240:/home/jetson/Documents/jetbot-master/notebooks/collision_avoidance/images ./images
# scp -r ./images/dataset jetson@192.168.0.240:/home/jetson/Documents/jetbot-master/notebo... | panjacob/brainbot_movement | move_jetbot_na_samych_obrazach.py | move_jetbot_na_samych_obrazach.py | py | 4,770 | python | en | code | 0 | github-code | 36 |
16510917004 | import netmanthan
from netmanthan import _
from netmanthan.model.document import Document
from netmanthan.utils import cint
class BulkUpdate(Document):
@netmanthan.whitelist()
def bulk_update(self):
self.check_permission("write")
limit = self.limit if self.limit and cint(self.limit) < 500 else 500
condition ... | netmanthan/Netmanthan | netmanthan/desk/doctype/bulk_update/bulk_update.py | bulk_update.py | py | 1,792 | python | en | code | 0 | github-code | 36 |
4798482149 | import requests
from datetime import datetime
import smtplib
from dotenv import load_dotenv
import os
import time
load_dotenv(override=True)
EMAIL = os.environ.get("SENDER")
PWD = os.environ.get("PWD")
# From https://www.latlong.net/
MY_LAT = 6.320439
MY_LONG = -75.567467
# Your position is within +5 or -5 degree... | andresmesad09/iss_overhead | main.py | main.py | py | 1,721 | python | en | code | 0 | github-code | 36 |
9353725368 | import os
import atexit
import dotenv
from dotenv import load_dotenv
from flask import Flask
from flask import render_template, request, url_for, flash, redirect
from flask_bootstrap import Bootstrap5
from mexc_sdk import Spot
from agents import TradingAgent
from clients import MexcClient
def to_float(x):
try:
... | ArtemNechaev/traderbot | app.py | app.py | py | 2,908 | python | en | code | 0 | github-code | 36 |
646259858 | #Lista de Exercício 3 - Questão 21
#Dupla: 2020314273 - Cauã Alexandre Torres de Holanda e 2021327294 - Kallyne Ferro Veiga
#Disciplina: Programação Web
#Professor: Ítalo Arruda
#21.Faça um programa que peça um número inteiro e determine se ele é ou não um número primo. Um número primo é aquele que é divisível somen... | caalexandre/Revisao-Python-IFAL-2023-Caua-e-Kallyne | Lista3/l3q21KC-523.py | l3q21KC-523.py | py | 1,060 | python | pt | code | 0 | github-code | 36 |
40657145010 | import tensorflow as tf
import tensorlayer as tl
import numpy as np
import scipy
import time
import math
import argparse
import random
import sys
import os
import matplotlib.pyplot as plt
from model import *
from tensorlayer.prepro import *
from tensorlayer.layers import *
from termcolor import colore... | betairylia/Pokemon-Showdown-Win-Rate-Prediction | PokemonVector.py | PokemonVector.py | py | 5,926 | python | en | code | 7 | github-code | 36 |
17092661782 | def sum_digits(number=""):
sum = 0
for i in range(len(number)):
sum += int(number[i])
return sum
N, A, B = input().split()
sum = 0
for i in range(1, int(N) + 1):
result = sum_digits(str(i))
if (int(A) <= result and result <= int(B)):
sum += i
print(sum)
| kmdkuk/myAtCoder | abc083/b/main.py | main.py | py | 294 | python | en | code | 0 | github-code | 36 |
37069849941 | #!/usr/bin/python3
"""
Gather data from an API
"""
import json
import requests
import sys
def get_employee_name(employee_id):
"""
Function to get employee name
"""
base_url = "https://jsonplaceholder.typicode.com"
user_url = f"{base_url}/users/{employee_id}"
response = requests.get(user_url)
... | wughangar/alx-system_engineering-devops | 0x15-api/2-export_to_JSON.py | 2-export_to_JSON.py | py | 1,733 | python | en | code | 0 | github-code | 36 |
14298819617 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/1/1 0:31
# @Author : lingxiangxiang
# @File : demonlogging.py
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt=' %Y/%m/%d %H:%M:%S', filename='myapp.log', fil... | ajing2/python3 | Basics/module/demonlogging.py | demonlogging.py | py | 568 | python | en | code | 2 | github-code | 36 |
10162530454 | """ ====== About Me ======
Name: ShiftBruteForce
Author: Keith Martin
Version: 1.02
Description: Shifts a string n times through the alphabet
produces 25 result sets. One for each shift
in the english alphabet.
"""
enPhabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i',... | haltpotato/BruteForceShiftDecipher | main.py | main.py | py | 1,371 | python | en | code | 0 | github-code | 36 |
5915682093 | import argparse
import pickle as pk
import re
import signal
import time
import atexit
import traceback
import warnings
import sys
import os
import json
from collections import defaultdict
from threading import Thread
import pandas as pd
import psycopg2 as pg
from psycopg2.extras import RealDictCursor
from selenium.web... | BatyaGG/kaspibot | kaspibotV3.py | kaspibotV3.py | py | 41,975 | python | en | code | 0 | github-code | 36 |
21639084484 | import mysql.connector
connect = mysql.connector.connect(host="ensembldb.ensembl.org",
user="anonymous",
db="homo_sapiens_core_95_38")
woord = input("Waar wil je op zoeken? ")
cursor = connect.cursor()
cursor.execute("select * from gene "
... | hanbioinformatica/owe3a | DemoMySQL2/demo.py | demo.py | py | 490 | python | en | code | 0 | github-code | 36 |
29785722520 | from django.shortcuts import render,redirect
from django.views import View
from account.models import Contact,Staff
from home.models import Students
from .forms import Studentform
from django.contrib import messages
# Create your views here.
class Home(View):
def get(self,request):
return rende... | Afnas4/project1 | students/home/views.py | views.py | py | 3,323 | python | en | code | 0 | github-code | 36 |
15318192424 | from django.shortcuts import get_object_or_404
from rest_framework import viewsets, mixins, permissions, status
from rest_framework.decorators import action
from django.db.models import Q
from rest_framework.response import Response
from users.models import User, Profile, FriendRequest
from users.serializers import Us... | Mrklata/Twitter-Fb-alternative | users/api.py | api.py | py | 4,554 | python | en | code | 1 | github-code | 36 |
3965122741 | # GBM'in hız ve tahmin performansını arttırmak üzere optimize edilmiş; ölçeklenebilir ve farklı platformlara entegre edilebilir halidir.
# R, Python, Hadoop, Scala, Julia ile kullanılabilir.
# Ölçeklenebilirdir.
# Hızlıdır.
# Tahmin başarısı yüksektir ve bir çok Kaggle yarışmasında başarısını kanıtlamıştır.
# Özet... | gorkenvm/DataScienceBootcamp-Prepration | ML/Dogrusal Olmayan Regresyon Modelleri/9_XGBoost.py | 9_XGBoost.py | py | 2,575 | python | tr | code | 2 | github-code | 36 |
3915726214 | # 조이스틱
def solution(name):
answer = 0
min_moving = len(name) - 1 # 오른쪽으로 쭉 가면서 바꾸는 경우
for idx, alpha in enumerate(name):
# 문자 변경
answer += min(ord(alpha)-ord('A'), ord('Z')-ord(alpha)+1)
# A를 만났을 때, 뒤(왼쪽)로 돌아가는 방법 계산하기 위함
next_idx = idx + 1
while next_idx < len(name... | 10EastSea/programers-algo | greedy/42860.py | 42860.py | py | 1,824 | python | ko | code | 0 | github-code | 36 |
72498735783 | # my_list_1 = [1, 2, 3, 4]
# my_list_2 = ['a', 'b', 'c', 'd', 'e']
#
# joined = list(zip(my_list_1, my_list_2))
# print(joined)
#
# i, j = zip(*joined)
# print(i)
# print(j)
# import random
# for i in range(100):
# print(random.randint(1,100), end=' ')
#print(random.randint(1,99))
# import webbrowser
# webbrowser.... | astreltsov/firstproject | Giles_McMullen-Klein/DICTIONARY/LECTURES.py | LECTURES.py | py | 3,032 | python | en | code | 0 | github-code | 36 |
25938234352 | from sanic.request import File
from pydantic.class_validators import root_validator
from typing import Optional, Union, IO
import io
import openpyxl
from pydantic import Field
from infrastructure.configs.translation_task import FILE_TRANSLATION_TASKS, PLAIN_TEXT_TRANSLATION_TASKS, AllowedFileTranslationExtensionEnum
f... | KCDichDaNgu/KC4.0_DichDaNgu_BackEnd | src/modules/translation_request/domain/entities/translation_request.py | translation_request.py | py | 2,827 | python | en | code | 0 | github-code | 36 |
26744629167 | import torch
from torch import nn
import torch.nn.functional as F
"""
Components
"""
class ASPP_module(nn.Module):
def __init__(self, inplanes, planes, rate): # inplanes: input channel; planes: output channel
super(ASPP_module, self).__init__()
if rate == 1:
kernel_size = 1
... | yuanlinping/deep_colormap_extraction | netArchitecture/ASPP.py | ASPP.py | py | 2,239 | python | en | code | 7 | github-code | 36 |
28616363443 | from enum import Enum
from InsertOrder import InsertOrder, LifeSpan, Side
import sys
import exchange_pb2 as proto
import State
from time import sleep
from typing import Callable
from threading import Thread
from websocket import WebSocketApp
class ExchangeClient:
'''
A client class responsible for sending Ins... | UOA-CS732-SE750-Students-2022/project-group-magenta-mice | apps/data-generator/libs/ExchangeClient.py | ExchangeClient.py | py | 3,811 | python | en | code | 20 | github-code | 36 |
72573554664 | """
This file will contain the metrics of the framework
"""
import matplotlib.pyplot as plt
import numpy as np
import sklearn.metrics as mt
import wandb
class IOUMetric:
"""
Class to calculate mean-iou using fast_hist method
"""
def __init__(self, num_classes):
self.num_classes = num_classes
... | ArthurZucker/PAMAI | utils/metrics.py | metrics.py | py | 4,262 | python | en | code | 5 | github-code | 36 |
22704972874 | class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
import bisect
m = len(matrix)
if m == 0: return False
n = len(matrix[0])
if n == 0... | CHENG-KAI/Leetcode | Searcha2DMatrix.py | Searcha2DMatrix.py | py | 564 | python | en | code | 0 | github-code | 36 |
19260761331 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 29 13:45:16 2020
"""
from pytube import YouTube
import tkinter as tk
window=tk.Tk()
#########by teacher############
window.title("Youtube下載器")
window.geometry("500x150")
window.resizable(False,False)
#######################
progress=0
def showProgr... | JeffreyChen-coding/student-homework | mike1024.py | mike1024.py | py | 1,513 | python | en | code | 0 | github-code | 36 |
20240300556 | # Definition for singly-linked list.
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# @see https://qiita.com/KueharX/items/7112e8bd9dbf69f5c083
class Solution:
def mergeTwoLists(
self, list1: Optional[ListNode], list2... | sugitata/leetCode | linkedList/merge_two_sorted_list.py | merge_two_sorted_list.py | py | 1,286 | python | ja | code | 0 | github-code | 36 |
42912024062 | import cv2
from PIL import Image
import pytesseract
import re
import numpy as np
from url_camera import url
# En esta función podría quitar la parte en la que me guarda la imagen.
def capture_food():
cap = cv2.VideoCapture(url)
while True:
ret, frame = cap.read()
if frame is not None:
... | marinapm90/E-vitalos | Proyecto/scanning_ingredients.py | scanning_ingredients.py | py | 1,342 | python | en | code | 2 | github-code | 36 |
3131897866 | #https://open.kattis.com/problems/zanzibar
def calc(arr):
total = 0
for i in range(len(arr) - 1):
if int(arr[i]) * 2 < int(arr[i+1]):
total += int(arr[i+1]) - 2*int(arr[i])
else:
total += 0
return total
n = int(input())
nums = []
for i in range(n):
nums += [inp... | MrLuigiBean/Some-Open-Kattis-Problems | Python3/Stand on Zanzibar.py | Stand on Zanzibar.py | py | 379 | python | en | code | 0 | github-code | 36 |
17796731524 | from __future__ import absolute_import, division, print_function, unicode_literals
import os
import unittest
import xml.etree.ElementTree as ET
from builtins import object
from textwrap import dedent
from pants.base.build_environment import get_buildroot
from pants.util.contextutil import open_zip, temporary_dir
from... | fakeNetflix/twitter-repo-pants | tests/python/pants_test/backend/jvm/tasks/jvm_compile/zinc/zinc_compile_integration_base.py | zinc_compile_integration_base.py | py | 13,451 | python | en | code | 0 | github-code | 36 |
10492846310 | import cv2
import time
import os
# 비디오 파일 열기
cap = cv2.VideoCapture('./frames/test2.mp4')
# 비디오 파일이 성공적으로 열렸는지 확인
if not cap.isOpened():
print("Cannot open video file")
exit()
# 프레임 레이트 가져오기
fps = cap.get(cv2.CAP_PROP_FPS)
fps = 3
# 각 프레임에서 이미지를 추출하고 저장할 폴더 경로 설정
output_folder = 'frames/images'
if not os.pat... | chansoopark98/3D-Scanning | video_extract.py | video_extract.py | py | 1,759 | python | ko | code | 0 | github-code | 36 |
18230811445 | import nfc
from nfc.clf import RemoteTarget
from pybleno import *
def startup(targets):
print("waiting for new NFC tags...")
return targets
def connected(tag):
print("old message:")
if tag.TYPE == 'Type4Tag' and tag.ndef is not None:
if tag.ndef.records[0].uri == 'http://www.kddi.com/hr-nfc/... | shugonta/monitor_nfc | pynfc.py | pynfc.py | py | 660 | python | en | code | 0 | github-code | 36 |
14300366370 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 26 20:12:34 2021
@author: RISHBANS
"""
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 26 19:35:00 2021
@author: RISHBANS
"""
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Flatten, Dense
#Initialize CNN
model = Sequential()
... | edyoda/ML-with-Rishi | cnn_3.py | cnn_3.py | py | 1,545 | python | en | code | 4 | github-code | 36 |
12438520461 | from genericpath import isfile
import os
from cryptography.fernet import Fernet
file_list = []
for file in os.listdir():
if file == "ransom.py" or file == "dosyalari-sifrele.py" or file == "generatedkey.key" or file == "dosyalari-coz.py":
continue
if os.path.isfile(file):
file_list.append(fil... | karakayaahmet/Ransomware | dosyalari-coz.py | dosyalari-coz.py | py | 657 | python | en | code | 2 | github-code | 36 |
28639327912 | #-*- coding: GBK-*-
import time
from wxauto import *
import openai
import os
#代理端口
os.environ['HTTP_PROXY'] = 'http://127.0.0.1:7890'
os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:7890'
#https://platform.openai.com/overview
openai.api_key="your_key"
def chatretern(prompt,moudel_engine="gpt-3.5-turbo"):
cmpletio... | sfs999/win_chatgpt | chatwx.py | chatwx.py | py | 1,735 | python | en | code | 0 | github-code | 36 |
18079307891 | # dictionary object
planet_moons = {
'mercury': 0,
'venus': 0,
'earth': 1,
'mars': 2,
'jupiter': 79,
'saturn': 82,
'uranus': 27,
'neptune': 14,
'pluto': 5,
'haumea': 2,
'makemake': 1,
'eris': 1
}
# obtain a list of moons and number of planets
moons = planet_moon... | Shunlexxi/shun-30daysoflearningDataScience | MS Learn/averageMoon.py | averageMoon.py | py | 551 | python | en | code | 0 | github-code | 36 |
74050782824 | from parlai.core.message import Message
import unittest
class TestUtils(unittest.TestCase):
def test_message(self):
message = Message()
message['text'] = 'lol'
err = None
try:
message['text'] = 'rofl'
except RuntimeError as e:
err = e
assert... | facebookresearch/ParlAI | tests/test_messages.py | test_messages.py | py | 481 | python | en | code | 10,365 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.