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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
43513717152 | # Get light values from ESP32 at regular intervals and store in tLightValues
import mysql.connector
import logging
import requests
import time
from datetime import datetime
# Set up logging
logging.basicConfig(filename="/home/jkumar/Projects/logs/lightTracker/lightTracker.log", level=logging.INFO,format="%(asctime)s... | jitadityakumar/home-automation | lightTracker/python/getLightValues.py | getLightValues.py | py | 3,301 | python | en | code | 0 | github-code | 1 |
28602926196 | '''
このコードはimabariさんのコードを元に作成しています。
https://github.com/imabari/covid19-data/blob/master/aichi/aichi_ocr.ipynb
'''
import pathlib
import re
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import pytesseract
import csv
import recognize_main_summary_date_1 as date_pattern1
import recogni... | code4nagoya/covid19-aichi-tools | scrape_main_summary.py | scrape_main_summary.py | py | 5,379 | python | en | code | 6 | github-code | 1 |
23164289569 | from pathlib import Path
from math import ceil, log2
from progress.bar import Bar
import numpy as np
import pandas as pd
import rasterio
from rasterio.windows import get_data_window
import geopandas as gp
import shapely
from analysis.constants import INDICATORS, CORRIDORS
from analysis.lib.raster import write_raster... | astutespruce/secas-blueprint | analysis/prep/tiles/encode_pixel_layers.py | encode_pixel_layers.py | py | 6,876 | python | en | code | 0 | github-code | 1 |
34841964240 | # Copy List with Random Pointer:
# A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.
# Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to th... | KevinKnott/Coding-Review | Month 01/Week 01/Day 03/c.py | c.py | py | 3,618 | python | en | code | 0 | github-code | 1 |
17418906876 | import collections
import math
class Graph:
''' graph class inspired by https://gist.github.com/econchick/4666413
'''
def __init__(self):
self.vertices = set()
# makes the default value for all vertices an empty list
self.edges = collections.defaultdict(list)
self.weights... | nzavarinsky/Algorhitms | LABA4(dijkstra-algo)/dijkstra-v2.py | dijkstra-v2.py | py | 2,905 | python | en | code | 1 | github-code | 1 |
21429960495 | import os
import mock
import yaml
import unittest
import tempfile
from pathlib import Path
import setuppath
from ops.testing import Harness
from src.charm import AlgorandCharm
class BaseTestAlgoCharm(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""Setup class fixture."""
# Setup a ... | ZestBloom/charm-algorand-node | tests/unit/unittest_base.py | unittest_base.py | py | 3,335 | python | en | code | 0 | github-code | 1 |
74945482273 | Import('test_env')
import platform
testsrcs = ['#test/'+i for i in Split("""
assertimpl.c
printutil.c
redirectStdStreams.c
""")]
basesrcs = ['test_ascend_base.c']
srcs = []
for dir in ['general','utilities','solver','linear','compiler']:
srcs += test_env['TESTSRCS_'+dir.upper()]
cpppath = ['#','#ascend']
if ... | georgyberdyshev/ascend | test/base/SConscript | SConscript | 1,297 | python | en | code | 5 | github-code | 1 | |
42373937252 | import itertools as it
from functools import reduce
import numpy as np
from qiskit import QuantumCircuit
from libbench.ibm import Job as IBMJob
class IBMSchroedingerMicroscopeJob(IBMJob):
@staticmethod
def job_factory(
num_post_selections, num_pixels, num_shots, xmin, xmax, ymin, ymax, add_measureme... | rumschuettel/quantum-benchmarks | benchmarks/Schroedinger-Microscope/ibm/job.py | job.py | py | 2,226 | python | en | code | 5 | github-code | 1 |
71312255075 | from PyQt6.QtWidgets import QDialog, QPushButton, QLineEdit, QRadioButton, QComboBox, QListWidget, QFileDialog, QMessageBox
from PyQt6 import uic
import sys
import time
import os
from absPath import resource_path
from LMSdataBackend import schoolClass_CRUD
from LMSdataBackend import gradeJHS_CRUD
from LMSdataBackend i... | jpcanas/School_LMSv2 | LMS_v2.1/LMSUiFrontend/cardExportWindow.py | cardExportWindow.py | py | 4,799 | python | en | code | 0 | github-code | 1 |
26647008274 | from newspaper import Article
from splitText import SplitText
from summarizer import Summarizer
from summarizingFuncs import naiveTextRank
TEST_ARTICLE = "http://www.lefigaro.fr/vie-bureau/2017/10/06/09008-20171006ARTFIG00032-japon-une-journaliste-meurt-apres-159-heures-sup-en-un-mois.php"
TEST_ARTICLE2 = "http://www.l... | AelHenri/TLDR-bot | TLDR/main.py | main.py | py | 784 | python | en | code | 0 | github-code | 1 |
26539795806 | from utilities.ltspice.ltpice_reader import LTSpiceReader
from utilities.ltspice.ltspice_bode_reader import LTSpiceBodeReader
from utilities.ltspice.ltspice_time_graph_reader import LTSpiceTimeGraphReader
from plot_tool.data.magnitudes import GraphMagnitude
from plot_tool.data.function import GraphFunction
from plot_to... | grupo-tc-volcan/plot-tool | utilities/ltspice/ltspice_reader_interface.py | ltspice_reader_interface.py | py | 4,321 | python | en | code | 0 | github-code | 1 |
24281269113 | import pandas as pd
def pop_data(country_df):
country_age = country_df.Age.tolist()
description_field = []
for i in range(len(country_age)):
if country_df.Sex.tolist()[i] == 'f':
try:
description_field.append('Women population ' + country_age[i] + ' to ' +\
... | pedrocamargo/road_analytics | notebooks/functions/population_data.py | population_data.py | py | 1,093 | python | en | code | 0 | github-code | 1 |
74818066594 | import tensorflow as tf
from example import Example
tf.enable_eager_execution()
def test_one_rule_body():
weights = tf.Variable([0.5, 1.0], dtype=tf.float32, name='weights')
model_shape = 2
weight_indices = tf.Variable([0], dtype=tf.int32)
body = tf.constant([[[0]]])
negs = tf.constant([[False]]... | chawkm/supported-ILP | common/test_example_eagerly.py | test_example_eagerly.py | py | 2,314 | python | en | code | 0 | github-code | 1 |
39409212934 | import cv2
import face_recognition
import put_chinese_text
import time
VIDEO_DIR = 'hamilton_clip.mp4'
resize_ratio = 0.5
input_video = cv2.VideoCapture(VIDEO_DIR) # 读取视频文件
length = int(input_video.get(cv2.CAP_PROP_FRAME_COUNT)) #视频帧数
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 视频编码器
output_video = cv2.VideoWrit... | Mikoto10032/FaceRecognition | face_recognition_in_video_file.py | face_recognition_in_video_file.py | py | 3,094 | python | en | code | 0 | github-code | 1 |
15749350207 | from pymongo import MongoClient
import pandas as pd
client = MongoClient()
db = client['Capstone']
parcels = db["ParcelsWithVariables"]
def TransformData(Xin):
X = Xin
# Do a one-hot encoding of the nhood ids into seperate variables
# to prevent them being treated numerically when they are categorical
nhood = pd.... | IvoDonev/DSCapstone | GetTrainingData.py | GetTrainingData.py | py | 1,401 | python | en | code | 0 | github-code | 1 |
41732364356 | #!/usr/bin/env python3
import csv
import crayons
def main():
dict_from_csv = {}
with open('animal_riddle.csv', mode='r') as riddle_file:
reader = csv.reader(riddle_file)
dict_from_csv = {rows[0]:rows[1] for rows in reader}
print(dict_from_csv)
# print crayons.red('red string')
main() | marylongnguyen/alta3research-python-cert | alta3research-pythoncert01.py | alta3research-pythoncert01.py | py | 320 | python | en | code | 0 | github-code | 1 |
28336979424 | import intReader
def TopoSort():
print ("Topologischen Sortieren.")
# Einlesen
input = intReader.readInt()
n = next(input)
# Inititalisieren array:
Knotenliste = [None] + [ Knoten(i) for i in range(1,n+1) ]
# Einlesen Kanten
try:
while True:
e = Knotenliste[nex... | qiaw99/WS2019-20 | DataStructure/U1/Lecture/topoSort-mit-push-und-pop.py | topoSort-mit-push-und-pop.py | py | 1,405 | python | de | code | 0 | github-code | 1 |
7590499685 | """
Transfer Learning (Time Delayed) version of the Convolutional Denoising Autoencoder
Contains functions to read in preprocessed data, split according to training parameters,
train models, and save model outputs
"""
import logging
from numpy.random import seed
seed(1)
import tensorflow
tensorflow.random.set_seed(2)
... | RiceD2KLab/TCH_CardiacSignals_F20 | src/models/autoencoders/cdae_timedelay.py | cdae_timedelay.py | py | 8,531 | python | en | code | 2 | github-code | 1 |
15429008868 | import discord
from discord.ext import commands, tasks
import requests
import json
import html
import random
# Commands for Trivia game
class triviaCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def trivia(self, ctx):
mention = ctx.author.mention... | brandenphan/Pami-Bot | Commands/trivia.py | trivia.py | py | 5,230 | python | en | code | 1 | github-code | 1 |
28917567329 | import healpy as hp
from astropy import units as u
from astropy.coordinates import SkyCoord
from numpy import *
import numpy as np
import matplotlib.pyplot as plt
import healpy as hp
from astropy.io import fits
with fits.open('gsm_182mhz_Jysr_nomono_nogalaxy_2048.fits') as hdu:
data = hdu[0].data
with fits.open('... | nicholebarry/gar_scripts | woden_scripts/temp_plotter.py | temp_plotter.py | py | 3,024 | python | en | code | 0 | github-code | 1 |
42313374761 | """Module for operating with DB in .csv format"""
from book_class import Book
import console
from note_class import Note
pathCSV = 'db.csv'
def save(book: Book):
with open(pathCSV, 'w', encoding='utf-8') as file:
for note in book.book_lst:
file.write(note.note_to_str_line() + ';\n')
con... | igorkunovski/notes | config_db.py | config_db.py | py | 723 | python | en | code | 0 | github-code | 1 |
21531841556 | import pandas as pd
from joblib import dump, load
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier, VotingClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import f1_score
from utils import l... | daniel-yehezkel/DS.DPA.HW1 | train.py | train.py | py | 1,254 | python | en | code | 0 | github-code | 1 |
8702400345 | import streamlit as st
import altair as alt
import inspect
from vega_datasets import data
@st.experimental_memo
def get_chart_72043(use_container_width: bool):
import altair as alt
import pandas as pd
import numpy as np
np.random.seed(1)
source = pd.DataFrame({
'x': np.arange(100)... | streamlit/release-demos | 1.16.0/demo_app_altair/pages/71_Scatter_With_Loess.py | 71_Scatter_With_Loess.py | py | 1,216 | python | en | code | 78 | github-code | 1 |
71188839073 | # Top 10 word occurences from a file Python Sample
# Author: Sriram Srinivasan
# Written On: 08/09/2019
fileHandle = open('Hamlet.txt')
counts = dict()
for line in fileHandle:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
lst = list()
for key, val in counts.items():
... | fullstack-sriram/Python | Basics/toptenwords.py | toptenwords.py | py | 452 | python | en | code | 0 | github-code | 1 |
11371082097 | #!/usr/bin/env python
from collections import OrderedDict
import rows
class BrazilianMoneyField(rows.fields.DecimalField):
"""Parser for money in Brazilian notation
"1.234,56" -> Decimal("1234.56")
"""
@classmethod
def deserialize(cls, value):
value = (value or "").replace(".", "").repl... | julianyraiol/portal_transparencia_am | antigo/pdf_parser.py | pdf_parser.py | py | 2,419 | python | en | code | 4 | github-code | 1 |
8125849858 | #!/usr/bin/env python
"""Apply a threshold to an image for background subtraction."""
__author__ = "Anas Abou Allaban"
__maintainer__ = "Anas Abou Allaban"
__email__ = "anas@abouallaban.info"
import cv2
import numpy as np
def printImage(image):
cv2.imshow('Test', image)
cv2.waitKey(0)
cv2.de... | piraka9011/EECE5550_MobileRobotics | mobile_robotics_utilities/scripts/threshold_image.py | threshold_image.py | py | 1,348 | python | en | code | 0 | github-code | 1 |
72198180835 | from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import preprocessing
from sklearn.neighbors import NearestCentroid
def cv2NN(X_train, X_test, y_train, y_test, kneighbors, metric ='euclidean', scalling = Fals... | karmelowsky/AcuteInflammations | myFunctions.py | myFunctions.py | py | 1,517 | python | en | code | 0 | github-code | 1 |
31765432845 | import cv2
import time
class Camera():
def __init__(self):
self.capture = cv2.VideoCapture('resource/capture.mp4')
# cv2.namedWindow('test')
def get_image(self, t):
t=1000
ret = self.capture.set(cv2.CAP_PROP_POS_FRAMES, t)
ret, frame = self.capture.read()
if ret ... | cande-cansat/SatSAT | SocketTest/satellite_camera.py | satellite_camera.py | py | 568 | python | en | code | 0 | github-code | 1 |
25833334472 | #!/usr/bin/python3
import sys, os
from PIL import Image
#import tinify
#tinify.key = "bjRHvxqtkW0Lw3vIVMUc2-aM-kxMfYln"
origin_file = sys.argv[1]
dst_path = str(os.path.dirname(origin_file)) + '/p_i/'
base_name = str(os.path.basename(origin_file))
file_name, file_extension = os.path.splitext(base_name)
print( ... | mijkenator/muploader | tinify/tf_mbd180.py | tf_mbd180.py | py | 1,043 | python | en | code | 0 | github-code | 1 |
2129904597 | #!/usr/bin/env python3
import sys
from heapq import nlargest
import json
from math import *
ratings = {}
rest = {}
visited = []
#function jaccard
#calculate the similarity index between two teammated by their ID's
#parameters- ratings, id1, id2
#ratings - the dictionary of ratings that got established in init()
#id... | dgeorge10/suitable-puzzles | recommendation/solution.py | solution.py | py | 6,538 | python | en | code | 0 | github-code | 1 |
30199618731 | from array import *
newarray = array('i', [4,5,6,7,8])
# for char we use typecode u - unicodes
# address and length of an array
# if you dont know the type
newValuedArray = array(newarray.typecode, (a for a in newarray))
# print(newarray.buffer_info())
#
# print(newarray)
#
# print(newarray.typecode)
#
# newarray.re... | salonikalsekar/Python | arrays.py | arrays.py | py | 582 | python | en | code | 0 | github-code | 1 |
19595095260 | from django.forms import ModelForm
from product.models import Product
from django import forms
class ProductForm(ModelForm):
class Meta:
model = Product
exclude = ["modified", "created"]
def __init__(self, **kwargs):
super().__init__(**kwargs)
ignore_fields = ["image"]
... | mbijou92/erp | gallery_backend/forms.py | forms.py | py | 606 | python | en | code | 0 | github-code | 1 |
16764330428 | # -*- coding: utf-8 -*-
"""
@author: kripa
"""
import pandas as pd
#reading the data in python
emp = pd.read_csv('unemployment.csv', delimiter= ',',
skiprows=6,
na_values='NA', #null values
usecols= ['Fips', 'Location'... | eraasch123/HW3 | unemployment.py | unemployment.py | py | 531 | python | en | code | 0 | github-code | 1 |
43495756114 | import numpy as np
from numpy import ndarray
from classes.utils import r2oos
from classes.data_loader import DataLoader
from sklearn.linear_model import ElasticNet
from sklearn.model_selection import GridSearchCV
class ElasticNet_Model(object):
def __init__(self, data_loader: DataLoader, alpha: float = 1.0, l1_r... | Sho-Shoo/36490-F23-Group1 | classes/elasticNet_model.py | elasticNet_model.py | py | 4,506 | python | en | code | 0 | github-code | 1 |
36571795647 | from flask import jsonify, request
from flask_restful import Resource
from Model import db, VistorLevel, LevelOptionsSchema, Level2OptionsSchema, Vistor, LocationOptionSchema
from webargs import fields, validate
from webargs.flaskparser import use_args, use_kwargs, parser, abort
level_schema = LevelOptionsSchema
leve... | donc310/WidgetApi | resources/Levels.py | Levels.py | py | 1,692 | python | en | code | 0 | github-code | 1 |
18468558231 | import numpy as np
import pylab as pl
from sklearn import mixture
np.random.seed(0)
#C1 = np.array([[3, -2.7], [1.5, 2.7]])
#C2 = np.array([[1, 2.0], [-1.5, 1.7]])
#
#X_train = np.r_[
# np.random.multivariate_normal((-7, -7), C1, size=7),
# np.random.multivariate_normal((7, 7), C2, size=7),
#]
X_train = np.r_[
... | sum-coderepo/Optimization-Python | Assignments_SMAI/BayesianClassifier.py | BayesianClassifier.py | py | 1,043 | python | en | code | 2 | github-code | 1 |
4966009254 | from gtts import gTTS
from playsound import playsound
import os
import queue
import threading
import logging
logging.basicConfig(level=logging.INFO)
class AudioPlayer:
def __init__(self):
self.audio_queue = queue.Queue()
def play_audio(self, file_path):
"""
Play the audio and signal ... | TheoTime01/ChatMoov | text_to_speech/text_to_speech.py | text_to_speech.py | py | 2,681 | python | en | code | 0 | github-code | 1 |
34855863470 | from abc import abstractmethod
from .base_autoencoder import BaseAutoencoder
import tensorflow as tf
import numpy as np
import time
from .utils import compute_mmd
class BaseInfoVariationalAutoencoder(BaseAutoencoder):
def __init__(self, input_dims, latent_dim, hidden_dim=1024, alpha=0.1):
super(BaseInfoVariation... | KienMN/Autoencoder-Experiments | autoencoders/info_vae.py | info_vae.py | py | 4,251 | python | en | code | 2 | github-code | 1 |
27211364983 | # -*- coding: utf-8 -*-
__author__ = 'kevin'
from openerp import models, api, fields, _
from openerp.exceptions import Warning
class purchase_invoice_onreceiving(models.TransientModel):
_name = 'purchase.invoice.onreceiving'
_description = u'采购进货发票开立'
@api.model
def _get_journal(self):
journ... | kh1688/four-old | purchase_receive/wizard/purchase_invoice_onreceiving.py | purchase_invoice_onreceiving.py | py | 2,611 | python | en | code | 0 | github-code | 1 |
8699137278 | # -*- coding: utf-8 -*-
import json
import pymongo
import re
import scrapy
from scrapy import Request, FormRequest
import logging
import redis
from sqlalchemy import create_engine
import pandas as pd
from sandbox.items import SXRItem,XZCFItem
from sandbox.utility import get_header
# get
class WebGetSpider(scrapy.Spid... | Rockyzsu/image_recognise | xinyong_shenzhen/sandbox/sandbox/spiders/website.py | website.py | py | 7,699 | python | en | code | 3 | github-code | 1 |
40061188327 | # https://www.acmicpc.net/problem/18352
# N개의 도시, M개의 도로
# 모든 도로의 거리 1
# 특정 도시 X르 부터 출발하여 도달할 수 있는 모든 도시 중에 최단 거리가 K인 도시 번호 출력
import sys
from collections import defaultdict
from collections import deque
def BFS(X):
qu = deque()
qu.append(X)
dist[X] = 0
while qu:
node = qu.popleft()
f... | hyein99/Algorithm_python_for_coding_test | Part3/ch13_DFS BFS 문제/15_특정 거리의 도시 찾기.py | 15_특정 거리의 도시 찾기.py | py | 999 | python | ko | code | 0 | github-code | 1 |
72340313954 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolios', '0002_auto_20170514_1729'),
]
operations = [
migrations.AlterField(
model_name='portfolioprovider',... | zakvan2022/Betasmartz | portfolios/migrations/0003_auto_20170519_0144.py | 0003_auto_20170519_0144.py | py | 469 | python | en | code | 1 | github-code | 1 |
17684234926 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 5 17:12:07 2017
@author: Aniket
"""
import gym
import universe
import random
def determine_turn(turn, observation_n, j, total_sum, prev_total_sum, reward_n):
if(j>=15):
if(total_sum/j) == 0:
turn = True
else:
turn = Fals... | aniketparsewar/Machine-Learning | OpenAI_Universe.py | OpenAI_Universe.py | py | 1,961 | python | en | code | 0 | github-code | 1 |
19054857270 | import random
class thoughts:
def getThought(self):
self.thought =[{
"title":"Move quickly. Now is the time to make progress"
},{
"title":"Today is a good day"
},{
"title":"Show everyone what you can do"
}]
return random... | irahulgulati/newsapi | newsapi/app/views/thought.py | thought.py | py | 355 | python | en | code | 0 | github-code | 1 |
3476101470 | # -*- coding: utf-8 -*-
"""
Trains and tests a Rolling Bayesian Ridge Regression model on data
@author: Nick
"""
import warnings
import numpy as np
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.feature_selection import VarianceThreshold
from sklearn.preprocessing import MinMaxScal... | N-ickMorris/Time-Series | crime_rolling_lasso.py | crime_rolling_lasso.py | py | 2,646 | python | en | code | 0 | github-code | 1 |
14819263875 | #!/usr/bin/env python3
import os
def parse_input(content: str) -> tuple[list[int], list[list[list[int]]]]:
numbers = []
boards = []
for line in content.split(os.linesep):
line = line.strip()
if not line:
boards.append([])
continue
if "," in line:
... | lolguinan/aoc-py | src/year2021/day04b.py | day04b.py | py | 2,555 | python | en | code | 0 | github-code | 1 |
36688920933 | '''
A retailer sells two products: Apples and Oranges. Each apple weighs 75 grams.
Each orange weighs 112 grams.
Write a program that reads the number of apples and the number of oranges in an order from the user.
Then your program should compute and display the total weight of the order.
'''
n1= input ("Enter the we... | sandhyalethakula/Iprimed_16_python | ASSGN-NUMBERS-Aug13-Q2-sandhyalethakula.py | ASSGN-NUMBERS-Aug13-Q2-sandhyalethakula.py | py | 747 | python | en | code | 0 | github-code | 1 |
2505498450 |
import psycopg2
hostname = 'localhost'
database = 'demo'
username = 'postgres'
pwd = '12345'
port_id = 5432
conn = None
cur = None
conn = psycopg2.connect(host= hostname,
port = port_id,
dbname = database,
user = username,
password = pwd)
cur = conn.cursor()
create_script = ''' CREATE TABLE T_emp... | ELFAHIM96/Python-and-PostgreSQL | Postgre2python.py | Postgre2python.py | py | 722 | python | en | code | 0 | github-code | 1 |
70365065314 | from flask import Flask, jsonify, request
from flask_cors import CORS
from note import models as note_model
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
CORS(app, supports_credentials=True)
@app.before_request
def __db_connect():
note_model.db.connect()
@app.teardown_request
def _db_close(exc):
... | HyperionD/api | api.py | api.py | py | 2,625 | python | en | code | 0 | github-code | 1 |
28147315416 | import os
import sys
import json
import unittest
sys.path.append("../get_job/")
import jobs
class TestDB(unittest.TestCase):
def setUp(self):
self.job_db = jobs.JobDB()
self.job_db.dbFile = "data_test.json"
def test_readData(self):
""" Test loading data """
self.job_db.readDat... | SV3A/Jobbi | tests/jobs_tests.py | jobs_tests.py | py | 2,972 | python | en | code | 0 | github-code | 1 |
11404152952 | import pandas as pd
from tqdm import tqdm
from gensim.models import Doc2Vec
from sklearn import utils
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from gensim.models.doc2vec import TaggedDocument
import matplotlib.pyplot as plt
import nltk
import multiprocessi... | kschutter/SarcasmDetection | src/logisticReg.py | logisticReg.py | py | 2,982 | python | en | code | 0 | github-code | 1 |
11726393436 | import side_by_side
import convolution
import numpy as np
from PIL import Image
from sys import argv
import math
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
def canny_img(im_init):
def gaussiano(im):
gaussian = np.ones((5,5), dtype=np.float);
gaussian[:,:] = [
... | gciruelos/imagenes-practicas | practica7/ejclase.py | ejclase.py | py | 6,141 | python | en | code | 0 | github-code | 1 |
70717531875 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 27 12:45:18 2017
@author: XPS 13 9350
"""
def keysWithValue(aDict, target):
'''
input: aDict: a dictionary
target: an integer
return: returns a list of keys in aDict with the value target
If aDict does not contain the value target, retu... | yyyyyykkk/Algorithms-and-Data-Structures | MIT Python/keysWithValue.py | keysWithValue.py | py | 477 | python | en | code | 0 | github-code | 1 |
36684105915 | from .settings_frontend import *
from .settings_prod import *
ALLOWED_HOSTS = [FRONTEND_DOMAIN]
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': 'unix:/var/run/memcached.sock',
'KEY_PREFIX': 'PROD',
}
}
| techquilateam/rozklad | settings/settings_frontend_prod.py | settings_frontend_prod.py | py | 302 | python | en | code | 1 | github-code | 1 |
13043003078 | from iotile.core.utilities.paths import settings_directory
import sqlite3
import os.path
import sys
import os
class SQLiteKVStore:
"""A simple string - string persistent map backed by sqlite for concurrent access
The KeyValueStore can be made to respect python virtual environments if desired
"""
Def... | iotile/coretools | iotilecore/iotile/core/utilities/kvstore_sqlite.py | kvstore_sqlite.py | py | 2,544 | python | en | code | 14 | github-code | 1 |
20255659902 | import numpy as np
from PIL import Image
from progress.bar import Bar
# (parameter), point
def ikeda(u):
def a(p):
x, y = p
t = 6.0/((x**2)+(y**2)+1)
c = np.cos(t)
s = np.sin(t)
return (1+u*((x*c)-(y*s)), u*((x*s)+(y*c)))
return a
# size, range, point
def toidx(size, R,... | OneAndZero24/ikeda | ikeda.py | ikeda.py | py | 1,572 | python | en | code | 0 | github-code | 1 |
36866466309 | """
Index Of an Extra Element
https://practice.geeksforgeeks.org/problems/index_of_an_extra_element/1
Given two sorted arrays. There is only 1 difference between the arrays.
First array has one element extra added in between. Find the index of the extra element.
Input:
The first line of input contains an integer T, d... | dtom90/Algorithms | Arrays/index-of-an-extra-element.py | index-of-an-extra-element.py | py | 1,671 | python | en | code | 0 | github-code | 1 |
30243853001 | import collections
import datetime
import os
import random
import shutil
import sys
import time
import numpy as np
import torch
from PIL import Image
class AverageMeter(object):
'''
Taken from:
https://github.com/keras-team/keras
'''
"""Computes and stores the average and curren... | akwasigroch/Pretext-Invariant-Representations | utils.py | utils.py | py | 11,632 | python | en | code | 89 | github-code | 1 |
74374436192 | from . import PRIMARY, SECONDARY, BACKGROUND, DETAIL, INVERSE_BG
class Tint:
"""this is only here to make the process more modular
use `PyTint().tint_svg()` instead.
"""
def __init__(self, svg_in: str) -> None:
self.__primary = PRIMARY
self.__secondary = SECONDARY
self.__backg... | toufy/pytint | pytint/tint.py | tint.py | py | 2,519 | python | en | code | 0 | github-code | 1 |
39285707049 | from PIL import Image, ImageEnhance, ImageOps
import PIL.ImageDraw as ImageDraw
import numpy as np
import random
class RandAugmentPolicy(object):
"""Randomly choose one of the best 25 Sub-policies on CIFAR10.
Example:
>>> policy = RandAugmentPolicy()
>>> transformed = policy(image)
Example as a Py... | PrateekMunjal/TorchAL | al_utils/autoaugment.py | autoaugment.py | py | 8,697 | python | en | code | 56 | github-code | 1 |
36503733262 | age = int(input("Please enter your age: "))
if age > 18:
print("You are " + str(age) + " years old. You're eligable to vote!")
else:
print("You are too young to vote!")
car = input("What care make would you like to rent today: ")
print("Lets see if I can find you a " + car.title() + " vehicle.")
group_size =... | JBolanle/PythonCrashCourseProjects | Chapter7/parrot.py | parrot.py | py | 1,147 | python | en | code | 0 | github-code | 1 |
30335073768 | from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
import psycopg2
# Create your views here.
def init(request):
try:
conn = psycopg2.connect(
database = 'djangotraining',
host = 'localhost',
user = 'djangouser',
passwo... | RickBadKan/42-mini-piscina | list05/ex02/views.py | views.py | py | 2,598 | python | en | code | 2 | github-code | 1 |
3553966386 | from __future__ import print_function
import pyaudio
from ibm_watson import SpeechToTextV1
from ibm_watson.websocket import RecognizeCallback, AudioSource
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from threading import Thread
import configparser
import time
import json
import requests
from requests... | omboido/telefone_sem_fio | dic.py | dic.py | py | 5,238 | python | en | code | 0 | github-code | 1 |
11735587857 | import pyrebase
import matplotlib.pyplot as plt
firebaseConfig = {"apiKey": "AIzaSyCfuQ46q09FozGesUxT3ZakA_7XhGrnrUM",
"authDomain": "fir-course-56a13.firebaseapp.com",
"projectId": "fir-course-56a13",
"storageBucket": "fir-course-56a13.appspot.com",
"messagingSenderId": "447378702514",
"appId": "1:44737870... | ifran-rahman/Python-Firebase | pythonProject/main.py | main.py | py | 2,608 | python | en | code | 0 | github-code | 1 |
37286208612 | print("Can I form a Triangle?")
def is_traingle(sd1,sd2,sd3):
if((sd1+sd2>sd3)and(sd1+sd3>sd2)and(sd2+sd3>sd1)):
print(f"You can form the triangle with sides : {sd1},{sd2},{sd3}")
else:
print(f"You cannont form the triangle with sides : {sd1},{sd2},{sd3}")
def input_sides():
sides=[]
fo... | HordesOfGhost/LearningML | StatsBasic/dd.py | dd.py | py | 498 | python | en | code | 0 | github-code | 1 |
75267266272 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
import os
import tensorflow as tf
from model import Unrolled_GAN
from data_utils import Processor
flags = tf.ap... | gokul-uf/TF-Unrolled-GAN | main.py | main.py | py | 4,491 | python | en | code | 5 | github-code | 1 |
18638555644 | # reference -https://towardsdatascience.com/machine-learning-nlp-text-classification-using-scikit-learn-python-and-nltk-c52b92a7c73a
from sklearn.feature_extraction.text import CountVectorizer,TfidfTransformer
count_vect = CountVectorizer(lowercase = False, ngram_range = (1,2), max_df=0.95)
tfidf_transformer = TfidfTra... | devanshi16/hackerRank-NLP | byte-the-correct-apple.py | byte-the-correct-apple.py | py | 1,728 | python | en | code | 0 | github-code | 1 |
7898200713 | from django.shortcuts import render
from .models import Product, OrderProduct, Department
from django.http import HttpResponse
from django.template import loader
import heapq
from operator import itemgetter
# server functions
def ticket_promedio():
order_products = OrderProduct.objects.all()
orders = {}
f... | PaulaGonzalez01/SalesHistory | sales_history/views.py | views.py | py | 2,968 | python | en | code | 0 | github-code | 1 |
17422411853 | from pathlib import Path
from typing import Any, Dict, List, Union
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import yaml
from torch import Tensor
from torchmetrics import Dice, JaccardIndex
from transformers import EvalPrediction
class ComputeMetrics(object):
def __ini... | GerasimovIV/kvasir-seg | src/metrics.py | metrics.py | py | 2,666 | python | en | code | 0 | github-code | 1 |
27214350964 | import numpy as np
import time
import uuid
from models.Basic import Basic
from gurobipy import *
class FairIR(Basic):
"""Fair paper matcher via iterative relaxation.
"""
def __init__(self, loads, loads_lb, coverages, weights, thresh=0.0):
"""Initialize.
Args:
loads - a list... | iesl/fair-matching | src/models/FairIR.py | FairIR.py | py | 12,878 | python | en | code | 11 | github-code | 1 |
26912223444 |
# Класс для точек программы
from math import cos, sin, radians, pi
class Figure():
def __init__(self):
self.dots = list()
self.connections = list()
def figure_clear(self):
self.dots.clear()
self.connections.clear()
def get_dots_count(self):
... | gga21u142/sem_4_CG | cg_lab_02/figure.py | figure.py | py | 3,009 | python | en | code | 0 | github-code | 1 |
8306566749 | import sys, os, pickle
DIR = os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
sys.path.append(DIR)
from Dataset.mnist import load_mnist
from functions import *
from PIL import Image
def img_show(img):
pil_img = Image.fromarray(np.uint8(img))
pil_img.show()
def get_data():
(x_tr... | PresentJay/Deep-Learning-from-Scratch | [03]신경망/03_MNIST/01_inference-with-forward-propagation.py | 01_inference-with-forward-propagation.py | py | 1,815 | python | en | code | 0 | github-code | 1 |
23549497570 | import os
import re
import shutil
import subprocess
import sys
import toml
MD_ANCHOR_LINKS = r"\[(.+)\]\(#.+\)"
def slugify(s):
"""
From: http://blog.dolphm.com/slugify-a-string-in-python/
Simplifies ugly strings into something URL-friendly.
>>> print slugify("[Some] _ Article's Title--")
some... | getzola/themes | generate_docs.py | generate_docs.py | py | 6,271 | python | en | code | 53 | github-code | 1 |
7425876986 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import logging
from ..json_struct_patch import JsonStructPatch
def test_properties_diff():
local = {'rsyslog': {'facility': 2}}
template = { "rsyslog": {
"properties": {
"facility": {
"index": ... | t0ffel/validate-es-documents | src/json_diff/test/test_template.py | test_template.py | py | 2,732 | python | en | code | 0 | github-code | 1 |
20524425789 | from tkinter import Canvas
from .WidgetsCore import create_round_rectangle
class ResizableCanvas(Canvas):
"""Resizeable Canvas"""
__desc__ = "Canvas resizes to fit frame on configure event."
def __init__(self, parent, **kw):
Canvas.__init__(self, parent)
self.configure(borderwidth=0)
... | AndrewSpangler/py_simple_ttk | src/py_simple_ttk/widgets/ResizableCanvas.py | ResizableCanvas.py | py | 1,400 | python | en | code | 2 | github-code | 1 |
13117903532 |
# coding: utf-8
# In[ ]:
from __future__ import division
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
import scipy.linalg
import time
import random
def print_np(x):
print ("Type is %s" % (type(x)))
print ("Shape is %s" % (x.shape,))
print ("Values are: \n%s" % (x))
class Opti... | taewankim1/robust_mpc_obstacle_avoidance | constraints/constraints.py | constraints.py | py | 2,204 | python | en | code | 28 | github-code | 1 |
70572585953 | from django.forms import ModelForm
from django.utils.translation import gettext_lazy as _
from . import models
class LivreForm(ModelForm):
class Meta:
model = models.Livre
fields = ('titre', 'auteur', 'date_parution', 'nombre_pages','resume')
labels = {
'titre' : _('Titre'),
... | arnauldAlbert/django-model | modele/bibliotheque/forms.py | forms.py | py | 751 | python | fr | code | 0 | github-code | 1 |
69890623394 | import requests
from django.shortcuts import redirect, render
from animal.models import Siliao,Zhongzhu,Peizhong,Renjian,Fenmian,Caijing,Xingweiy
from django.http import JsonResponse
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from animal.models import Site_Info, User
from ... | yurooc/Breed-pigs-Management-system | animalManage/views.py | views.py | py | 9,322 | python | en | code | 1 | github-code | 1 |
2573566116 | import re
from dist_measurer import Dist_measurer
class Cs_Sk_dist_measurer( Dist_measurer):
def __init__( self, lang_reverse=False, **kwargs):
super().__init__( **kwargs)
self.dist_00_strings = [('t$', 'ť$'),
('ci$', 'cť$')
]
... | Jankus1994/ud-valency | udapi-python/udapi/block/valency/backups/b_1_10_2022/cs_sk_dist_measurer.py | cs_sk_dist_measurer.py | py | 6,614 | python | en | code | 0 | github-code | 1 |
75065182433 | __all__ = [
"calc",
]
import copy
import json
import logging
from pathlib import Path
import pickle as pk
from typing import NoReturn, Optional, Tuple
import numpy as np
import torch
from torch import Tensor
from torch.utils.data import DataLoader
from . import _config as config
from . import dirs
from . import... | ZaydH/target_identification | fig01_cifar_vs_mnist/poison/influence_func.py | influence_func.py | py | 12,090 | python | en | code | 5 | github-code | 1 |
26579217754 | # Data Sonification Project - LITR 0110D
import csv
from datetime import datetime
from miditime.miditime import MIDITime
from scipy import stats
import math
# instantiate the MITITime class with tempo 120 and 5sec/year
mymidi = MIDITime(120, 'data_sonfication.mid', 1, 5, 1)
# load in climate data as dictionary
climat... | pattwm16/climate_sonification | data_sonification.py | data_sonification.py | py | 2,655 | python | en | code | 0 | github-code | 1 |
24887452366 | import os
import json
import aloe
from werkzeug.datastructures import MultiDict
from nose.tools import assert_equals
import flask_login
import sqlalchemy
from app import app
from app.database import db
from app.models.university import University, UniversityPending
from ..steps import fieldname_with_language
f... | jamesfowkes/golden-futures-site | aloe-test/features/university-features/university_steps.py | university_steps.py | py | 7,482 | python | en | code | 0 | github-code | 1 |
28595875606 |
import board
import busio
import digitalio
import microcontroller
import sys, os
from time import sleep, monotonic_ns
import adafruit_dotstar as dotstar
import feathers2
# +--------------------------+
# | Imports for LCD control |
# +--------------------------+
from sparkfun_serlcd import Sparkfun_SerLCD_I2C
# -----... | PaulskPt/UM_FeatherS2_MSFS2020_GPSout_GPRMC_and_GPGGA | Example/code.py | code.py | py | 40,614 | python | en | code | 0 | github-code | 1 |
40214308408 | import requests
import json
import unicodedata
from bs4 import BeautifulSoup
import os
from dotenv import load_dotenv
import time
def find_env_file(folder):
for filename in os.listdir(folder):
if filename.endswith(".env"):
return os.path.join(folder, filename)
return None
def normalize_t... | kdambrowski/Scraping_quotes_from_page | settings.py | settings.py | py | 2,140 | python | en | code | 0 | github-code | 1 |
19818986748 | import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread("imagens/hospital2.jpg")
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
corners = cv.goodFeaturesToTrack(gray, 10, 0.05, 0.25)
for item in corners:
x, y = item[0]
cv.circle(img, (x, y), 4, (0, 0, 255), -1)
fig = plt.figure... | vitormnoel/opencv | visao-comp/extracao-goodcorners.py | extracao-goodcorners.py | py | 363 | python | en | code | 0 | github-code | 1 |
31327573302 | import os
import tensorflow as tf
import tensorflow_hub as hub
from tfhub_styletransfer_wrapper.imgFnc import load_image, show_images, save_to_gif, save_image
class StyleHub:
def __init__(self, cpu_or_gpu='CPU'):
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
if cpu_or_gpu == 'cpu' or cpu_or_gpu == 'CPU... | alex-parisi/tfhub-styletransfer-wrapper | src/tfhub_styletransfer_wrapper/hubFnc.py | hubFnc.py | py | 2,257 | python | en | code | 0 | github-code | 1 |
26850595638 | import logging
from celery import shared_task
logger = logging.getLogger('error')
@shared_task
def error_logger(err, exc_info=None):
if exc_info:
exc_type, exc_obj, exc_tb = exc_info
logger.error(f'{exc_tb.tb_frame.f_code.co_filename} {exc_tb.tb_lineno} {str(err)}')
else:
logger.error... | praneshsaminathan/Django-Multi-Tenant | multiten/tasks.py | tasks.py | py | 336 | python | en | code | 1 | github-code | 1 |
41206628067 | # Library and Modules used
import os
import cv2
import numpy as np
import customtkinter as ctk
from tkinter import *
from rembg import remove
from pathlib import Path
from threading import Thread
from datetime import datetime
from deepface import DeepFace
from PIL import Image ,ImageTk
from tkinter import ttk, filedia... | Raghvendra5448/Image_Sorter | image_sorter.py | image_sorter.py | py | 37,326 | python | en | code | 1 | github-code | 1 |
32259577603 | import copy
import threading
import socketserver
import json
from typing import List
from mcsu_data import *
_BUFFER_SIZE = 1024
_CLIENTS_MAX = 8
class State:
def __init__(self):
self.userdata = DataGame(0, [])
self.uid_free = []
self.uid = 0
self.lock = threading.Semaphore()
... | JacobLondon/mcsu2 | mcsu_server.py | mcsu_server.py | py | 6,444 | python | en | code | 0 | github-code | 1 |
15576289154 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
result = []
depth =... | quetzaluz/codesnippets | python/leetcode/n-ary-tree-level-order-traversal.py | n-ary-tree-level-order-traversal.py | py | 697 | python | en | code | 0 | github-code | 1 |
69905287713 | """
Entry point for the DB Load dispatcher based on scheduler events.
"""
import json
import queue
import uuid
from concurrent import futures
from typing import Any, Callable, Dict, List
from google.cloud import pubsub_v1
from common import settings as CFG
from common.data_representation.config import ConfigExceptio... | JarosBaumBolles/platform | dispatcher/db_load_meters_data_dispatcher.py | db_load_meters_data_dispatcher.py | py | 20,905 | python | en | code | 0 | github-code | 1 |
6131467896 | def union(x,y):
px = find(x)
py = find(y)
if px != py :
mn = min(cost[px], cost[py])
parent[py] = px
cost[px] = mn
cost[py] = mn
def find(x):
if parent[x] == x:
return x
parent[x] = find(parent[x])
return parent[x]
n,m,k = map(int,input().split())
arr =... | 2020-ASW/kwoneyng-Park | 4월 4주차/친구비.py | 친구비.py | py | 679 | python | en | code | 0 | github-code | 1 |
71720555874 | import pandas as pd
import streamlit as st
from st_aggrid import AgGrid, GridOptionsBuilder
from st_aggrid.shared import GridUpdateMode
STREAMLIT_AGGRID_URL = "https://github.com/PablocFonseca/streamlit-aggrid"
st.set_page_config(
layout="centered", page_icon="🖱️" , page_title="Interactive table app"
)
st.title("... | carywoods/app1 | app1_v3.py | app1_v3.py | py | 1,462 | python | en | code | 0 | github-code | 1 |
18794965698 | import os
import sys
import transaction
import json
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models.meta import Base
from ..models import (
get_engine,
get_session_factory,
get_tm_session,
)
from ..models import S... | alko89/cryptodokladi | cryptodokladi/scripts/initializedb.py | initializedb.py | py | 2,872 | python | en | code | 0 | github-code | 1 |
32275238953 | from tkinter import ttk, constants, Menu
from logic.chain_analytics_service import chain_analytics_service
class NewEventsView:
def __init__(self, root, transactions_handler, filter_handler):
self._root = root
self._transactions_handler = transactions_handler
self._filter_handler = filter_... | tugee/cryptoChainAnalyzer | src/ui/new_transactions_view.py | new_transactions_view.py | py | 4,477 | python | en | code | 2 | github-code | 1 |
30171139606 | from functools import partial, wraps
from usage_model import Redis
def init_redis(func=None, *, redis: Redis = None):
if func is None:
return partial(init_redis, redis=redis)
@wraps(func)
async def wrapper(*args, **kwargs):
if not redis.is_connected:
await redis.connect()
... | ruicore/python | 02-usecase/redis/__init__.py | __init__.py | py | 511 | python | en | code | 10 | github-code | 1 |
43232195290 | #!/usr/bin/env python
#
# License: BSD
# https://raw.github.com/robotics-in-concert/concert_services/license/LICENSE
#
##############################################################################
# About
##############################################################################
# Simple script to pimp out make... | graziegrazie/my_turtlebot | rocon/src/concert_services/concert_service_waypoint_navigation/scripts/waypoint_nav_pimp.py | waypoint_nav_pimp.py | py | 4,883 | python | en | code | 0 | github-code | 1 |
11053554578 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from environments.mc_model.mc_environment import MonteCarloEnv
from collections import defaultdict
import pickle
def heatmap_Q(Q_tab, file_path=None, skip_T=False):
"""
generates a heatmap based on Q_tab
Paramete... | KodAgge/Reinforcement-Learning-for-Market-Making | code/utils/mc_model/plotting.py | plotting.py | py | 8,201 | python | en | code | 85 | github-code | 1 |
8139052478 | # Reference: https://leetcode.com/problems/palindrome-pairs/discuss/535904/Python-3-Clean-Solutions
class Solution:
def palindromePairs(self, words: list) -> list:
def palindrome(word:str) -> bool:
return word == word[::-1]
ans = []
table = {}
for i, wor... | MinecraftDawn/LeetCode | Hard/336. Palindrome Pairs.py | 336. Palindrome Pairs.py | py | 935 | python | en | code | 1 | github-code | 1 |
12335503668 | import subprocess
import os
import csv
import sys
from sys import platform as _platform
import traceback
import argparse
import re
# Platform
os_platform = ""
if _platform == "linux" or _platform == "linux2":
os_platform = "linux"
elif _platform == "darwin":
os_platform = "macos"
elif _platform == "win32":
... | ibrahim0x20/AutoVol3 | autovol3.py | autovol3.py | py | 60,175 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.