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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
34338246402 | # https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
curMaxProfit = 0
minPrice = prices[0]
for price in prices:
curMaxProfit = max(curMaxProfit, price - minPrice)
minP... | 0x0400/LeetCode | p121.py | p121.py | py | 376 | python | en | code | 0 | github-code | 36 |
19199302998 | import argparse
import pandas as pd
import numpy as np
from pathlib import Path
from sklearn.model_selection import train_test_split
from ebm.probability import log_distributions, fit_distributions
from ebm.mcmc import greedy_ascent, mcmc
if __name__=="__main__":
# EXAMPLE
# python run_experiment_mcmc.py --f... | kurmukovai/ebm-progression | scripts/run_experiment_mcmc.py | run_experiment_mcmc.py | py | 3,960 | python | en | code | 0 | github-code | 36 |
485002500 | # My entry number is 2019CS10465.
import time
import sys
from typing import SupportsComplex
from nltk.corpus.reader.chasen import test
import numpy as np
import pandas as pd
from cvxopt import matrix as cvxopt_matrix
from cvxopt import solvers as cvxopt_solvers
def load_data(file, a, b):
a, b = a % 10, b % 10
... | AparAhuja/Machine_Learning | Naive Bayes and SVM/Q2/binary_a.py | binary_a.py | py | 2,670 | python | en | code | 0 | github-code | 36 |
70481931625 | from django.db import models
from .apps import ApiConfig
import sqlite3
# Create your models here.
# ** Make raw SQL queries.
class Weather(object):
__columns__ = ['id', 'city', 'sky', 'temp', 'wind_speed', 'wind_degree', 'clouds', 'time']
__db_name__ = ApiConfig.db_name
def __init__(self):
... | AlexMuliar/WeatherPortal | api/models.py | models.py | py | 3,527 | python | en | code | 0 | github-code | 36 |
9520734015 | '''Code for running a simulation and saving its data.'''
from framework.lattice import Lattice
from simulation.simulator import Simulator
from analysis.visualisation import LatticeVisual
import matplotlib.pyplot as plt
import numpy as np
temp = 5.0
N = 50
#path = r"/net/vdesk/data2/buiten/COP/"
path = "C:\\Users\\vic... | vbuiten/monte-carlo-ising | tests/save_simulation.py | save_simulation.py | py | 970 | python | en | code | 0 | github-code | 36 |
6192905424 | #!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (c) 2013-2018 ProphetStor Data Services, Inc.
# All Rights Reserved.
#
import json
from httplib import UNAUTHORIZED
from flask import request, abort, make_response
from functools import wraps
SERVICE_KEY = "n3oNJ8CE6FIJiMHQuCD... | Colinslik/practice_for_python | api/ifttt/define.py | define.py | py | 1,598 | python | en | code | 0 | github-code | 36 |
39520835273 | from app import create_app
import os
env_name = os.getenv("ENV_NAME", "development")
app = create_app(env_name)
if __name__ == "__main__":
print(app.url_map)
app.run(debug=True, port=5000, host="0.0.0.0")
| RidhimaIyer/CarSalesDealership | wsgi.py | wsgi.py | py | 233 | python | en | code | 0 | github-code | 36 |
7305588960 | # XxxSchema file controls how the data must be organized
# XxxDomain file configures how to access data throught URL API call
from .OperationGrabSchema import *
OperationGrabDomain = {
'schema': OperationGrabSchema,
'item_title': 'Grab action in factory',
'resource_title':'factory/{factoryId}/grab',
# ... | CoRotProject/FOF-API | DatabaseSchema/OperationGrabDomain.py | OperationGrabDomain.py | py | 538 | python | en | code | 0 | github-code | 36 |
36248154374 | #!/usr/bin/env python3
import pickle
import sys
# To ensure we can safely unpickle and repickle, we need to import the relevent
# data type exactly as it is in emat.
from datetime import date as Date
def main(argv):
filename = argv[0] + '.emat'
oldName, newName = argv[1:]
try:
with open(filename... | luther9/emat-py | changetrackname.py | changetrackname.py | py | 739 | python | en | code | 0 | github-code | 36 |
19107589976 | from twitter_crawler import Twitter_crawler
import json
import time
import datetime
#get the keys
with open("keys/keys2.txt","r") as f:
tmplist = f.read().split('\n')
consumer_key = tmplist[0]
consumer_secret = tmplist[1]
access_token = tmplist[2]
access_token_secret = tmplist[3]
#宣告Twitter_crawler物件
tc = Twi... | JJ-Tom-Li/project | twitter_crawler/test.py | test.py | py | 885 | python | en | code | 1 | github-code | 36 |
27792785070 | from analysis_helper import *
from world import *
from linclab_utils import plot_utils
plot_utils.linclab_plt_defaults()
plot_utils.set_font(font='Helvetica')
data = np.load('') # data.npz file
label = 'NoMem TUNL'
stim = data['stim'] # n_episode x 2
delay_resp_hx = data['delay_resp_hx'] # n_episode x len_delay ... | dongyanl1n/sim-tunl | analysis.py | analysis.py | py | 5,622 | python | en | code | 2 | github-code | 36 |
15958493126 | import os
from itertools import product
import re
from numpy import append, array, bincount, diff, ma, sort #cumsum, nditer, roll, setdiff1d, where
from numpy import product as np_prod
seating_re = re.compile('[L\.]')
workPath = os.path.expanduser("~/Documents/Code/Advent_of_code/2020")
os.chdir(workPath)
#with open... | jdmuss/advent_of_code | 2020/day_11.py | day_11.py | py | 1,586 | python | en | code | 0 | github-code | 36 |
74940728105 | import pybullet as p
import numpy as np
import os
class Robot:
def __init__(self,client):
self.client = client
f_name = os.path.join(os.path.dirname(__file__), 'custom_robot.urdf')
self.robot = p.loadURDF(fileName=f_name, basePosition=[0,0,0.205], physicsClientId=client)
self.jointA... | anujkprajapati/Quadruped_env | quadruped/resources/robot.py | robot.py | py | 1,539 | python | en | code | 0 | github-code | 36 |
74869512103 | from apiclient.discovery import build
class BigQueryClient(object):
def __init__(self, httpss):
"""Creates the BigQuery client connection"""
self.service = build('bigquery', 'v2', http=httpss)
def getTableData(self, project, dataset, table):
tablesCollection = self.service.tables()
... | bsyouness/PunORama | FrontEnd/bqclient.py | bqclient.py | py | 1,072 | python | en | code | 1 | github-code | 36 |
25587364266 | import threading, sys
class Main(object):
def __init__(self):
self.closed = False
def run(self):
while not self.closed:
try:
t = threading.Thread(target=self.handle)
t.setDaemon(True)
t.start()
except KeyboardInterrupt:
... | marekjagielski/python-from-java | src/main/resources/python/from/java/Main.py | Main.py | py | 673 | python | en | code | 0 | github-code | 36 |
3886268083 | """
ref :https://leetcode.com/problems/all-paths-from-source-lead-to-destination/
"""
def dfs(memo, visited, node, destination):
# leaf node detected, make sure leaf node is destination
if not memo[node]:
return node == destination
# detect cycles
if visited[node] != 0:
return visited[n... | duochen13/Hikaru-Nara | DFS/PathFromSourceToDest/Solution.py | Solution.py | py | 888 | python | en | code | 0 | github-code | 36 |
34682614662 | import numpy as np
import matplotlib
import scipy
import netCDF4 as nc4
import numpy.ma as ma
import matplotlib.pyplot as plt
from netCDF4 import Dataset
import struct
import glob
import pandas as pd
from numpy import convolve
import datetime
import atmos
import matplotlib.dates as mdates
#"""
#Created on Wed Nov 13... | ClauClouds/PBL_paper_repo | myFunctions.py | myFunctions.py | py | 168,788 | python | en | code | 1 | github-code | 36 |
26476541074 | import pandas as pd
import requests
from lxml import html
tarot_cards = pd.read_csv("tarot.csv")
def fetch_content(url):
print(f"FETCHING {url}")
res = requests.get(url)
tree = html.fromstring(res.content)
xpath = "(//*[not(self::script or self::style)]/text()[string-length() > 50])"
output = "\n... | PrototypesProjects/TAROT | tarot_fetch_text.py | tarot_fetch_text.py | py | 608 | python | en | code | 0 | github-code | 36 |
36045718424 | #Write a program to print all positive numbers in range
list1=[11,-5,67,-32,-21,4,14,-20]
#iterating each number in list
for num in list1:
#checking condition
if num>=0:
print(num, end=" ")
"""
Spyder Editor
This is a temporary script file.
"""
| ArpistaBan/MyCaptain-assignment | positive range.py | positive range.py | py | 278 | python | en | code | 0 | github-code | 36 |
22082345466 | #coding=utf-8
import cv2
import numpy as np
import scipy.signal as sp
from scipy import stats
import math
import os
def nothing(*arg):
pass
def get_video():
#address = "http://admin:admin@10.189.149.245:8081" ; locate_method = 4
address = "pictures/video.mp4" ; locate_method = 1
#addre... | Hao-Wang-Henry/Augmented-Reality-Circuit-Learning | final code with AR.py | final code with AR.py | py | 16,471 | python | en | code | 3 | github-code | 36 |
74260986982 | import numpy as np
import torch
from pcdet.config import cfg, cfg_from_yaml_file
from pcdet.datasets import build_dataloader
from pcdet.utils import common_utils
from pcdet.models.detectors import build_detector
import time
import argparse
def build_test_infra(cfg_file: str, **kwargs):
np.random.seed(666)
cfg... | quan-dao/practical-collab-perception | tools/create_sample_batch_dict.py | create_sample_batch_dict.py | py | 2,968 | python | en | code | 5 | github-code | 36 |
20049471962 | import numpy as np
from keras.applications.vgg16 import preprocess_input
def predict(img_dir):
img = load_img(img_dir)
img = np.resize(img, (224,224,3))
img = preprocess_input(img_to_array(img))
img = (img/255.0)
img = np.expand_dims(img, axis=0)
prediction = model.predict(img)
idx = np.arg... | ocinemod87/Advanced_Topics_Image_Analysis | Assignment_3/custom_metric.py | custom_metric.py | py | 1,949 | python | en | code | 0 | github-code | 36 |
33741125422 | # Design guessing game using While loop
import random
print("Please Enter a highest Number")
highest = int(input())
answer = random.randint(1,highest)
print(highest)
print(answer)
print("please enter a number between 1 and {}".format(highest))
guess = 0
while answer != guess:
guess = int(input())
i... | SatyaSaiKrishnaAdabala/Python | Guess Game using Loop.py | Guess Game using Loop.py | py | 542 | python | en | code | 0 | github-code | 36 |
37412475145 | import pytest
import numpy as np
from ...dust import IsotropicDust
from ...util.functions import B_nu
from .. import Model
from .test_helpers import random_id, get_test_dust
def test_point_source_outside_grid(tmpdir):
dust = get_test_dust()
m = Model()
m.set_cartesian_grid([-1., 1.], [-1., 1.], [-1.,... | hyperion-rt/hyperion | hyperion/model/tests/test_fortran.py | test_fortran.py | py | 2,753 | python | en | code | 51 | github-code | 36 |
27610932999 | n, m = map(int, input().split())
a = list(map(int,input().split()))
def binary(array, start, end, target):
if start > end :
return end
mid = (start+end)//2
result =0
for i in array:
if (i - mid) > 0 :
result += i - mid
if result == target:
return mid
elif ... | Youngminah/thisiscodingtest | 2장.주요알고리즘이론/07.이진탐색/7-8.py | 7-8.py | py | 479 | python | en | code | 2 | github-code | 36 |
11154422217 | """
Wimbledon - Prac 5
The champions and how many times they have won.
The countries of the champions in alphabetical order
Estimate: 40 mins
Actual: 46 mins
"""
FILENAME = "wimbeldon.txt"
def main():
data = get_data_from_file()
champions = extract_values_from_data(data, 2)
countries = set(extract_values... | CobeySmith/Practicals | prac_05/wimbledon.py | wimbledon.py | py | 1,647 | python | en | code | 0 | github-code | 36 |
40272165655 | import abc
import threading
import time
from datetime import datetime
from .AbstractProcess import AbstractProcess
from .SaveStopProcess import SaveStopProcess
from utils.threads import set_thread_name
class SaveStartProcess(AbstractProcess):
@staticmethod
def __parse_buffer(buffer):
try:
... | donghyyun/PF_OfflinePhaseServer | handle_processes/SaveStartProcess.py | SaveStartProcess.py | py | 1,933 | python | en | code | 0 | github-code | 36 |
34932792727 | somaidade = 0
m = 0
maioridadehomem = 0
nomevelho = ''
totmulher20 = 0
for c in range(1, 5):
print('-'*10, c, 'ª', '-'*10)
nome = str(input('Digite o nome: ')).strip()
idade = int(input('Digite a idade: '))
sexo = str(input('Digite o sexo [M/F]: ')).strip()
m = m + idade
if c == 1 and sexo in 'M... | lucasaguiar-dev/Questoes-Python | Projeto donwload/PythonExercicios/ex056.py | ex056.py | py | 734 | python | pt | code | 0 | github-code | 36 |
69906138984 | from flask_app import DATABASE
from flask_app.config.mysqlconnection import connectToMySQL
class Ninja:
def __init__( self, data ):
self.id = data[ 'id' ]
self.first_name = data[ 'first_name' ]
self.last_name = data[ 'last_name' ]
self.age = data[ 'age' ]
self.created_at = ... | xmparnold/dojos_and_ninjas | flask_app/models/ninja_model.py | ninja_model.py | py | 1,732 | python | en | code | 0 | github-code | 36 |
36939059453 | import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
def create_number_tweets_graphic(
data: pd.DataFrame, colors: list[str], time_stamps: list[tuple[int, int]]
) -> go.Figure:
"""Returns a picture with a histogram per newspaper
Args:
data (pd.DataFrame): Data frame w... | drearondov/nlp-newspapersDashboard | nlp_newspapersDashboard/api/number_tweets.py | number_tweets.py | py | 1,038 | python | en | code | 0 | github-code | 36 |
43302009564 | import math
from rpython.rtyper.tool import rffi_platform
from rpython.translator.tool.cbuild import ExternalCompilationInfo
class CConfig:
_compilation_info_ = ExternalCompilationInfo(includes=['float.h'])
DBL_MAX = rffi_platform.DefinedConstantDouble('DBL_MAX')
DBL_MIN = rffi_platform.DefinedConstantDo... | mozillazg/pypy | rpython/rlib/constant.py | constant.py | py | 1,561 | python | en | code | 430 | github-code | 36 |
5991316924 | import requests
import re
import sys
inject = sys.argv[1]
url = f"http://10.10.33.143/admin?user={inject}"
token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIsInVzZXJuYW1lIjoibWljaGFlbCIsImFkbWluIjp0cnVlLCJpYXQiOjE2ODE0MDYxNjZ9.7S5bGRpPZetpWvlwYOa3U2D24wYQGDcm7R_CaLONA5E"
headers = {
"Cookie": f"token... | singha-brother/ctf_challenges | TryHackMe/marketplace/sql_exploit.py | sql_exploit.py | py | 461 | python | en | code | 1 | github-code | 36 |
15287830329 | ##encoding=UTF8
"""
author: Sanhe Hu
compatibility: python3 ONLY
prerequisites: angora.SQLITE
import:
from angora.PandasSQL.sqlite3blackhole import CSVFile, Sqlite3BlackHole
"""
from __future__ import print_function
from angora.SQLITE.core import MetaData, Sqlite3Engine, Table, Column, DataType
from angora.DAT... | MacHu-GWU/Angora | angora/PandasSQL/sqlite3blackhole.py | sqlite3blackhole.py | py | 10,015 | python | en | code | 0 | github-code | 36 |
75321076905 | from modules.amazon_parser import *
from collections import defaultdict
from cosine_sim import cosine_sim
reviews = parserJSON('./library/amazon-review-data.json',)
"""
keys of reviews
`Rate`
`reviewText`
`video`
`verifiedPurchase`
`Date`
`productId`
`reviewId`
`memberId`
`reviewTitle`
"""
#rating for product p give... | josiahcoad/Faker | individual_kevin.py | individual_kevin.py | py | 3,188 | python | en | code | 1 | github-code | 36 |
18876976348 | # coding=utf-8
import copy
import logging
import traceback
import time
import socket
from collections import namedtuple
from functools import partial
from logging.handlers import SysLogHandler, WatchedFileHandler
import tornado.options
from tornado.options import options
from tornado.escape import to_unicode
try:
... | nekanek/frontik-without-testing | frontik/frontik_logging.py | frontik_logging.py | py | 7,857 | python | en | code | 1 | github-code | 36 |
74611360425 | #--------Contact Us Module-----------
import os
from tkinter import *
def back1():
root.destroy()
os.system("homescreen.py")
root = Tk()
root.title("Contact Us")
root.geometry("500x250+0+0")
root.minsize(500,250)
root.maxsize(500,250)
f1 = Frame(root)
Label(f1,text="ABC University",font="times_roman 20 bold",f... | jobanjit-singh/University-Management-System | contactus.py | contactus.py | py | 1,488 | python | en | code | 1 | github-code | 36 |
2849684748 | from django.urls import path
from .views import blog_post,\
blogview,\
search_blog, \
all_blog, \
post_detail,\
createpost, \
updatepost
urlpatterns = [
path('', blogview, name='blogview'),
path('create-post', createpost, name='create-post'),
path('all-blog', all_blog, name = ... | myfrank4everreal/baronshoes_v_2.0 | blog/urls.py | urls.py | py | 585 | python | en | code | 0 | github-code | 36 |
70596977383 | #Create a dataset of normalised spectrograms from files
import os
import numpy as np
import librosa
import audiofile as af
import configparser
from utils.audioTools import getSpectro
debugFlag = False
def main():
config = configparser.ConfigParser()
if debugFlag == True:
config.read(r'configTest.c... | epsln/chiner | utils/makeDS.py | makeDS.py | py | 1,952 | python | en | code | 1 | github-code | 36 |
38293625086 | """
Base implementation of SNGAN with default variables.
"""
from torch_mimicry.nets.gan import gan
class SNGANBaseGenerator(gan.BaseGenerator):
r"""
ResNet backbone generator for SNGAN.
Attributes:
nz (int): Noise dimension for upsampling.
ngf (int): Variable controlling generator featur... | kwotsin/mimicry | torch_mimicry/nets/sngan/sngan_base.py | sngan_base.py | py | 1,093 | python | en | code | 593 | github-code | 36 |
73112493223 | #!/usr/bin/env python
"""
Created by howie.hu at 2018/9/21.
"""
import numpy as np
class Perceptron:
"""
李航老师统计学习方法第二章感知机例2.2对偶形式代码实现
"""
def __init__(self, alpha_length=3):
self.alpha = np.zeros(alpha_length)
# 权重
self.w = np.zeros(2)
# 偏置项
self.b = 0.0
... | howie6879/pylab | src/books/statistical_learning_method/chapter02_02.py | chapter02_02.py | py | 1,996 | python | en | code | 49 | github-code | 36 |
11425267400 | from django.shortcuts import render, redirect
from .models import Product, SliderImage, Guest, CartItem
from django.http import HttpResponse
from django.db.models import Q
def home(request):
products = Product.objects.all()
slides = SliderImage.objects.all()
category = request.GET.get('category')
brand... | MairaAllen/django--------3 | top/store/views.py | views.py | py | 1,860 | python | en | code | 0 | github-code | 36 |
23640743170 | from pymongo import MongoClient
from config import DB_USER, DB_PASSWORD, DB_IP_ADDR, DB_AUTH_SOURCE
from console import console, Progress
from time import sleep
def connect_to_db():
console.print("Підключення до бази даних...", end="")
try:
client = MongoClient(DB_IP_ADDR, username=DB_USER, password=D... | WebUraXalys/vstupBot | parser/db.py | db.py | py | 2,401 | python | uk | code | 0 | github-code | 36 |
9587688117 | # -*- coding: utf-8 -*-
import Jarvis
import colorama
import sys
def check_python_version():
return sys.version_info[0] == 3
def main():
# enable color on windows
colorama.init()
# start Jarvis
jarvis = Jarvis.Jarvis()
command = " ".join(sys.argv[1:]).strip()
jarvis.executor(command)
i... | sukeesh/Jarvis | jarviscli/__main__.py | __main__.py | py | 451 | python | en | code | 2,765 | github-code | 36 |
3050296786 | # coding=utf-8
"""Csv download model definition.
"""
from datetime import datetime
from django.db import models
from django.conf import settings
from django.core.exceptions import ValidationError
from bims.api_views.csv_download import (
send_csv_via_email,
send_rejection_csv,
send_new_csv_notification
)
... | anhtudotinfo/django-bims | bims/models/download_request.py | download_request.py | py | 3,152 | python | en | code | null | github-code | 36 |
11232703752 | from django.shortcuts import render, get_object_or_404
from .models import Post, Group
def index(request):
"""YaTube - main."""
TEMPLATE = 'posts/index.html'
posts = Post.objects.order_by('-pub_date')[:10]
context = {
'posts': posts
}
return render(request, TEMPLATE, context)
def gro... | semenov-max/yatube_project | yatube/posts/views.py | views.py | py | 620 | python | en | code | 0 | github-code | 36 |
25250856119 | import argparse
import imgkit
import sched
from datetime import datetime, timedelta
from pytz import timezone
from random import randint
from time import sleep, time
from availability_checker import AvailabilityChecker
from config.configuration import SLEEP_TIME, REPORT_HOUR
TIMEZONE = timezone('EST')
def when_to_g... | colecanning/hockey_availability_trigger | run_checks.py | run_checks.py | py | 2,061 | python | en | code | 1 | github-code | 36 |
15655252113 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 13 17:04:34 2018
@author: ecupl
"""
import numpy as np
import pandas as pd
import os,copy
import matplotlib.pyplot as plt
#######################
# #
# HMM最优路径 #
# #
#######################
os.chdir(r"D:\mywork\test")
'''... | shoucangjia1qu/Machine-Learnning1 | Machine Learning 0217 charpter11.py | Machine Learning 0217 charpter11.py | py | 2,970 | python | en | code | 6 | github-code | 36 |
34053641545 | from datetime import datetime, date
import pickle as pickle
def stringfy(value:any, dbtype)->str:
if type(value) == str:
if dbtype == 'mysql':
symbols = ['\\', "'", '"', "(", ")", "%", '&', '@', '*', '[', ']', '{', '}', '^', '!', '/', '-', '+', '?', ';', '~', '|']
for symbol in symb... | ajcltm/Isql_v2 | Isql_v2/sql.py | sql.py | py | 2,592 | python | en | code | 0 | github-code | 36 |
21372604951 | import os
import uuid
class BaseStorage(object):
def get(self, size, address):
raise NotImplementedError()
def set(self, data, address):
raise NotImplementedError()
class FileStorage(BaseStorage):
path = None
mode = None
handler = None
def __init__(self, path, read_only=F... | sergio-bershadsky/indexer | src/indexer/base/storage.py | storage.py | py | 2,472 | python | en | code | 0 | github-code | 36 |
35251627738 | #prob.7
# searching the whole number is not efficient! -> use the prime numbers previously searched
# repetitive calling of the isprime improves the performance
primenumbers :list[int] = [2] #prime number cache
#find the number is prime
def isPrime (num :int) ->bool:
"""Check the number is prime
Args:
... | lila-lalab/SDDataExpertProgram2021 | 이재호/day3/test_7_cache.py | test_7_cache.py | py | 1,040 | python | en | code | 0 | github-code | 36 |
7666619166 | from PyQt5 import QtWidgets, QtCore, QtGui
from UI import Ui_MainWindow
import sys
import images
import core
from database import SessionLocal, engine
from models import APP, Group, Function
# 创建数据库表
APP.metadata.create_all(bind=engine)
Group.metadata.create_all(bind=engine)
Function.metadata.create_all(bind=engine)
... | mrknow001/API-Explorer | main.py | main.py | py | 2,246 | python | en | code | 29 | github-code | 36 |
2186193561 | import os
PROJECT_PATH: str = os.getenv("n2t_hardware_tester_project_path") # type: ignore
N2T_WORK_AREA_PATH: str = os.getenv("n2t_work_area_path") # type: ignore
TEST_SUCCESS = "End of script - Comparison ended successfully"
TIMESTAMP_NOT_FOUND_VALUE_LATE_DAYS = 99999
GOOGLE_API_CREDENTIALS: str = os.getenv("n2t_g... | kpaik18/N2THardwareTester | n2tconfig.py | n2tconfig.py | py | 1,483 | python | en | code | 0 | github-code | 36 |
14085187886 | from tkinter import *
from tkinter.messagebox import *
from tkinter import messagebox
#Клас, що представляє меню програми
#Атрибути:
# Відсутні
# Методи
# ------
# ********************************************************
# ********************************************************
# def __init__(self, ca... | Vladosichek/KPI_1course | OP2_Kursach/Kursova_Robota/Kursova_Robota/MENU.py | MENU.py | py | 3,922 | python | uk | code | 0 | github-code | 36 |
43296470854 | import pytest
from pypy.interpreter.pyparser import pytokenizer
from pypy.interpreter.pyparser.parser import Token
from pypy.interpreter.pyparser.pygram import tokens
from pypy.interpreter.pyparser.error import TokenError
def tokenize(s):
return pytokenizer.generate_tokens(s.splitlines(True) + ["\n"], 0)
def chec... | mozillazg/pypy | pypy/interpreter/pyparser/test/test_pytokenizer.py | test_pytokenizer.py | py | 2,472 | python | en | code | 430 | github-code | 36 |
28065082848 | from argparse import ArgumentParser
from collections import namedtuple, deque
from functools import partial
from random import sample
from time import time
import numpy as np
import torch
from gym import make
from numpy.random import random
from torch import tensor, save, no_grad
from torch.nn import MSELoss
from torc... | Daggerfall-is-the-best-TES-game/reinforcement-learning | Chapter6/02_dqn_pong.py | 02_dqn_pong.py | py | 5,814 | python | en | code | 1 | github-code | 36 |
20111358095 | def enhance(image, x, y):
return iea[int(image[y-1][x-1:x+2]+image[y][x-1:x+2]+image[y+1][x-1:x+2], 2)]
with open('input.txt') as f:
iea = f.readline().strip().replace('.', '0').replace('#', '1')
image = f.read().strip().replace('.', '0').replace('#', '1').split('\n')
for i in range(50):
p = str(i % ... | heinosoo/aoc_2021 | day_20/part_12.py | part_12.py | py | 731 | python | en | code | 0 | github-code | 36 |
26360074769 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 12:59:23 2020
@author: juliaschopp
"""
# Simulate test comp with 4 athletes
import pandas as pd
from itertools import permutations
from combined import *
# --- Competitor and results variables ---
competitors = ['Mori', 'Condie', 'Rakovec', '... | JuliaSchoepp/charly_o_mat | combined_s_test.py | combined_s_test.py | py | 1,517 | python | en | code | 0 | github-code | 36 |
13990217528 | class Node:
def __init__(self, key):
self.key = key
self.next = None
self.prev = None
class List:
def __init__(self):
self.first = None
self.last = None
self.size = 0
def append(self, node):
if self.size == 0:
self.first = self.last = no... | dariomx/topcoder-srm | leetcode/zero-pass/google/lru-cache/Solution3.py | Solution3.py | py | 2,501 | python | en | code | 0 | github-code | 36 |
12445078745 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
# Defining the seed for some random operations:
random_seed = 42
# Setting some variables to format the logs:
log_begin_red, log_begin_blue, log_begin_green = '\033[91m', '\033[94m', '\033[92m'
log_begin_bold, log_begin_underline = '... | happiness6533/AI-study-project | supervised_learning/neural_network/regularizers.py | regularizers.py | py | 13,898 | python | en | code | 0 | github-code | 36 |
30589096561 | """mse_home.log module."""
import logging
LOGGER = logging.getLogger("mse")
def setup_logging(debug: bool = False):
"""Configure basic logging."""
logging.basicConfig(format="%(message)s")
LOGGER.setLevel(logging.DEBUG if debug else logging.INFO)
| Cosmian/mse-home-cli | mse_home/log.py | log.py | py | 263 | python | en | code | 1 | github-code | 36 |
13102044092 | import time
import json
import requests
from tqdm import tqdm
from datetime import datetime, timezone
from . import logger
from pleroma_bot.i18n import _
# from pleroma_bot._utils import spinner
def twitter_api_request(self, method, url,
params=None, data=None, headers=None, cookies=None,
... | robertoszek/pleroma-bot | pleroma_bot/_twitter.py | _twitter.py | py | 32,092 | python | en | code | 98 | github-code | 36 |
22557090121 | import torch
import numpy as np
import matplotlib.pyplot as plt
import torch.optim as optim
from tqdm import tqdm
from cvaegan.conditional_architecture import *
from cvaegan.utils import *
import porespy as ps
DATASET = torch.from_numpy(np.load('./data/bentheimer1000.npy')).reshape(1000,1,128,128,128)
POROSI... | pch-upc/reconstruction-cvaegan | train.py | train.py | py | 6,241 | python | en | code | 0 | github-code | 36 |
6733216231 | import seaborn as sbn
import numpy as np
import matplotlib.pylab as plt
import scipy as sci
from scipy.io import wavfile
sr, aud_array = wavfile.read(r'C:\Users\jackk\OneDrive - South East Technological University (Waterford Campus)\college backup\semester 7\Digital Signal Processing\mini project\python files\... | jackkelly247/DSP | first steps parsing wav file.py | first steps parsing wav file.py | py | 1,539 | python | en | code | 0 | github-code | 36 |
16249965323 | from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import plot_confusion_matrix
import pandas as pd
import pickle
import json
import os
def dynamic_data_extract(path):
dataline = pd.DataFrame()
with open(path) as f:
data = json.... | sbalan7/HCL-Hack-IITK-2020 | Challenge-Round-1/Dynamic-Analysis/dynamic_model_building.py | dynamic_model_building.py | py | 2,930 | python | en | code | 0 | github-code | 36 |
74542668264 | import time
import numpy as np
import tensorflow as tf
import os.path as osp
from baselines import logger
from collections import deque
from baselines.common import explained_variance, set_global_seeds
from baselines.common.models import get_network_builder
import random
try:
from mpi4py import MPI
except ImportErr... | asaiacai/cs285-final-project | baselines/baselines/ppo2/ppo2.py | ppo2.py | py | 12,780 | python | en | code | 0 | github-code | 36 |
4254816914 | """
Problem Statement
Given a staircase with ‘n’ steps and an array of 'n' numbers representing the fee that you have to pay if you take the step. Implement a method to calculate the minimum fee required to reach the top of the staircase (beyond the top-most step). At every step, you have an option to take either 1 ste... | blhwong/algos_py | grokking_dp/fibonacci_numbers/minimum_jumps_with_fee/main.py | main.py | py | 1,467 | python | en | code | 0 | github-code | 36 |
32682301069 | ######################################
#
# Deborah Pinna, August 2015
#
######################################
from utils import *
#samples.append("SingleMuon_Run2016G-PromptReco-v1")
#samples.append("SingleMuon_Run2016F-PromptReco-v1")
#samples.append("SingleMuon_Run2016E-PromptReco-v2")
#samples.append("SingleMuon... | oiorio/NAAnaFW | python/MakePlot/samples/Data.py | Data.py | py | 5,441 | python | en | code | 0 | github-code | 36 |
31061791335 |
from ..utils import Object
class RemoveAllFilesFromDownloads(Object):
"""
Removes all files from the file download list
Attributes:
ID (:obj:`str`): ``RemoveAllFilesFromDownloads``
Args:
only_active (:obj:`bool`):
Pass true to remove only active downloads, including pau... | iTeam-co/pytglib | pytglib/api/functions/remove_all_files_from_downloads.py | remove_all_files_from_downloads.py | py | 1,245 | python | en | code | 20 | github-code | 36 |
40194408515 | from products.models import get_product_model
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from django.core.files.uploadedfile import SimpleUploadedFile
import requests
# Create your tests here.
# Images app test
class ImageManagerTest(TestCase):
... | Trojnar/django-store | images/tests.py | tests.py | py | 6,945 | python | en | code | 0 | github-code | 36 |
22636872735 | import os
os.system('sudo pigpiod')
import time
from random import randint
from random import shuffle
import pigpio
import RPi.GPIO as GPIO
from datetime import datetime
import numpy as np
import pandas as pd
import pygame
###variables for filenames and save locations###
partnum = '001'
device = 'Amp'
filename = 'Sh... | APPLabUofA/Pi_Experiments | Shutter_Grid/Task/shutter_grid.py | shutter_grid.py | py | 6,498 | python | en | code | 4 | github-code | 36 |
41519542938 | #!/bin/python3
import sys
def getRecord(s):
# Complete this function
max=0
min=0
start=s[0]
for i in range(n):
if s[i] > s[0]:
max+=1
s[0]=s[i]
s[0]=start
for i in range(n):
if s[i]<s[0]:
min+=1
s[0]=s[i]
return max,min
... | AarthiAnanth/SampleProject | BreakingtheRecords.py | BreakingtheRecords.py | py | 467 | python | en | code | 0 | github-code | 36 |
31433336762 | from flask import Flask, request
import json
import uuid
from models.poker import Poker
from models.state import State
app = Flask(__name__)
poker = Poker()
@app.route("/state", methods=["GET"])
def state():
return json.dumps(State.to_dict(poker.state))
@app.route("/add-player", methods=["POST... | akbae/poker | server/server.py | server.py | py | 1,971 | python | en | code | 0 | github-code | 36 |
3113291140 | """common logging for easy integration with application insights"""
import logging
import sys
from typing import Any, Dict, Optional
from opencensus.ext.azure.log_exporter import AzureLogHandler
class FunctionName:
ED = "event_driven"
PACKAGES = {
FunctionName.ED: "event_driven",
}
class OptionalCustom... | dgonzo27/event-driven-architecture | functions/utils/logging.py | logging.py | py | 2,446 | python | en | code | 0 | github-code | 36 |
1307004621 | import turtle as tt
import time
t = tt.Turtle()
t.color("blue")
screen = tt.Screen()
screen.tracer(0)
t.hideturtle()
#Define draw function
def draw_rectangle(pen, x, y, width, height):
pen.penup()
pen.goto(x, y)
pen.down()
for i in range(2):
pen.forward(width)
pen.right(90)
pen... | tholuongduc/mypython3 | Thuat_toan_va_cham/Rectangle_Collision.py | Rectangle_Collision.py | py | 1,710 | python | en | code | 0 | github-code | 36 |
3539505659 | import os
from pathlib import Path
from split_settings.tools import include
from dotenv import dotenv_values
BASE_DIR = Path(__file__).resolve().parent.parent
config = dotenv_values(".env")
DEBUG = config.get('DEBUG', False) == 'True'
include(
'components/database.py',
'components/middleware.py',
'compone... | bogatovad/new_admin_panel_sprint_2 | docker_compose/simple_project/app/example/settings.py | settings.py | py | 932 | python | en | code | 0 | github-code | 36 |
36955027199 | import threading, time
import wttest
import wiredtiger
from wtdataset import SimpleDataSet
from wtscenario import make_scenarios
# test_checkpoint16.py
#
# Make sure a table that's clean when a checkpointed can still be read in
# that checkpoint.
@wttest.skip_for_hook("tiered", "FIXME-WT-9809 - Fails for tiered")
cla... | mongodb/mongo | src/third_party/wiredtiger/test/suite/test_checkpoint16.py | test_checkpoint16.py | py | 3,374 | python | en | code | 24,670 | github-code | 36 |
71390250985 | #!/usr/bin/env python
import sys,os,glob, inspect
#,re,numpy,math,pyfits,glob,shutil,glob
import optparse
import scipy as sp
import numpy as np
import pylab as pl
from scipy.interpolate import interp1d
from scipy import optimize
#from mpmath import polyroots
import time
import pprint, pickle
#from snclasses import my... | fedhere/SESNCfAlib | templates/templutils.py | templutils.py | py | 21,005 | python | en | code | 0 | github-code | 36 |
73609243625 | import imp, ast, sys, inspect
def on_error_resume_next(path):
file_ = open(path)
tree = ast.parse(file_.read(), path)
OnErrorResumeNextVisitor().visit(tree)
ast.fix_missing_locations(tree)
return compile(tree, path, 'exec')
class OnErrorResumeNextFinder(object):
def _find_module(self, name, p... | armooo/on_error_resume_next | on_error_resume_next.py | on_error_resume_next.py | py | 3,419 | python | en | code | 2 | github-code | 36 |
28042659077 | import requests
from contextlib import closing
import csv
import codecs
import matplotlib.pyplot as plt
url = 'http://www.mambiente.munimadrid.es/opendata/horario.txt'
with closing(requests.get(url, stream='true')) as r:
reader = csv.reader(codecs.iterdecode(r.iter_lines(), 'utf-8'), delimiter=',')
for row in... | Berckbel/bigDataPython | Ficheros/fIcherosEnWEB1.py | fIcherosEnWEB1.py | py | 835 | python | en | code | 0 | github-code | 36 |
7135785492 | # -*- coding: utf-8 -*-
# ***************************************************
# * File : LSTM_CNN.py
# * Author : Zhefeng Wang
# * Email : wangzhefengr@163.com
# * Date : 2023-05-28
# * Version : 0.1.052816
# * Description : description
# * Link : link
# * Requirement : 相关模块版本需求(例如:... | wangzhefeng/tsproj | models/csdn/LSTM_CNN.py | LSTM_CNN.py | py | 2,422 | python | en | code | 0 | github-code | 36 |
7373341985 | import cv2
import numpy as np
from tkinter import *
import tkinter.font
from tkinter import messagebox
from tkinter import filedialog
from pytube import YouTube
from PIL import ImageTk,Image
from bs4 import BeautifulSoup
from datetime import date
from googlesearch import search
import csv
import time, vlc
import pandas... | 07akshay/YouLoader | __init__.py | __init__.py | py | 5,073 | python | en | code | 1 | github-code | 36 |
24623749772 | from utils.dataloader import make_datapath_list, VOCDataset, DataTransform
from torch.utils import data
from utils.pspnet import *
from torch import optim
import math
from utils import train
rootpath = "./data/VOCdevkit/VOC2012/"
train_img_list, train_anno_list, val_img_list, val_anno_list = make_datapath_list(rootpat... | TOnodera/pytorch-advanced | ch03/main.py | main.py | py | 2,748 | python | en | code | 0 | github-code | 36 |
495598497 | # pylint: disable=no-value-for-parameter
from dagster import Output, OutputDefinition, RunConfig, execute_pipeline, pipeline, solid
from dagster.core.instance import DagsterInstance
def test_retries():
fail = {'count': 0}
@solid
def fail_first_times(_, _start_fail):
if fail['count'] < 1:
... | helloworld/continuous-dagster | deploy/dagster_modules/dagster/dagster_tests/core_tests/execution_tests/test_retries.py | test_retries.py | py | 1,768 | python | en | code | 2 | github-code | 36 |
71266832745 | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn.model_selection as ms
import sklearn.preprocessing as pp
import sklearn.linear_model as lm
import sklearn.ensemble as en
import sklearn.metrics as met
import joblib as jb
df = pd.read_csv('churnprediction_ch9.csv', sep=',', index_... | arfian-rp/machine-learning-python | Churn Prediction/main.py | main.py | py | 2,414 | python | en | code | 1 | github-code | 36 |
74532513383 | import time
import pandas as pd
import numpy as np
from os.path import dirname
from . import converters;
from sklearn.datasets.base import Bunch
#Load dataframe
def load_df_dogs_2016(NApolicy = 'none', dropColumns = [], fixErrors = True, fixAge=True, censoringPolicy = 'none', newFeats = True):
module_path = dirna... | elvisnava/svm-thesis | experiments/datasets/dogs_2006_2016.py | dogs_2006_2016.py | py | 6,959 | python | en | code | 0 | github-code | 36 |
12143911661 | import pygame
import Classes_objects
import Developer_help
import Load_image
import Sound_effects
import Check_reasults
import Deck_module
import Speical_moves
#-------------------------------------------------------- load data -----------------------------
#----------------------------------------------------player... | DvirS123/Black_Jack_Game | Player_phases.py | Player_phases.py | py | 14,772 | python | en | code | 0 | github-code | 36 |
16156353318 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('researcher_UI', '0019_auto_20170505_0444'),
]
operations = [
migrations.AddField(
... | langcog/web-cdi | webcdi/researcher_UI/migrations/0020_study_test_period.py | 0020_study_test_period.py | py | 544 | python | en | code | 7 | github-code | 36 |
1435191130 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import shutil
import azure
from azure.storage import BlobService
import azure.http
import os.path
import sys
import os
import pdb
storage_name = ""
storage_key = ""
def list_files_from_path(container, path):
blob_service = BlobService(account_name=storage_name, accoun... | UnluckyNinja/hwindCode | python/scripts/download_files_from_azure.py | download_files_from_azure.py | py | 1,763 | python | en | code | 0 | github-code | 36 |
26490671738 | from .authorities_sync.unesco import UnescoScraper
from .authorities_sync.eric import EricScraper
from .authorities_sync.oecd import OecdScraper
from .models import Authorities
def scrap_unesco():
"""
Starts the scraping process
"""
scraper = UnescoScraper()
scraper.scrape()
def scrap_eric():
... | JU4NP1X/teg-backend | categories/sync.py | sync.py | py | 839 | python | en | code | 1 | github-code | 36 |
886557630 |
class fileInput():
def getStates(self):
statesList = list()
fo = open("states.csv", "r")
while(1):
line = fo.readline(2)
if len(line) == 0:
break
if len(line) > 1:
spot = len(line)
x = ""
x... | tichen47/Travel-Planner | Entity/fileInput.py | fileInput.py | py | 424 | python | en | code | 0 | github-code | 36 |
7409463239 | from django.http import Http404
from django.shortcuts import render, redirect
from django.db import IntegrityError
from contact_manager.models import Contact, Country
from contact_manager.forms import CountryModelForm
def c_form(request):
if request.method == 'GET':
template = 'contact.html'
... | SRI-VISHVA/Django_Basic | django1/contact_manager/views.py | views.py | py | 2,829 | python | en | code | 0 | github-code | 36 |
29687155696 | # Databricks notebook source
import pandas as pd
import numpy as np
# COMMAND ----------
x1=np.arange(10)
y1=np.random.random(10)
x2=np.arange(4,12)
y2=np.random.random(8)
df1 = pd.DataFrame({'x':x1,'y1':y1})
df2 = pd.DataFrame({'x':x2,'y2':y2})
df1.head(3)
# COMMAND ----------
df1.to_csv('df1.csv')
# COMMAND ----... | donagiro/titania | titanie_nl.py | titanie_nl.py | py | 408 | python | en | code | 0 | github-code | 36 |
36956641199 | import os, sys, getopt
def usage():
print('Usage:\n\
$ python .../tools/wt_ckpt_decode.py [ -a allocsize ] addr...\n\
\n\
addr is a hex string\n\
')
def err_usage(msg):
print('wt_ckpt_decode.py: ERROR: ' + msg)
usage()
sys.exit(False)
# Set paths
wt_disttop = sys.path[0]
env_builddir = ... | mongodb/mongo | src/third_party/wiredtiger/tools/wt_ckpt_decode.py | wt_ckpt_decode.py | py | 3,634 | python | en | code | 24,670 | github-code | 36 |
74027914343 | import os
import re
def get_ch_en(str1):
name_china = re.sub("(.*)", "", str1)
name_english = re.sub(name_china, "", str1)
return (name_china, name_english[1:-1])
def main():
all_brands = open("all_brands.csv","r",encoding="utf-8")
for item in all_brands.readlines():
brands_list = item.st... | jercheng/js_video_scrapy | crawl/list_jd_com/sorted_brands.py | sorted_brands.py | py | 1,029 | python | en | code | 0 | github-code | 36 |
86452313478 | import algorithm
import pandas as pd
from pymongo import MongoClient
import pymongo
client = MongoClient('localhost', 27017)
db = client['tushare']
data = db.history_data.find({'code':'600446'}).sort([("date", pymongo.ASCENDING)])
df = pd.DataFrame(list(data))
prices = df['close'].values
print(prices... | justquant/dataimport | test.py | test.py | py | 463 | python | en | code | 1 | github-code | 36 |
14065733809 | from itertools import combinations
from collections import deque
N, M = map(int, input().split())
room = []
vir_l = []
for n in range(N):
room.append(list(map(int, input().split())))
for m in range(N):
if room[n][m] == 2:
vir_l.append((n,m))
d_v = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (... | yeon-june/BaekJoon | 17142_plus.py | 17142_plus.py | py | 1,863 | python | en | code | 0 | github-code | 36 |
37634946150 | # You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ing... | sunnyyeti/Leetcode-solutions | 2115 Fina All Possible Recipes from Given Supplies.py | 2115 Fina All Possible Recipes from Given Supplies.py | py | 3,074 | python | en | code | 0 | github-code | 36 |
10650192389 | from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class TestingReport(Document):
def validate(self):
for report in self.reports:
doc = frappe.get_doc("Report",report.report)
frappe.db.sql("delete from `tabHas Role` where parent = %s ",doc.name)
doc.append("r... | venku31/ceramic | ceramic/ceramic/doctype/testing_report/testing_report.py | testing_report.py | py | 399 | python | en | code | null | github-code | 36 |
41472346976 | # User Input
a=input("Enter Your Name : ")
print("** Good Afternoon " + a + " :) **")
# Letter Template
name=input("Enter Your Name : ")
date=input("Enter Date : ")
letter='''\nDear <|NAME|> ,
You are Selected !
\tDate: <|DATE|>'''
letter=letter.replace("<|NAME|>",name)
letter=letter.replace("<|DATE|>",date)
... | Shilajit2002/Python | Tutorial/String & Escape Sequences/Practice.py | Practice.py | py | 717 | python | en | code | 0 | github-code | 36 |
36281488792 | #!/usr/bin/env python
from qt_gui.plugin import Plugin
from .plugin_widget import ScienceWidget
class SciencePlugin(Plugin):
def __init__(self, context):
super(SciencePlugin, self).__init__(context)
self.setObjectName('SciencePlugin')
self._widget = ScienceWidget(context)
self._wi... | sandy1618/URC | rosws/src/rover_rqt_science/src/rqt_rover_science/plugin_view.py | plugin_view.py | py | 568 | python | en | code | null | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.