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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
3038364585 | import pandas as pd
mushrooms = pd.read_csv('mushrooms.csv')
# convert letters to numbers
for n in range(0,mushrooms.shape[1]):
mushrooms.iloc[:,n] = [ord(x) - 97 \
for x in mushrooms[mushrooms.columns[n]]]
mushrooms.to_csv('mushrooms_clean.csv',index=False)
| estimatrixPipiatrix/decision-scientist | pythonCode/support_vector/clean_data.py | clean_data.py | py | 276 | python | en | code | 0 | github-code | 6 |
19528118390 |
__author__ = 'zhaicao'
import sys
from PyQt5.QtWidgets import (QWidget, QPushButton, QLineEdit, QInputDialog, QApplication, QColorDialog,
QFrame, QVBoxLayout, QSizePolicy, QLabel, QFontDialog, QTextEdit, QAction, QFileDialog ,QMainWindow)
from PyQt5.QtGui import QColor, QIcon
#通过输入框改变文字
... | zhaicao/pythonWorkspace | Pyqt5Practice/demo_8.py | demo_8.py | py | 3,852 | python | en | code | 0 | github-code | 6 |
27278546383 | from cProfile import label
from genericpath import exists
from math import ceil
import os
import random
import numpy as np
import argparse
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import optim, autograd
from matplotlib import pyplot as plt
import seaborn as sns
from mpl_... | JiantingFeng/Deep-Ritz-PDE-Solver | new_train.py | new_train.py | py | 6,408 | python | en | code | 3 | github-code | 6 |
39480165735 | import numpy as np
import scipy.sparse as sp
agg1_index = np.load("../trace/agg1_index.npy")
agg1_adj = np.load("../trace/agg1_adj.npy")
input_feature = np.load("../trace/feat1.npy")
coo_row = agg1_index[0]
coo_col = agg1_index[1]
num_nodes = input_feature.shape[0]
"""
# Use adjacency matrix to generate norm
num_nod... | zhang677/SparseAcc | train/dgl/check.py | check.py | py | 4,271 | python | en | code | 0 | github-code | 6 |
17459989896 | from flask import current_app, render_template, make_response, session
from ecom.datastore import db,redis_store
from ecom.exceptions import ServiceUnavailableException
from ecom.models import Item, Cart, Account
import json
import razorpay
from ecom.utils import general_util
class PaymentManager():
@staticmethod... | ubamax/esocial-app | ecom/managers/payment_manager.py | payment_manager.py | py | 3,473 | python | en | code | 0 | github-code | 6 |
23722748410 | from django.urls import path
from gisapp.views import HomeView, county_datasets, point_datasets
from gisapp.api.views import ProvincesListAPIView,ProvincesDetailAPIView
urlpatterns = [
path('', HomeView.as_view(), name='home'),
path('county_data/', county_datasets, name = 'county'),
path('incidence_data/'... | shwky56/geo-django | gisapp/urls.py | urls.py | py | 506 | python | en | code | 0 | github-code | 6 |
42543026750 | """Utility related functions.
"""
import sys
import os
import ctypes
import pygame
from .window import *
def quit():
"""Shuts down ag_py the correct way."""
destroy_window()
pygame.quit()
sys.exit()
def is_admin() -> bool:
"""Determines if the user is running your game as admin."""
try:
... | trypolis464/ag_py | agpy/utils.py | utils.py | py | 951 | python | en | code | 0 | github-code | 6 |
41234449235 | # create by andy at 2022/4/21
# reference:
import torchvision
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
from torch.utils.data import DataLoader
dataset_transform = transforms.Compose([
transforms.ToTensor(),
])
train_set = torchvision.datasets.CIFAR10(root="./dataset",... | beishangongzi/study_torch | p10_dataset/dataset_download.py | dataset_download.py | py | 1,327 | python | en | code | 0 | github-code | 6 |
11038610201 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 19 14:24:54 2018
@author: henyd
"""
from sklearn import tree
from sklearn import svm
import numpy as np
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
def get_response(usrText):
bot = ChatBot('Couns',
storage_adapter='chat... | henydave/career-counselling-chatbot | chatbot_final2.py | chatbot_final2.py | py | 2,211 | python | en | code | 1 | github-code | 6 |
9518060798 | from ast import Lambda
from functools import reduce
l2=[1,2,3,4,5,6,7,8,9]
l=[1,2,3,4,5,6,7,8,9,10]
a=list(filter(lambda x : x>5,l))
print (a)
b=list(map(pow,a,l2))
print(b)
sum=(reduce(lambda x, y: x + y,b))
print(sum)
| SouvikPaul2000/Souvik-paul-2 | Basic code/MapFilterLamdaReduce.py | MapFilterLamdaReduce.py | py | 222 | python | en | code | 0 | github-code | 6 |
3916832510 |
T = int(input())
for _ in range(T):
num = int(input())
dp = [0] * (num + 1)
dp[1] = 1
dp[2] = 2
dp[3] = 4
for i in range(4,num+1):
dp[i] = dp[i-1] + dp[i-2] + dp[i-3]
print(dp[num])
| jun2mun/code_study | 코딩테스트/소프트웨어마에스트로/9095.py | 9095.py | py | 228 | python | en | code | 2 | github-code | 6 |
26465205985 | #aks for your to enter a nummber from 1-10 and if it's the coorect answer it'll say you're correct
NUM = 4
keep_asking = True
while keep_asking == True:
number = int(input("Guess a number between 1 and 10 "))
if number == NUM:
keep_asking = False
print("Good job you guessed the number")
if n... | standrewscollege2018/2021-year-11-classwork-NekoBrewer | Guess the Number.py | Guess the Number.py | py | 504 | python | en | code | 0 | github-code | 6 |
71700390588 | from django.shortcuts import render
from django.shortcuts import render, redirect
from .forms import NewUserForm
from django.contrib.auth import login, authenticate
from django.contrib import messages
from django.contrib.auth.forms import AuthenticationForm
from django.core.mail import send_mail, BadHeaderError
... | KeanDelly/GrowExplore | worldBuilder/Login/views.py | views.py | py | 13,994 | python | en | code | 6 | github-code | 6 |
23589518050 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import mne
fname ="oddball_example_small-fif.gz"
raw = mne.io.read_raw_fif(fname)
raw = mne.io.read_raw_fif(fname,preload=True)
raw.plot_psd();
raw.plot();
#%%data in 20 different ica components
ica = mne.preprocessing.ICA(n_co... | Sarah436/EEG_Control_Drone | EEG_Drone.py | EEG_Drone.py | py | 1,304 | python | en | code | 0 | github-code | 6 |
22989091213 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# utf-8 中文编码
u"""
>>> m=encrypt('123456789','1'*16)
>>> m
'34430c0e47da2207d0028e778c186d55ba4c1fb1528ee06b09a6856ddf8a9ced'
>>> decrypt('123456789',m)
'1111111111111111'
m = encrypt_verify('123','0123456789')
print m
print decrypt_verify('123',m)
"""
from Crypto.Cipher im... | GameXG/shadowsocks_admin | mycrypto.py | mycrypto.py | py | 2,044 | python | zh | code | 175 | github-code | 6 |
27591581690 | import logging
from pymongo import MongoClient
from src.utils import Singleton
logger = logging.getLogger(__name__)
class DBConnection(metaclass=Singleton):
def __init__(self, db_settings):
self.db_settings = db_settings
self.client = MongoClient(
host=db_settings['host'],
... | andre1393/fashion-mnist | src/database/mongo_connection.py | mongo_connection.py | py | 1,388 | python | en | code | 0 | github-code | 6 |
74849030268 | """
@author: Tobias Carryer
"""
import numpy as np
import pandas as pd
from pyts.image import GASF, GADF, MTF
from splitting_data import get_subject_data
from matplotlib import pyplot as plt
def create_gasf_gadf_mtf_compound_images(observations, image_size=128):
"""
Designed to take observations of time seri... | TobCar/delirium | demo_compound_images.py | demo_compound_images.py | py | 3,064 | python | en | code | 0 | github-code | 6 |
15169928273 | from fastapi import Depends, Request
from fastapi_utils.cbv import cbv
from fastapi_utils.inferring_router import InferringRouter
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from admins.models import TemplateField, Template
from permissions import manage_helpdesk
from admins.schemas i... | AlexeyShakov/helpdesk_fast_api | src/admins/endpoints/template_fields.py | template_fields.py | py | 2,294 | python | en | code | 0 | github-code | 6 |
353792942 | import socket
ADDRESS = ("127.0.0.1", 9000)
if __name__ == '__main__':
while True:
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = input("input: ")
client.sendto(data.encode(encoding="utf-8"), ADDRESS)
recv, addr = client.recvfrom(1024)
print(recv.decode(en... | Masterlovsky/NMRVS | tools/client_udp.py | client_udp.py | py | 351 | python | en | code | 0 | github-code | 6 |
5897393360 | from fastapi import FastAPI, HTTPException
from model import Todo
from fastapi.middleware.cors import CORSMiddleware
from database import(
fetch_all_todos,
fetch_one_todo,
create_todo,
remove_todo,
patch_todo
)
app = FastAPI()
origins = [
"https://localhost:3000",
"http://... | MdAhosanHabib/Redis-Kafka-FastAPI-React | main.py | main.py | py | 1,538 | python | en | code | 0 | github-code | 6 |
74130707068 | import datetime
def get_next_friday(some_date: datetime.datetime, if_friday_same=True):
if if_friday_same: # if a Friday, then same day
return some_date + datetime.timedelta((4 - some_date.weekday()) % 7)
else: # if a Friday, then next one
return some_date + datetime.timedelta((... | alex-muci/small-projects | snippets/five_min_test.py | five_min_test.py | py | 748 | python | en | code | 0 | github-code | 6 |
26824633032 | import matplotlib.pyplot as plt
import scipy
import scipy.interpolate
import sys
sys.path.append('/home/faustian/python/adas/xxdata_13/')
from matplotlib import rc
import adasread
rc('text', usetex=True)
rc('font',**{'family':'serif','serif':['Computer Modern Roman']})
#rc('font',**{'family':'sans-serif','sans-serif'... | icfaust/Misc | analyzeSXB.py | analyzeSXB.py | py | 3,468 | python | en | code | 0 | github-code | 6 |
24354887610 | import csv
import requests
import xml.etree.ElementTree as ET
def parseXML(xmlfile):
tree = ET.parse(xmlfile)
root = tree.getroot()
orderitems = []
for item in root.findall('./AddOrder'):
orders = {}
for child in item:
orders[child.tag] = child.text.encode('utf8')
... | actioncamen13/Orderbook-submission | csv_convert.py | csv_convert.py | py | 1,032 | python | en | code | 0 | github-code | 6 |
26624814566 | #
# SERMEPA / ServiRed payments module for Satchmo
#
# Author: Michal Salaban <michal (at) salaban.info>
# with a great help of Fluendo S.A., Barcelona
#
# Based on "Guia de comercios TPV Virtual SIS" ver. 5.18, 15/11/2008, SERMEPA
# For more information about integration look at http://www.sermepa.es/
#
# ... | dokterbob/satchmo | satchmo/apps/payment/modules/sermepa/views.py | views.py | py | 8,365 | python | en | code | 30 | github-code | 6 |
39122527665 | import yaml, tempfile, os, libUi
import PinshCmd, ConfigField
from bombardier_core.static_data import OK, FAIL
from SystemStateSingleton import SystemState
system_state = SystemState()
class CreateType(PinshCmd.PinshCmd):
'''A thing that can be created.'''
def __init__(self, name, help_text):
PinshCmd.... | psbanka/bombardier | cli/lib/Create.py | Create.py | py | 3,460 | python | en | code | 1 | github-code | 6 |
13922774332 | import requests
from authid_agent_client.listeners.request_listener import RequestListener
DEFAULT_HOST = "localhost"
DEFAULT_PORT = 8080
API_PATH = "/api/v0.0.1/"
IDS_PATH = API_PATH + "ids/"
PROCESSOR_KEYS_PATH = API_PATH + "processorKeys/"
REQUESTS_PATH = API_PATH + "requests/"
ADDRESSES_PATH = API_PATH + "addres... | OnePair/authid-agent-client-py | authid_agent_client/authid_agent_client.py | authid_agent_client.py | py | 4,618 | python | en | code | 0 | github-code | 6 |
24416682335 | import tests.links.cloudify_nagios_snmp_trap_handler as snmp_trap_handler
from tests.fakes import FakeLogger
def test_check_name():
logger = FakeLogger()
target_type = 'target'
trap_value = 'trap'
expected = '{target_type}_instances:SNMPTRAP {trap}'.format(
target_type=target_type,
tr... | cloudify-cosmo/cloudify-managed-nagios-plugin | tests/snmp_trap_handler/test_get_check_name.py | test_get_check_name.py | py | 574 | python | en | code | 0 | github-code | 6 |
20040254087 | string = 'I am not sure this will even work'
def rep_chars(string):
rstr = []
lower = string.lower()
for char in lower:
if char.isspace(): continue
elif rstr.count(char * lower.count(char)): continue
elif lower.count(char) > 1:
count = lower.count(char)
... | mwboiss/DSI-Prep | intro_py/string_count.py | string_count.py | py | 746 | python | en | code | 0 | github-code | 6 |
23121624875 | from flask import render_template, flash
from app.giturl_class.url_form import UrlForm
from app.giturl_class import bp
import json
@bp.route('/index', methods = ['GET', 'POST'])
def urlPage():
form = UrlForm()
citation = None
installation = None
invocation = None
description = None
if form.vali... | quiteaniceguy/SM2KG-WebApp | app/giturl_class/routes.py | routes.py | py | 1,182 | python | en | code | 0 | github-code | 6 |
34553013793 | # coding:utf8
from numpy import *
from loadnews import *
'''
Description:分析新闻数据主成分特征
Author:伏草惟存
Prompt: code in Python3 env
'''
'''分析数据'''
def analyse_data(dataMat,topNfeat = 20):
# 去除平均值
meanVals = mean(dataMat, axis=0)
meanRemoved = dataMat-meanVals
# 计算协方差矩阵
covMat = cov(mean... | bainingchao/PyDataPreprocessing | Chapter9/analyse.py | analyse.py | py | 1,828 | python | zh | code | 157 | github-code | 6 |
30763963293 | # Permanently saving data
import pickle
class Person():
def __init__(self, name, gender, age):
self.name = name
self.gender = gender
self.age = age
print('You have crated a new person named: ', self.name)
def __str__(self):
# Formating the message
return '{} ... | Giorc93/PythonCourse | ExternalFiles/TextFiles/SavingData/savingData.py | savingData.py | py | 1,432 | python | en | code | 1 | github-code | 6 |
19065408732 | from confluent_kafka import Consumer
import redis
import time
from datetime import datetime
################
r = redis.Redis(host='localhost', port=6379)
c=Consumer({'bootstrap.servers':'localhost:9092','group.id':'python-consumer','auto.offset.reset':'earliest'})
print('Available topics to consume: ', c.list_topics(... | Failedvixo/SD-Tarea2 | kafka_consumer.py | kafka_consumer.py | py | 857 | python | en | code | 0 | github-code | 6 |
21416490365 | # #!/usr/bin/env python
# #coding:utf-8
from random import randint
from BaseAI import BaseAI
from Common import *
#from ComputerAI import ComputerAI
class PlayerAI(BaseAI):
def getMove(self, grid, weight):
# I'm too naive, please change me!
depth = 0
cells = grid.getAvailableCells()
limit = 3
bestmove... | Staniel/AI2048 | PlayerAI.py | PlayerAI.py | py | 1,971 | python | en | code | 1 | github-code | 6 |
2115336751 | # Affine Cipher
# With ASCII Table
# suhaarslan
import sys
keys = (15,21)
def encrypt(chr):
global keys
formula = lambda a,b,c,m:(a*(c-m)+b)%26+m
if chr < 97:
return formula(keys[0],keys[1],chr,65)
elif chr > 90:
return formula(keys[0],keys[1],chr,97)
def decrypt(chr):
global keys
... | programmer-666/Cryptography | Symetric/Affine.py | Affine.py | py | 1,006 | python | en | code | 0 | github-code | 6 |
19990844115 | from django.conf.urls import url
from . import views, verifycode
urlpatterns = [
url(r'^$', views.index),
# 生成验证码
url(r'^verifycode/$', verifycode.Verifycode),
# 输入验证码试验
url(r'^verifycodeinput/$', views.verifycodeinput),
url(r'^verifycodecheck/$', views.checkcode),
# 反向解析(针对的是超链接,千万别弄错)
... | Evanavevan/Django_Project | Project3/myApp/urls.py | urls.py | py | 700 | python | en | code | 0 | github-code | 6 |
14242354466 | #基类,将原生的方法都封装一遍,让继承的类去调用
import csv
import logging
import os
from time import sleep, strftime
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from baseView.desired_caps import appium_desired
class BaseView(object):
def __init__(self,driver): #初始化方法... | XiaoChang97/maishou_testProject | baseView/baseView.py | baseView.py | py | 5,558 | python | zh | code | 0 | github-code | 6 |
19492440920 | # -*- coding: utf-8 -*-
from flask import Flask,request,abort # 引用flask库
import os
import time
import sys, getopt
from dd.mylog import TNLog
import dd
logger = TNLog()
print(__name__)
app= Flask(__name__)
app.config.update(DEBUG=True)
# 定义路由
@app.route('/')
def hello_world():
out = os.popen('docker info').re... | stosc/dockerDeployer | dd/run.py | run.py | py | 3,114 | python | en | code | 0 | github-code | 6 |
24998585781 | import wizard
import pooler
import datetime
import time
from copy import deepcopy
import netsvc
from tools.translate import _
_schedule_form = '''<?xml version="1.0"?>
<form string="Interview Scheduling Of Candidate">
<field name="start_interview"/>
<field name="end_interview"/>
<field name="interval_time"... | factorlibre/openerp-extra-6.1 | hr_interview/wizard/wiz_schedule.py | wiz_schedule.py | py | 4,374 | python | en | code | 9 | github-code | 6 |
30133946462 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
-... | Divjot-kaur/python | rock_paper_scissors.py | rock_paper_scissors.py | py | 969 | python | en | code | 0 | github-code | 6 |
42649131070 | """ some tools """
import logging
import re
import sys
from rancon import settings
tag_matcher = re.compile("%([A-Z0-9]+)%")
def fail(message):
""" logs message before calling sys.exit
XXX: why is this using print not log?
"""
if isinstance(message, list) or isinstance(message, tuple):
... | flypenguin/python-rancon | rancon/tools.py | tools.py | py | 1,596 | python | en | code | 0 | github-code | 6 |
37108029587 | """2 question 6 sprint"""
import json
import logging
logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
def parse_user(output_file, *input_files):
def get_name(dct):
if "name" in dct and dct["name"] not in list(map(lambda x: x["name"], users_list)):
... | Misha86/python-online-marathon | 6_sprint/6_2question.py | 6_2question.py | py | 803 | python | en | code | 0 | github-code | 6 |
10696495998 | # -*- coding: utf-8 -*-
import os
import uuid
import json
import requests
import re
from datetime import datetime
import urllib
import hmac
import base64
from threading import Timer
REQUEST_URL = 'https://alidns.aliyuncs.com/'
LOCAL_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ip.txt')
ALIYUN_SET... | mikuh/aliyun_ddns | ddns.py | ddns.py | py | 4,069 | python | en | code | 0 | github-code | 6 |
910975330 | import sys, argparse, os, numpy as np
from horton import __version__, IOData
# All, except underflows, is *not* fine.
np.seterr(divide='raise', over='raise', invalid='raise')
def parse_args():
parser = argparse.ArgumentParser(prog='horton-convert.py',
description='Convert between file formats supported... | theochem/horton | scripts/horton-convert.py | horton-convert.py | py | 1,810 | python | en | code | 83 | github-code | 6 |
36411448777 |
#import logging; logging.basicConfig(level=logging.INFO)
import asyncio, os, json, time, base64
from datetime import datetime
from aiohttp import web
from jinja2 import Environment, FileSystemLoader
from log import Log,create_logger
import config as conf
import common.orm as orm
from common.webmiddlewares import ... | jkilili/python_web | www/app.py | app.py | py | 3,208 | python | en | code | 0 | github-code | 6 |
20572139596 | from ._base import _rule
from .field import Field
from .operators.operator import Operator
class Expr(Field, Operator):
reserved = {**Field.reserved, **Operator.reserved}
tokens = Field.tokens + Operator.tokens
precedence = Field.precedence + Operator.precedence
# rules
_start = 'expr'
@_rul... | bluerelay/windyquery | windyquery/validator/expr.py | expr.py | py | 1,965 | python | en | code | 68 | github-code | 6 |
23307657200 | from __future__ import print_function
try:
# For Python 3.0 and later
from urllib.request import urlopen
from urllib.request import urlretrieve
from urllib import request
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
from urllib import urlretrieve
import ... | nblago/utils | src/utils/finder_chart.py | finder_chart.py | py | 24,759 | python | en | code | 2 | github-code | 6 |
72683668667 | import sys
from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QPushButton, QLabel, QHBoxLayout, QLineEdit
button_y_position = 0.1 # Initial Y position for the buttons
class Addsubject(QDialog):
def __init__(self):
super().__init__()
self.setWindowTitle('Custom Pop-up Block')
... | Rush-154/DBMS | Login/flexcards.py | flexcards.py | py | 2,119 | python | en | code | 0 | github-code | 6 |
15191243945 | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
prefix = []
prod = 1
for i in nums:
prod *= i
prefix.append(prod)
sufix = []
prod = 1
for i in range(len(nums)-1,-1,-1):
prod *= nums[i]
sufix.a... | Dumbris/leetcode | medium/238.product-of-array-except-self.py | 238.product-of-array-except-self.py | py | 644 | python | en | code | 0 | github-code | 6 |
22941445874 | import re
log_lines=None
with open(r"C:\Users\remote_pc\Desktop\python_log2.txt",'r',encoding='utf-8') as log_txt:
log_lines=log_txt.readlines()
machine_policty_logs={}
for line in log_lines:
if 'Machine policy' in line:
re_result_time=re.findall(r'\[\d+:\d+:\d+:\d+\]',line)[0].replace('[',''... | sam4u3/Ignicia_Python | file_io.py | file_io.py | py | 901 | python | en | code | 0 | github-code | 6 |
16062801257 | import pygame
import init
from gui_config import Config
from widget import Widget
class Label(Widget):
def __init__(self,
text,
x,y,width,height,
config=Config.default_drawing_conf):
Widget.__init__(self,x,y,width,height,config)
self.__set_text(text)
... | unusualcomputers/unusualgui | code/label.py | label.py | py | 2,516 | python | en | code | 0 | github-code | 6 |
73822719228 | import math
def findMag(vector):
return math.sqrt(vector[0]**2 + vector[1]**2 + vector[2]**2)
def findUnit(vector):
unit = []
mag = findMag(vector)
if mag == 0:
return [0,0,0]
for a,b in enumerate(vector):
unit.append(b/mag)
return unit
def dotProduct(vector1,vector2):
dot = 0
for a,b in... | CaelumD25/Statics-Equations | ENGR141 Equations/mymath.py | mymath.py | py | 1,084 | python | en | code | 0 | github-code | 6 |
6922603466 | import os
# python -m pip install --upgrade pip
# python -m pip install --upgrade Pillow
from PIL import Image
# pip install numpy
import numpy as np
#######################################################################
black=[25,25,25]
blue=[50,75,175]
brown=[100,75,50]
cyan=[75,125,151]
gray=[75,75,75]
green=[100... | kirbycope/map-markers-java | img.py | img.py | py | 4,689 | python | en | code | 0 | github-code | 6 |
42483141861 | import os
import json
import requests
from flask import Flask, jsonify, request, Response
from faker import Factory
from twilio.access_token import AccessToken, IpMessagingGrant
app = Flask(__name__)
fake = Factory.create()
@app.route('/')
def index():
return app.send_static_file('index.html')
@app.route('/ton... | AvonGenesis/jwms | app.py | app.py | py | 2,338 | python | en | code | 0 | github-code | 6 |
18527949488 | import pytest
from selene.support.shared import browser
from selene import be, have
@pytest.fixture(scope='session', autouse=True)
def browser_size():
browser.config.window_width = 1280
browser.config.window_height = 720
def test_search(browser_size):
browser.open('https://google.com')
browser.eleme... | ekat-barkova/qa_guru_python_6_2_homework | tests/test_google_should_find_selene.py | test_google_should_find_selene.py | py | 788 | python | en | code | 0 | github-code | 6 |
72761928188 | import nussl
import torch
from torch import nn
from torch.nn.utils import weight_norm
from nussl.ml.networks.modules import (
Embedding, DualPath, DualPathBlock, STFT,
LearnedFilterBank, AmplitudeToDB, RecurrentStack,
MelProjection, BatchNorm, InstanceNorm, ShiftAndScale
)
import numpy as np
from . import ... | bfredl/tutorial | common/models.py | models.py | py | 6,359 | python | en | code | 1 | github-code | 6 |
43008598388 | # coding:utf-8
import operator
import re
import math
import numpy as np
file_path = "./GameOfThrones.txt"
def num_dict(str):
alist = []
letter_list = [chr(i) for i in range(ord("A"), ord("Z") + 1)] + ["space"]
for i in range(26): # 初始化一个长度为26的列表
alist.append(0)
str = str.lower()
for i in ... | weixinxu666/encoders | shannon.py | shannon.py | py | 5,662 | python | en | code | 3 | github-code | 6 |
11300309585 | from django.contrib import admin
from django.urls import path
from firstapp import views as v1
urlpatterns = [
path('admin/', admin.site.urls),
path('home/',v1.home),
path('gm/',v1.gm_),
path('ga/',v1.ga_),
path('gn/',v1.gn_),
] | Ranjith8796/Demo | firstapp/urls.py | urls.py | py | 262 | python | en | code | 0 | github-code | 6 |
5898520470 | import os
from datetime import datetime, timezone
import tweepy
def scrape_user_tweets(username: str, num_tweets: int = 10) -> list:
"""
Scrapes Twitter user's original tweets (i.e., no retweets or replies) and returns them as a list of dictionaries.
Each dictionary has three fields: "time_posted" (relat... | mdalvi/langchain-with-milind | third_parties/twitter.py | twitter.py | py | 1,318 | python | en | code | 2 | github-code | 6 |
28108895632 | import mat73
import matplotlib.pyplot as plt
FORMAT = 'pdf'
plt.rcParams.update({'font.size': 22})
datasets = ["Brain", "MAG-10", "Cooking", "DAWN", "Walmart-Trips", "Trivago"]
budgets = [0, .01, .05, .1, .15, .2, .25]
budget_strings = ['0.0', '0.01', '0.05', '0.1', '0.15', '0.2', '0.25']
n = [638, 80198, 6714, 2109... | TheoryInPractice/overlapping-ecc | Exp1-Algorithm-Evaluation/R_Plots.py | R_Plots.py | py | 2,373 | python | en | code | null | github-code | 6 |
71483943548 | # SPDX-License-Identifier: MIT
# (c) 2023 knuxify and Ear Tag contributors
from gi.repository import GObject, GLib
import threading
import time
class EartagBackgroundTask(GObject.Object):
"""
Convenience class for creating tasks that run in the background
without freezing the UI.
Provides a "progress... | knuxify/eartag | src/utils/bgtask.py | bgtask.py | py | 3,589 | python | en | code | 67 | github-code | 6 |
31261537971 | from collections import namedtuple
from itertools import izip
from operator import attrgetter
from tilequeue.log import LogCategory
from tilequeue.log import LogLevel
from tilequeue.log import MsgType
from tilequeue.metatile import common_parent
from tilequeue.metatile import make_metatiles
from tilequeue.process impor... | thanhnghiacntt/tilequeue | tilequeue/worker.py | worker.py | py | 24,574 | python | en | code | 0 | github-code | 6 |
73832973307 | import numpy as np
from .anim_utils.animation_data.joint_constraints import JointConstraint
def normalize(v):
return v/np.linalg.norm(v)
def array_from_mosim_t(_t):
t = np.zeros(3)
t[0] = -_t.X
t[1] = _t.Y
t[2] = _t.Z
return t
def array_from_mosim_q(_q):
q = np.zeros(4)
q[0] = -_q.W
... | mercedes-benz/MOSIM_Core | BasicMMus/Python-MMUs/MGReach/utils.py | utils.py | py | 2,927 | python | en | code | 16 | github-code | 6 |
43193627416 | #!/usr/bin/env python
import rospy
import smach
from PrintColours import *
from std_msgs.msg import String
class Idle(smach.State):
def __init__(self,pub,autopilot,uav_id):#modify, common_data
smach.State.__init__(
self, outcomes=['gcs_connection', 'shutdown'])
self.pub = pub
s... | miggilcas/muav_state_machine | scripts/AgentStates/idle.py | idle.py | py | 1,523 | python | en | code | 0 | github-code | 6 |
22963907434 | import urllib3
# 忽略警告:InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised.
urllib3.disable_warnings()
import json
import os
# http://www.meituan.com/meishi/api/poi/getMerchantComment?id=42913246&offset=0&pageSize=50&sortType=1
COMMENT_URL = 'http://www... | puke3615/comment_spider | comment_spider/util.py | util.py | py | 4,172 | python | en | code | 5 | github-code | 6 |
5139284225 | def getobjectgroups(DATA) -> list:
result = list()
ogroup = dict()
ogroup['items'] = list()
ogroup_detected = False
for _ in DATA:
data = _.strip().split()
if len(data) == 0:
continue
if data[0] == "object-group":
ogroup_detected = True
ogr... | Rel1ct0/Convert2FortiGate | Scripts/IOS/getobjectgroups.py | getobjectgroups.py | py | 1,074 | python | en | code | 0 | github-code | 6 |
33645109204 | from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from datetime import datetime, timedelta
calendar_id = os.environ... | Santixs/NotionGSync | gcalendarsync.py | gcalendarsync.py | py | 3,727 | python | en | code | 1 | github-code | 6 |
8774738477 | import gym
import numpy as np
from cartpole_deep_net import CartpoleDeepNet
class CartPole:
def __init__(self, render_mode='None'):
self.env_title = 'CartPole-v1'
self.env=gym.make(self.env_title, render_mode=render_mode)
self.single_state_shape_len = 1
self.... | asharali001/Deep-Q-Learning | cartpole.py | cartpole.py | py | 1,231 | python | en | code | 0 | github-code | 6 |
39293592719 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name o... | WaadShehab/Explore_US_Bikeshare_Data | bikeshare.py | bikeshare.py | py | 6,672 | python | en | code | 0 | github-code | 6 |
33725319623 | import qiskit_toqm.native as toqm
class ToqmHeuristicStrategy:
def __init__(self, latency_descriptions, top_k, queue_target, queue_max, retain_popped=1):
"""
Constructs a TOQM strategy that aims to minimize overall circuit duration.
The priority queue used in the A* is configured to drop t... | qiskit-toqm/qiskit-toqm | src/qiskit_toqm/toqm_strategy.py | toqm_strategy.py | py | 3,866 | python | en | code | 6 | github-code | 6 |
23060222816 | import math
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
compdata=np.loadtxt('compdata.txt')
agelabel=compdata[:,0]
compdata=compdata[:,1]
obsdata=np.loadtxt('obsdata.txt')
error=obsdata[:,3]
obsdata=obsdata[:,1]
#plt.plot(agelabel, compdata, 'r',label='Computed data')
plt... | AndreasMu/Bachelor | Graphs and Tex/obsdataplot.py | obsdataplot.py | py | 554 | python | en | code | 0 | github-code | 6 |
44665541614 | import random
l = ["O", "P"]
k = []
count = 0
s = 10
while s:
x = random.randint(0, 1)
k.append(x)
for i in range(len(k)-2):
if k[i] + k[i+2] == 0:
print("O")
print(k)
elif k[i] + k[i+2] == 2:
print("P")
print(k)
s-=1
# n = int(i... | AkulaBiznesu/training | _Coin x3.py | _Coin x3.py | py | 499 | python | en | code | 0 | github-code | 6 |
31534048424 | import telebot;
import os
import subprocess
import re
#получение токена при запуске и возможно его сохранение
file = open("Token", "r")
token = file.read()
file.close()
bot = telebot.TeleBot(token)
os.system("echo запущено")
@bot.message_handler(content_types=['text'])
def get_text_messages(message):
if message.text ... | romazanovma/probable-octo-potato-telegram-bot | bot.py | bot.py | py | 1,759 | python | ru | code | 0 | github-code | 6 |
74197622589 | from rest_framework import serializers
from des.models import Exposure, SkybotJob, SkybotJobResult
class SkybotJobResultSerializer(serializers.ModelSerializer):
# job = serializers.PrimaryKeyRelatedField(
# queryset=SkybotJob.objects.all(), many=False
# )
# exposure = serializers.PrimaryKeyRela... | linea-it/tno | backend/des/serializers/skybot_job_result.py | skybot_job_result.py | py | 1,678 | python | en | code | 1 | github-code | 6 |
22134160802 | from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name = 'home'),
path('about', views.about, name = 'about'),
path('create', views.create, name = 'create'),
path('review', views.review, name = 'review'),
path('test1', views.test1, name = 'test1'),
path('<int... | Voron4ikhin/Web_lab | taskmanager/main/urls.py | urls.py | py | 553 | python | en | code | 0 | github-code | 6 |
11975286960 | from socket import *
from ssl import *
from _ssl import PROTOCOL_TLSv1
finished = False
client_socket = socket(AF_INET, SOCK_STREAM)
tls_client = wrap_socket(client_socket,
ssl_version=PROTOCOL_TLSv1,
cert_reqs=CERT_NONE)
address = 'localhost'
port = 6668
bufsize =... | SamXSu/458Project | client/client.py | client.py | py | 697 | python | en | code | 0 | github-code | 6 |
25791786011 | import sys
class Shift:
def encrypt(self, plain, a):
cipher = ''
for ch in plain:
i = char_to_int(ch)
i = (i + a) % 26
ch = int_to_char(i)
cipher += ch
return cipher
def decrypt(self, cipher, a):
plain = ''
for ch in cip... | Ismail-Mahmoud/Cryptography-Assignments | Assignment1/ciphers.py | ciphers.py | py | 3,088 | python | en | code | 0 | github-code | 6 |
71200356027 | from moviepy.editor import *
from moviepy.video.tools.subtitles import SubtitlesClip
import moviepy.video.fx as vfx
def create_srt(line):
subs_obj = open(r"D:\Final Renders\your next line.srt", "r")
orig_subs = subs_obj.read().split("\n")
print(orig_subs)
orig_subs[6] = f"\"{line}\""
orig_subs[10... | alwynwan/Messenger-Bot | srtgen.py | srtgen.py | py | 1,002 | python | en | code | 0 | github-code | 6 |
17335047402 | import sesame
import numpy as np
######################################################
## define the system
######################################################
# dimensions of the system
Lx = 3e-4 #[cm]
Ly = 3e-4 #[cm]
# extent of the junction from the left contact [cm]
junction = .1e-4 # [cm]
# Mes... | usnistgov/sesame | examples/tutorial5/2d_EBIC.py | 2d_EBIC.py | py | 4,876 | python | en | code | 16 | github-code | 6 |
3643899773 | import random
import time
isim = input("Merhaba! İsminiz nedir ?")
print("Sayı tahmin oyununa hoşgeldin")
print("Şimdi 1-50 arası sayı tahmin et",isim)
secilen = random.randint(1,50) #1-50 arası random sayı üretir
can = 6
while True:
deger = int(input("Tahmin ettiğin sayı: "))
if(deger < ... | brcmst/python-tutorials | GuessingGame.py | GuessingGame.py | py | 958 | python | tr | code | 0 | github-code | 6 |
71913849148 | import requests
API_ENDPOINT = 'https://api.openai.com/v1/chat/completions'
API_KEY = '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'
MODEL_ID = 'gpt-3.5-turbo'
def test_chatgpt_api():
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
d... | Ali-Jabowr/TelegramWordBot | commands/chatgpt_testing.py | chatgpt_testing.py | py | 777 | python | en | code | 0 | github-code | 6 |
7650485189 | # Author hugo
# Time 2023/8/11 13:02
'''
学生信息管理系统
'''
import os.path
'''
需求分析
系统设计
系统开发必备
主函数设计
学生信息维护模块设计
查询/统计模块设计
排序模块设计
项目打包
'''
# 需求分析
'''
学生管理系统应具备的功能
添加学生及成绩信息
将学生信息保存到文件中
修改和删除学生信息
查询学生信息
根据学生成绩进行排序
统计学生的总分
'''
# 系统设计
'''
系统功能结构
学生信息管理系统的7大模块
录入学生信息模块
查找学生信息模块
... | hjzts/python_code | python_study/exercise/学生信息管理系统.py | 学生信息管理系统.py | py | 12,248 | python | zh | code | 1 | github-code | 6 |
28639960700 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import lldb
import re
import optparse
import ds
import shlex
class GlobalOptions(object):
symbols = {}
@staticmethod
def addSymbols(symbols, options, breakpoint):
key = str(breakpoint.GetID())
GlobalOptions.symbols[key] = (symbols, options)
... | DerekSelander/LLDB | lldb_commands/breakifonfunc.py | breakifonfunc.py | py | 3,454 | python | en | code | 1,689 | github-code | 6 |
24362182930 | from datetime import date, timedelta
from .downloaders import Downloader
from .parsers import Parser
class RequiredValue():
def __init__(self, child_of=None):
self.child_of = child_of
def __call__(self, value):
return self.child_of is None or isinstance(value, self.child_of)
class Default... | suningwz/netaddiction_addons | netaddiction_octopus/base/supplier.py | supplier.py | py | 2,132 | python | en | code | 0 | github-code | 6 |
31957664132 | # https://www.hackerrank.com/challenges/candies/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dynamic-programming
def candies(arr):
candies = [1 for i in range(len(arr))]
for i in range(0, len(arr) - 1):
if(arr[i] < arr[i+1]):
candies[i+1] = can... | JacobLayton/code-problems | hackerrank/Python/candies.py | candies.py | py | 672 | python | en | code | 0 | github-code | 6 |
72784214587 | # https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2
from itertools import starmap
def solve(arr):
def conv(t1,t2):
t1 = tuple(map(int,t1.split(":")))
t2 = tuple(map(int,t2.split(":")))
hd1, md = divmod((t2[1] - t1[1] - 1), 60)
hd2 = (t2[0] - t1[0] + hd1) % 24
mm = (hd2... | blzzua/codewars | 6-kyu/simple_time_difference.py | simple_time_difference.py | py | 487 | python | en | code | 0 | github-code | 6 |
23768567133 | #!/usr/bin/env python3
"""Main."""
import sys
from cpu import *
cpu = CPU()
program = "default"
if len(sys.argv) == 2:
program = sys.argv[1]
elif len(sys.argv) > 2:
print("Only one program can be ran at a time. First argument will be used.")
program = sys.argv[1]
elif len(sys.argv) < 2:
print("No pro... | VictorGoic0/Computer-Architecture | ls8/ls8.py | ls8.py | py | 393 | python | en | code | 0 | github-code | 6 |
12746838211 | from tkinter import *
grid = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9,... | Programmer-X31/PythonProjects | Project Sudoku Solver/efficient_main.py | efficient_main.py | py | 1,862 | python | en | code | 0 | github-code | 6 |
33135136420 | str1 = 'AABBCCDDEEFFGFZZZZZZ'
lst1 = [word for word in str1]
i = 0
while (i<len(lst1)-1):
if lst1[i] != lst1[i+1]:
(x,y) = (lst1[i],lst1[i+1])
print (x,y)
lst1.remove(lst1[i])
lst1.remove(lst1[i])
i = 0
else:
i = i + 1
#Result:
('A', 'B')
('A', 'B... | Unmindful/Classic-Short-Problems-in-Python | Array Pair Creation.py | Array Pair Creation.py | py | 382 | python | en | code | 0 | github-code | 6 |
71718724348 | #GUI-less stuff here...
from . import FileOps
import numpy as np
import math
from . import MTLsetup
def MTLPlotData(fname):
data=GetTransferSetupData(fname)
dists=[]
temps=[]
r_errs=[]
ind1=[]
ind2=[]
for setup in data:
for sats in setup:
#slow...
n_opst,d,i1,i2,r_err=sats[0:5]
t=sat... | SDFIdk/nivprogs | MyModules/Analysis.py | Analysis.py | py | 6,438 | python | en | code | 0 | github-code | 6 |
24756305475 | import os
import sys
def execute_pipleline(n_prototipes, window_size, step, max_level, standardization, weight):
call1 = 'python 1.sample.py lightcurves.R.txt {0} {1} {2} {3}'.format(n_prototipes, standardization, window_size, step)
call2 = 'python 2.twed.py lightcurves.R.txt {0} {1} {2} {3}'.format(n_prototi... | luvalenz/time-series-variability-tree | pipeline.py | pipeline.py | py | 1,598 | python | en | code | 2 | github-code | 6 |
4473417766 | import datetime
import logging
import re
from estropadakparser.parsers.parser import Parser
from estropadakparser.estropada.estropada import Estropada, TaldeEmaitza
class ArcParserLegacy(Parser):
'''Base class to parse an ARC legacy(2006-2008) race result'''
def __init__(self, **kwargs):
pass
de... | ander2/estropadak-lxml | estropadakparser/parsers/arc_legacy_parser.py | arc_legacy_parser.py | py | 4,486 | python | eu | code | 2 | github-code | 6 |
14927451670 | import tkinter as tk
from tkinter import filedialog, simpledialog, messagebox, Scale, HORIZONTAL
from tkinter.ttk import Notebook
from PIL import Image, ImageTk
import random
import os
import shutil
import zipfile
import json
class TraitBubble:
def __init__(self, canvas, trait_name, x, y, prob_scale):
self... | net1ife/NFT-generation | v0.py | v0.py | py | 7,914 | python | en | code | 0 | github-code | 6 |
1008006432 | '''Solving today's Yohaku Puzzle posted on Twitter
https://twitter.com/1to9puzzle/status/1123345947755311105
May 1, 2019'''
import random
import time
start = time.time()
NUMS = [1,2,3,4,5,6,7,8,9]
products = [90,90,72,24]
attempts = 0
#infinite loop
while True:
#increment attempts
attempts +... | hackingmath/puzzles | yohakuPuzzle050119Products.py | yohakuPuzzle050119Products.py | py | 1,003 | python | en | code | 7 | github-code | 6 |
40369189284 | from multiprocessing.spawn import old_main_modules
from os import listdir
from os.path import isfile, join
from wordcloud import WordCloud
import codecs
import jieba
import matplotlib.pyplot as plt
# read data
mypath = 'lab/contexts/'
font_filename = 'fonts/STFangSong.ttf'
files = [f for f in listdir(mypath) if isfil... | NATaaLiAAK/PPE1 | cloud_build.py | cloud_build.py | py | 1,000 | python | en | code | 0 | github-code | 6 |
8420322841 | # Program to show classes and objects in Python
class Person:
def __init__(self,name, age):
self.name = name # instance attribute
self.age = age
person1 = Person("David", 31)
print("person 1 name = ", person1.name)
print("person 1 age = ", person1.age)
person2 = Person("Paul",32)
print("person ... | davidjava1991/Python3CompleteCourse | Section6/lecture61/Program1.py | Program1.py | py | 384 | python | en | code | 1 | github-code | 6 |
35743736914 | import sys
import os
import numpy as np
import scipy.sparse
from scipy.sparse import csr_matrix, find
import read_write as rw
import matlab.engine
'''
finput_iu_rating_matrix_train = "Data/iu_sparse_matrix_train.npz"
finput_title_sim_matrix = "Data/title_similarity_matrix"
finput_description_sim_matrix = "D... | clamli/Dissertation | Step1-Preprocessing/buildtree_preparation.py | buildtree_preparation.py | py | 4,436 | python | en | code | 28 | github-code | 6 |
17615533766 | import web
import os
urls = ('/upload', 'Upload')
class Upload:
def GET(self):
web.header("Content-Type","text/html; charset=utf-8")
return open(r'upload.html', 'r').read()
def POST(self):
try:
x = web.input(myfile={})
filedir = 'submit' # change this to the... | Louis-He/simpleOj | webmain.py | webmain.py | py | 2,766 | python | en | code | 0 | github-code | 6 |
71226678909 | from hzf.file import base_file
import os
# ------------------------------ base_file -----
bfile = base_file.BaseFile()
# ===== folder
testfolder = os.getcwd() + r"\temp\testfolder"
bfile.create_folder(testfolder)
bfile.remove_folder(testfolder)
# ===== path
print(bfile.split_path_drive(testfolder))
print(bfile.split... | huangzf128/something | code/python/hzf-unittest/file.py | file.py | py | 685 | python | en | code | 0 | github-code | 6 |
12639157505 | """Escribe un programa que calcule el promedio general de una clase."""
quant = int(input(f"Ingrese la cantidad de alumnos que tiene la clase: "))
count = 0
acc = 0
while count < quant:
acc += int(input(f"Ingrese la nota del alumno Nº {count + 1}: "))
count += 1
print(f"El promedio final de la clase es {acc / qu... | sbelbey/pp-python | Ejercicios_21_al_30/ejercicio24.py | ejercicio24.py | py | 327 | python | es | code | 0 | github-code | 6 |
7125623220 | ######################################################
### SQL Database Script for PokeDex and TrainerDex ###
######################################################
import numpy as np
import pandas as pd
from sqlalchemy import create_engine
from config import password
import pprint as pp
# Set locations for CSV Files... | ASooklall/ETL_Project | pokemon_db/pokemon_db.py | pokemon_db.py | py | 4,633 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.