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
39761904162
import json import os from time import sleep from aviso_monitoring import logger from aviso_monitoring.collector.config import Config from aviso_monitoring.collector.time_collector import TimeCollector from aviso_monitoring.udp_server import UdpServer def take_some_time(seconds=0.1, flag=False, flag2=True): slee...
ecmwf/aviso
aviso-server/monitoring/tests/test_time_collector.py
test_time_collector.py
py
2,449
python
en
code
9
github-code
13
37966286118
import commands ########################################################################### include("LArCalibProcessing/LArCalib_Flags.py") include("RecExCommission/GetInputFiles.py") ####################################################### # Run properties #######################################################...
rushioda/PIXELVALID_athena
athena/LArCalorimeter/LArCalibTools/share/LArParamsFromDB2NTuple_jobOptions.py
LArParamsFromDB2NTuple_jobOptions.py
py
6,957
python
en
code
1
github-code
13
41823447719
import numpy as np from PIL import Image beta, eta, h =1e-3,2.1e-3,0.0 def E(x,y): xxm=np.zeros_like(x) xxm[:-1, :]=x[1:, :] xxm[1:, :]+=x[:-1, :] xxm[:, :-1] += x[:, 1:] # right xxm[:, 1:] += x[:, :-1] # left xx = np.sum(xxm * x) xy = np.sum(x * y) xsum = np.sum(x) return h * xs...
imwebson/learn
image/image.py
image.py
py
1,589
python
en
code
0
github-code
13
17350992302
'''This application connects to the USGS and OpenCage API's to collect earthquake data and store it in a csv file that is overwritten whenever the app is ran''' import requests, xmltodict, json, csv, toTime, creds response = requests.get("https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson"...
JosephABB/earthquake_data_pub
main.py
main.py
py
3,291
python
en
code
0
github-code
13
29753234806
# 함수 실습 p.2 def personal_info(file, save, search): def file_open(): f = open(file, "r") data = f.read() data = data.split("\n") f.close() return data def name(data): i = 0 lst = [] while i <len(data): if "Name" in data[i]: ...
1000hyehyang/Advanced-Python-Programming
week15/Ex07_01.py
Ex07_01.py
py
1,394
python
en
code
0
github-code
13
11628410045
#!/usr/bin/env python # =============================================================================== from . import Logger, __home__, __scratch__ from .campaigns import Campaign from .databases import Database from .datasets import Dataset from .emulators import Emulator from .evaluators import Evaluator from .obje...
aspuru-guzik-group/olympus
src/olympus/olympus.py
olympus.py
py
5,968
python
en
code
70
github-code
13
26390923019
#!/usr/bin/env python """ Constructs a PNG graph of workout data """ #from pylab import * from datetime import datetime class DataReader(object): """ In charge of reading in a csv file with workout data """ def __init__(self): self.data = {} def read_data(self, file_name)...
mjgpy3/ExerciseManager
build_progress_graph.py
build_progress_graph.py
py
3,209
python
en
code
0
github-code
13
32591192681
import random import requests from .globals import bitcoin def get_fee(tx): # multiply stuff by 100000000 because bitcoind returns values in btc inputsum = sum( [ int( bitcoin.getrawtransaction(inp["txid"], True)["vout"][inp["vout"]][ "value" ...
fiatjaf/lnchannels
getdata/utils.py
utils.py
py
1,065
python
en
code
23
github-code
13
23886654065
#!/usr/bin/env python3 import colorsys, io, logging, math, pantilthat, picamera, random, socketserver, sys, threading, time from http import server HTML_PAGE = """<!doctype html> <html lang="en"> <head> <meta name="charset" value="utf-8"> <title> Raspberry Webcam </title> <style type="...
hacker-bastl/raspberry
ansible/roles/camera/files/webcam.py
webcam.py
py
5,540
python
en
code
2
github-code
13
39637045120
""" Module of manager for managing multiple bulbs. """ import logging import platform import subprocess import threading import time from copy import copy from queue import Queue from typing import List import ifaddr from sqlalchemy import func from yeelight import discover_bulbs, BulbException from .bulb import Bulb...
NikSavilov/yeelight-atmosphere
src/yeelight_atmosphere/manager.py
manager.py
py
11,882
python
en
code
0
github-code
13
12229802582
from aiogram import Bot, types import logging from datetime import datetime import asyncio from aiogram.dispatcher import Dispatcher from aiogram.utils import executor from aiogram.types import * from zqmpwork import Parcer from time import sleep bot = Bot(token='YOUR TOKKEN') dp = Dispatcher(bot) logging.basicConfi...
prn-ic/myfsttgbot
bot.py
bot.py
py
4,360
python
ru
code
0
github-code
13
38760984852
# import necessary modules from bs4 import BeautifulSoup import requests import datetime import pandas as pd # create the file writer = pd.ExcelWriter('data.xlsx', engine='xlsxwriter') # data source url = "https://coinmarketcap.com/" # get the data from the source result = requests.get(url).text doc ...
GKK7/Projects
Web projects/Crypto.py
Crypto.py
py
1,613
python
en
code
2
github-code
13
74632619216
# Jason Morris # Work in progress # June 1, 2016 import json, requests print('') #load all json data from json dump data_in_file = open('airQualityIn.json') dataIn = json.load(data_in_file) data_in_file.close() #form data from waterQualityRaw.json into arrays of objects per-site location dataOut = {} for row in d...
blayne/atxgreenatlas
public/data/airQualityParser.py
airQualityParser.py
py
1,570
python
en
code
0
github-code
13
17733262827
'''pmf.py: probabilistic matrix factorization using variational inference Model: U: user vectors of rank n, Ixn V: item vectors of rank n, Jxn M: Ratings matrix, IxJ m_ij = rating for item j given by user i. Likelihood: P(m_ij | u_i, v_j) = N((u_i)^T v_j, tau^2) Priors: P(u_i) = prod_l=1^n N(u_il, diag(nu_il^2)...
saurabhmathur96/variational-collaborative-filtering
pmf.py
pmf.py
py
3,398
python
en
code
0
github-code
13
37951534158
# Input files import AthenaPoolCnvSvc.ReadAthenaPool ServiceMgr.EventSelector.InputCollections = ["aod.pool.root"] # Number of events to be processed (default is 10) theApp.EvtMax = -1 ToolSvc = Service('ToolSvc') # Select Vertex or Track Algorithms useVertex = True # Do Histogramming doHists = False if us...
rushioda/PIXELVALID_athena
athena/InnerDetector/InDetCalibAlgs/InDetBeamSpotFinder/share/InDetBeamSpotFinder_jobOptions.py
InDetBeamSpotFinder_jobOptions.py
py
2,856
python
en
code
1
github-code
13
21871943494
import RPi.GPIO as GPIO import time leds = [24] GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(leds, GPIO.OUT) p = GPIO.PWM(24, 120) for n in range(10): for i in range(100): p.start(i) time.sleep(0.003) p.stop() for i in range(100): p.start(100 - i) time.s...
mershavka/get
examples/4-3-dac-pwm.py
4-3-dac-pwm.py
py
364
python
en
code
0
github-code
13
71130597139
import numpy as np x = np.array([[3,3],[4,3],[1,1]]) x_0 = np.array([[3,4,1],[3,3,1]]) y = np.array([1,1,-1]) N,M = x.shape w = np.ones(M) b = 0.0 import sympy as sp w1,w2,B,lam1,lam2,lam3 = sp.symbols('w1 w2 B lam1 lam2 lam3') f = (w1**2+w2**2)/2 st1 = 1 - (3*w1 + 3*w2 + B) st2 = 1 - (4*w1 + 3*w2 + B) st3 = 1 - (...
patricklan2/test
SVM/SVM2.py
SVM2.py
py
1,216
python
en
code
0
github-code
13
1029823680
# Program to check if a sentence is Pangram or not. """ A pangram is a sentence where every letter of the English alphabet appears at least once. Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise. """ class Solution(object): def checkIfPan...
kumarvaibhav2003/LeetCodeProblems
pangram_check.py
pangram_check.py
py
897
python
en
code
0
github-code
13
27014271335
# Sample Gunicorn configuration file. import multiprocessing # # Server socket # bind = "127.0.0.1:8018" # bind = 'unix:/tmp/gunicorn.api-nethub.sock' backlog = 2048 # # Worker processes # workers = multiprocessing.cpu_count() * 2 + 1 worker_class = 'gevent' timeout = 120 keepalive = 2 # # Debugging # debug = True s...
arleincho/publish
facenew/gunicorn.py
gunicorn.py
py
758
python
en
code
0
github-code
13
3721174060
''' A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. sk ==...
JaeEon-Ryu/Coding_test
LeetCode/0127_ Word Ladder.py
0127_ Word Ladder.py
py
2,324
python
en
code
1
github-code
13
73693523217
# -*- coding: utf-8 -*- ''' Escreva a sua solução aqui Code your solution here Escriba su solución aquí ''' func_num = int(input()) horas_trab = int(input()) valor_hora = float(input()) salario = horas_trab * valor_hora print(f"NUMBER = {func_num}") print(f"SALARY = U$ {salario:.2f}")
AkiraTorres/beecrowd
Respostas/Python/1008.py
1008.py
py
293
python
pt
code
3
github-code
13
29718420631
import numpy as np import cv2 img = cv2.imread('watch.jpg',cv2.IMREAD_COLOR)# read #cv2.line(img,(0,0),(200,300),(255,255,255),50) #line cv2.rectangle(img,(500,250),(1000,500),(0,0,255),15) # rectangle font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img,'YOLO',(-100,100), font, 6, (200,255,155), 13, cv2.LINE_AA) cv2.i...
aman15012/stuffPrecog
opencv/code3.py
code3.py
py
377
python
en
code
0
github-code
13
18994412933
import disnake from disnake.ext import commands from utils import database, checks class CloseSession(commands.Cog): def __init__(self, bot: disnake.ext.commands.Bot): self.bot = bot @commands.slash_command( guild_only=True, name="закрыть-активную-сессию", description="Закрыть...
Komo4ekoI/DiscordCasinoBot
cogs/commands/close_session.py
close_session.py
py
1,812
python
ru
code
0
github-code
13
10569109750
n = int(input()) numbers = list(map(int,input().split())) dp = [0 for _ in range(n)] dp[0] = numbers[0] maxx = dp[0] # dp[n] = n + dp[n-1] for i in range(1,n): if dp[i-1] < 0: dp[i] = max(dp[i-1], numbers[i]) elif dp[i-1] + numbers[i] > 0 : dp[i] = numbers[i] + dp[i-1] if maxx < dp[i]: ...
sossont/Pycharmpractice
Baekjoon Online Judge/다이나믹 프로그래밍/1912 연속합.py
1912 연속합.py
py
349
python
en
code
1
github-code
13
35448583315
records = ["Enter uid1234 Muzi", "Enter uid4567 Prodo","Leave uid1234","Enter uid1234 Prodo","Change uid4567 Ryan"] def solution(records): answer = [] dic = dict() l = [] for record in records: split = record.split() verb, uid = split[0], split[1] if verb == 'Enter': ...
xjayleex/problem_solving
programmers/오픈채팅방.py
오픈채팅방.py
py
882
python
en
code
0
github-code
13
17403751467
import time import datetime as dt from pytz import timezone from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options import dbAdapter da = dbAdapter.adapter() videoData = { 'id': '', 'title': '', 'description': '', 'videoThumbnail': '', 'in...
tohlh/Summer2021-Homework-2-Scraper
videoPage.py
videoPage.py
py
4,166
python
en
code
0
github-code
13
33020320416
BASE_TEMP_ADR = 5 PUSH_CMD = "push" POP_CMD = "pop" POSSIBLE_COMMANDS = [PUSH_CMD, POP_CMD] SOLID_MEMORY_segmentS = {"local": "LCL", "argument": "ARG", "this": "THIS", "that": "THAT"} VIRTUAL_MEMORY_segmentS = ["constant", "static", "poi...
damebrown/NAND_ex8
memory_parser.py
memory_parser.py
py
2,651
python
en
code
0
github-code
13
27977355893
"""Demo app using SQLAlchemy.""" from flask_debugtoolbar import DebugToolbarExtension from flask import Flask, request, redirect, render_template from models import db, connect_db, Pet app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///pet_shop_db' app.config['SQLALCHEMY_TRACK_MODIFI...
petitepirate/sqlAlchemyFundamentals
petsDemo/app.py
app.py
py
1,413
python
en
code
0
github-code
13
17062296314
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class ZhimaMerchantOrderCreditCreateModel(object): def __init__(self): self._amount = None self._category = None self._channel = None self._deposit = None self._...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/ZhimaMerchantOrderCreditCreateModel.py
ZhimaMerchantOrderCreditCreateModel.py
py
5,343
python
en
code
241
github-code
13
38131554534
import numpy as np adjacencymatrix=np.loadtxt("3adjacencymatrix.dat") clustersperframe=np.zeros((len(adjacencymatrix),60)) Nmono=60 for ts in range(len(adjacencymatrix)): nclu = 0 clu=np.zeros(60,dtype=int) todo=np.zeros(60,dtype=int) for i in range(60): if clu[i] == 0: nclu+=1 ...
mccullaghlab/FFInitialAggregationOrdering
MakeTreeOfDimerClusters.py
MakeTreeOfDimerClusters.py
py
1,388
python
en
code
0
github-code
13
43348328023
class Solution: def getRow(self, rowIndex: int) -> List[int]: answer = [0 for _ in range(rowIndex+1)] answer[0] = 1 for i in range(1, rowIndex+1): tmp_answer = [0 for _ in range(i+1)] for j in range(i): tmp_answer[j] ...
W00SUNGLEE/leetcode
119-pascals-triangle-ii/119-pascals-triangle-ii.py
119-pascals-triangle-ii.py
py
474
python
en
code
0
github-code
13
73996341138
from imutils import paths from sklearn.cluster import DBSCAN from imutils import build_montages import face_recognition import numpy as np import argparse import pickle import cv2 import os img_path='all' enc_path='./pkl/dsface.pkl' def face_cfg(): if os.path.exists(enc_path): data = pickle.loads(open(en...
hry8310/ai
ml/same_face/dsc_face.py
dsc_face.py
py
2,008
python
en
code
2
github-code
13
26621894489
import pandas as pd import numpy as np import re import os import sys import transformers from transformers import AutoTokenizer, AutoModelForSequenceClassification from transformers import RobertaTokenizer, RobertaForSequenceClassification import torch import torch.nn.functional as F from torch.utils.data import Datas...
hyomin14/Classifying-false-alarm
app.py
app.py
py
7,486
python
en
code
0
github-code
13
19121052760
import torch from torch import nn from torch.nn import functional as F class PositionWiseFeedForward(nn.Module): ''' Position-wise feed forward layer ''' def __init__(self, config) -> None: super(PositionWiseFeedForward, self).__init__() d_model = config.D_MODEL d_ff = config....
hieunghia-pat/OpenViVQA
models/modules/positionwise_feed_forward.py
positionwise_feed_forward.py
py
796
python
en
code
8
github-code
13
17057561914
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class OutputInvoiceRedApplyVO(object): def __init__(self): self._blue_invoice_code = None self._blue_invoice_no = None self._invoice_material = None self._invoice_type =...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/OutputInvoiceRedApplyVO.py
OutputInvoiceRedApplyVO.py
py
5,360
python
en
code
241
github-code
13
21831128126
# python debug import pdb def doubleval(argsum, val): argsum = 0 newval = argsum + val return newval pdb.set_trace() # break point values = [1,2,3,4,5] mysum = 0 for val in values: mysum = 0 mysum = doubleval(mysum, val) print(mysum) # c or continue to go to next step of loop ...
cepheus87/pythonStuff
pdbExample.py
pdbExample.py
py
527
python
en
code
0
github-code
13
40289098625
# 1.Write a program to loop through a list of numbers and add +2 to every value to elements in list list = [2,3,5,6,9,6,10] New_list = [x + 2 for x in list] print(New_list) # 2.Write a program to get the below pattern rows = int(input("Enter the number of rows: ")) for i in range(0, rows + 1): # inne...
abhishekkumar116/python-internship-code-expreance
Day9_solution.py
Day9_solution.py
py
2,834
python
en
code
0
github-code
13
12703191666
import argparse import warnings import cv2 import torch from matplotlib import pyplot as plt from tqdm import tqdm from detector import ( distance_calculation, height_calculation, input_handling, output_creation, pose_estimation, synchrony_detection, visualization, ) from models.with_mobil...
StrgFJojo/diid2
main.py
main.py
py
5,425
python
en
code
0
github-code
13
383217623
from __future__ import absolute_import, unicode_literals import logging import os from abc import ABCMeta from six import add_metaclass from virtualenv.info import fs_supports_symlink from virtualenv.util.path import Path from virtualenv.util.zipapp import ensure_file_on_disk from ..creator import Creator, CreatorM...
alexnathanson/solar-protocol
backend/createHTML/venv-bk/lib/python3.7/site-packages/virtualenv/create/via_global_ref/api.py
api.py
py
3,500
python
en
code
207
github-code
13
25902876216
import os from datetime import datetime from web2qgis.tinycss.color3 import parse_color_string from PyQt5.QtCore import QDir def getTempDir(): tempDir = os.path.join( unicode(QDir.tempPath()), 'web2qgis', datetime.now().strftime("%Y_%m_%d-%H_%M_%S_%f")) if not QDir(tempDir).exists(): ...
tomchadwin/web2qgis
utils.py
utils.py
py
815
python
en
code
15
github-code
13
20645607564
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function, division from collections import Counter from tqdm import tqdm from sentencepiece import SentencePieceTrainer import dill import sentencepiece as sp # ================================================== class Sen...
seujung/electra_pytorch_kr
tokenizer.py
tokenizer.py
py
6,073
python
en
code
1
github-code
13
19623020290
# -*- coding: utf-8 -*- class elevator: def processData(self, fileName): count = 0 fp = open(fileName, 'r') lines = fp.readlines() if len(lines) > 2: maxCil = int(lines[0]) curCil = int(lines[1]) entries = [] for line in lines[2:]: ...
streeg/pseudo-os
inout/elevator.py
elevator.py
py
796
python
en
code
0
github-code
13
36492502562
import threading from homealone import * # import whichever gpio library is installed try: import RPi.GPIO as gpio gpioLibrary = "RPi.GPIO" except ImportError: import RPIO as gpio gpioLibrary = "RPIO" # dictionary of MCP23017Interfaces indexed by their interrupt pins gpioInterfaces = {} # initial inte...
jbuehl/homealone
homealone/interfaces/mcp23017Interface.py
mcp23017Interface.py
py
7,639
python
en
code
0
github-code
13
74607400976
# Smoothing tool for solar neutrino spectra # Davide Basilico - Dec 2020 - davide.basilico@mi.infn.it import plotly.graph_objects as go import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy import matplotlib.pylab as pylab from scipy import signal from scipy import interpolate from scipy ...
davidebas/SmoothingPDFs
SmoothingTool.py
SmoothingTool.py
py
8,266
python
en
code
0
github-code
13
73078923539
from grabscreen import grab_screen from cs_model import load_model import cv2 import win32gui import win32con import torch import numpy as np from utils.general import non_max_suppression, scale_coords, xyxy2xywh from utils.augmentations import letterbox import pynput from mouse_control import lock, recoil_co...
MacroXie/CSGO-Copilot
aim-csgo/main.py
main.py
py
6,050
python
en
code
1
github-code
13
72915524498
import io import struct import pytest import hypothesis from hypothesis import strategies as hst from qutebrowser.misc import elf from qutebrowser.utils import utils @pytest.mark.parametrize('fmt, expected', [ (elf.Ident._FORMAT, 0x10), (elf.Header._FORMATS[elf.Bitness.x64], 0x30), (elf.Header._FORMATS...
qutebrowser/qutebrowser
tests/unit/misc/test_elf.py
test_elf.py
py
4,115
python
en
code
9,084
github-code
13
39976980609
# -*- coding: utf-8 -*- CURRENT_STAGE = { "no":29, "date":"2014/5/7 - 5/26", "manager":u"鄭安琪"} APP_URL="http://ntulifeguardapp.appspot.com/" APP_ADMIN_EMAIL="ntulifeguard@gmail.com" APP_LOGIN_MAX_RETRY=3 APP_NOTICE_EMAIL="ntulifeguardreg@groups.facebook.com" APP_EMAIL_GREETING=u"[ntulifeguard] ...
timchen86/ntulifeguardapp
ntulifeguardapp/globals.py
globals.py
py
603
python
en
code
0
github-code
13
71139097619
import argparse import math import random import os from types import GeneratorType import numpy as np import torch from torch import nn, autograd, optim from torch.nn import functional as F from torch.utils import data import torchvision from tqdm import tqdm import pdb import wandb import sys sys.path.append("../")...
klory/MPG2
sefa_new/train_cs.py
train_cs.py
py
26,949
python
en
code
5
github-code
13
7178569110
""" Code for day 4 of the 2021 Advent of Code challenge :) """ # SYSTEM IMPORTS # THIRD PARTY IMPORTS # LOCAL APPLICATION IMPORTS def read_input(): # Read input file input_data = open("day_04_input", "r") cleaned_input = [] for item in input_data: line = item.split("\n")[0] if line...
CatAndDogSoup/AdventOfCode_2021
day_04.py
day_04.py
py
730
python
en
code
1
github-code
13
33021737942
from abc import ABC, abstractmethod import pytube import os from os import path from config import DOWNLOAD_PATH from utils.logging.logger import logger import json class VideoDownloadBase(ABC): @abstractmethod def download(self, href, config): pass class VideoDownload(VideoDownloadBase): def...
timothyxp/Text2VideoServer
utils/video_download.py
video_download.py
py
2,538
python
en
code
1
github-code
13
25579204842
""" Converting DIMACS to Z3 expr """ from typing import List import z3 def int_clauses_to_z3(clauses: List[List[int]]) -> z3.BoolRef: """ The int_clauses_to_z3 function takes a list of clauses, where each clause is a list of integers. The function returns the conjunction (AND) of all clauses in the input...
ZJU-Automated-Reasoning-Group/arlib
arlib/translator/intclauses2z3.py
intclauses2z3.py
py
893
python
en
code
6
github-code
13
43850061252
# -*- coding: utf-8 -*- import os import django # Scrapy settings for scraper project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'scraper' SPIDER_MODULES ...
dillonko/jobboardscraper
jobboardscraper/scraper/settings.py
settings.py
py
1,073
python
en
code
1
github-code
13
26934741384
from setuptools import setup, find_packages from codecs import open from os import path from pyway.version import __version__ here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() #...
sergiosbx/pyway
setup.py
setup.py
py
1,400
python
en
code
null
github-code
13
865050232
def encrypt(message: str, rails: int) -> str: """ Encrypts a message using the Rail Fence Cipher with the specified number of rails. Args: message (str): The message to encrypt. rails (int): The number of rails to use. Returns: str: The encrypted message. Raises: V...
eshabaweja/classicciphers
classicciphers/railfence.py
railfence.py
py
1,862
python
en
code
0
github-code
13
8417704054
''' 上传头像 将一个图片从客户端发送给服务端 思路:客户端 读取头像图片内容 --》通过网络发送给服务端 服务端 先从网络中接收内容--》写入到服务端的文件 ''' from socket import * import time ADDR = ('127.0.0.1', 8888) # 创建套接字 s = socket() # 发起连接 s.connect(ADDR) # 发送文件 f=open('TCP.png','rb') while True: data=f.read(1024) if not data: time.sleep(1) s.send('文件发送完...
FAREWELLblue/AID1912_personal
day05/send_file.py
send_file.py
py
554
python
zh
code
0
github-code
13
36783910266
from pyramid.config import Configurator from pyramid.session import SignedCookieSessionFactory def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ my_session_factory = SignedCookieSessionFactory('itsaseekreet') config = Configurator(settings=settings, session...
ontiyonke/scrape_wikipedia
scrape_wikipedia/__init__.py
__init__.py
py
621
python
en
code
0
github-code
13
42705253850
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns get_ipython().run_line_magic('matplotlib', 'inline') # In[2]: train=pd.read_csv('train_IQ.csv') test=pd.read_csv('test_IQ.csv') # In[3]: print(test.shape) print(train.sh...
sskatti/Income-Qualification
Income Qualification Project.py
Income Qualification Project.py
py
11,503
python
en
code
0
github-code
13
42051957648
import sys sys.setrecursionlimit(10 ** 8) ini = lambda: int(sys.stdin.readline()) inm = lambda: map(int, sys.stdin.readline().split()) inl = lambda: list(inm()) ins = lambda: sys.stdin.readline().rstrip() debug = lambda *a, **kw: print("\033[33m", *a, "\033[0m", **dict(file=sys.stderr, **kw)) N = ini() def solve():...
keijak/comp-pub
atcoder/abc173/F/main.py
main.py
py
569
python
en
code
0
github-code
13
30113998690
import os import sys import io import zipfile import math as Math CWD = os.path.dirname(__file__) sys.path.append(CWD) from get_config import SCRIPT_FILE import parse_lua as PL def get_tunings(): with zipfile.ZipFile(SCRIPT_FILE) as zip: content = zip.read("scripts/tuning.lua") fp = io.StringIO(conte...
NullOnSpace/dst-qq
utils/dst/manage_server/parse_tunings.py
parse_tunings.py
py
1,879
python
en
code
0
github-code
13
39789223802
import torch from functools import lru_cache from unicore.data import BaseWrapperDataset class PrependAndAppend2DDataset(BaseWrapperDataset): def __init__(self, dataset, token=None): super().__init__(dataset) self.token = token @lru_cache(maxsize=16) def __getitem__(self, idx): it...
dptech-corp/Uni-Mol
unimol/unimol/data/prepend_and_append_2d_dataset.py
prepend_and_append_2d_dataset.py
py
590
python
en
code
453
github-code
13
31234364859
def homework_1(nums): # 請同學記得把檔案名稱改成自己的學號(ex.1104813.py) length = len(nums)#計算長度 count = 0#累計個數 ans=0#最大連續次數 for i in range(1,length): if nums[i-1] != nums[i]: n=i-count count +=n if n >ans: ans = n last = length-count if last>ans: ...
daniel880423/Member_System
file/hw1/1100342/s1100342_1.py
s1100342_1.py
py
522
python
en
code
0
github-code
13
4742946263
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Function to load data from CKAN object classes. ''' import app.utilities.load as Load from app.classes.user import User from app.classes.country import Country from app.classes.dataset import Dataset from app.classes.revision import Revision from app.classes.resource impo...
luiscape/hdx-monitor-sql-collect
app/functions/fetch_class_data.py
fetch_class_data.py
py
1,269
python
en
code
0
github-code
13
42834416786
from bisect import bisect, insort from ..cores import ICore from ..util import coerce_to_uri _IMPL_REG_KEYS = [] _IMPL_REGISTRY = {} def register_implementation(uri_prefix): """Registers a subclass of :class:`.interface.ICore`. This is to be used as a decorator generator, as in:: @register_impleme...
ktbs/ktbs
lib/rdfrest/cores/factory.py
factory.py
py
3,781
python
en
code
24
github-code
13
26010444038
"""Account DTO""""" from src.dtos.transactions_dto import TransactionDTO class AccountDTO: """Account Data Transfer Object class""" def __init__(self, name: str, account_id: int, account_uuid: str, balance: int, currency: str, transactions: list[TransactionDTO]): self.name = name self.account_...
razvanmarinn/expense-tracker
src/dtos/accounts_dto.py
accounts_dto.py
py
884
python
en
code
0
github-code
13
72929070417
#! /usr/bin/env python2 import numpy as np from scipy import interpolate import cv2 import sys,os import time # Local imports import parameters as defaults cpath = os.path.split(os.path.abspath(__file__))[0] print(cpath) sys.path.append(cpath) from utils import pcautils from utils.cprint import cprint libviso_a...
jswulff/pcaflow
pcaflow/PCAFlow.py
PCAFlow.py
py
14,213
python
en
code
83
github-code
13
36308673254
import math # For a = 2.3, find the ceil of a a = 2.3 ceil_result = math.ceil(a) print(f"The ceil of {a} is: {ceil_result}") # For a = 2.3, find the floor of a floor_result = math.floor(a) print(f"The floor of {a} is: {floor_result}") # For a = 5, find the factorial of a b = 5 factorial_result = math.factorial(b) pr...
debsicat22/AdvanceProgramming
Assessment1/Chapter 6/Exercise1.py
Exercise1.py
py
633
python
en
code
0
github-code
13
9521303457
from __future__ import absolute_import from django.test import override_settings from rest_framework import status from rest_framework.reverse import reverse from rest_framework.test import APITestCase from silver.fixtures.factories import AdminUserFactory from silver.fixtures.test_fixtures import PAYMENT_PROCESSORS...
silverapp/silver
silver/tests/api/test_payment_processors.py
test_payment_processors.py
py
2,326
python
en
code
292
github-code
13
72033244178
from __future__ import annotations from typing import TYPE_CHECKING, List from ..ns import * from .SpatialObject import SpatialObject if TYPE_CHECKING: from rdflib import Graph, Literal from ..Thing import Thing from .GeometryType import GeometryType class Geometry(SpatialObject): __type__ = CLV["...
luca-martinelli-09/ontopia-py
ontopia_py/clv/Geometry.py
Geometry.py
py
1,559
python
en
code
0
github-code
13
29977147523
import torch from torchvision import transforms as T from torchvision.transforms import functional as F import cv2 as cv import numpy as np def box_cxcywh_to_xyxy(x): x_c, y_c, w, h = x.unbind(1) b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)] return torch....
OneMagicKey/TwoStageSegmentation
utilities/bbox_generators.py
bbox_generators.py
py
2,882
python
en
code
0
github-code
13
28561661642
# -*- coding: utf-8 -*- import sys import threading import functools import contextlib import click from ._compat import reraise try: import queue except ImportError: import Queue as queue # The docs state that "Future should not be instantiated directly, only by # Executors", but since I'm basically implem...
ag1455/OpenPLi-PC
pre/python/lib/python2.7/dist-packages/click_threading/__init__.py
__init__.py
py
4,625
python
en
code
19
github-code
13
20215645929
import os import argparse import os.path as osp import pickle import sys import numpy as np from tqdm import tqdm from opt import opt from PIL import Image import cv2 import torch from torch.autograd import Variable import torch.nn.functional as F import torchvision.transforms as transforms import torch.nn as nn import...
linye-boli/boli-tracking-0.0.1
tracking_pj/tracking-multi-thread/main.py
main.py
py
9,543
python
en
code
0
github-code
13
5419166620
from shiny import * from pathlib import Path from test import treatment_file, data_separation, data_split, LR, evaluate_linear_regression, train_and_evaluate_random_forest, plot_linear_regression_results, create_shap_waterfall_chart, shap_beeswarm_plot, shap_violin_plot, Split_and_Shap,create_and_display_graph_test, Jo...
karlcise222/Cancer_Care_Dashboard
app.py
app.py
py
14,598
python
en
code
0
github-code
13
74638119376
n = int(input()) arr = [] # 문장 입력 for i in range(n): arr.append(input()) # 문장 개수만큼 반복 for i in range(len(arr)): # 현재 위치, x,y 저장 배열, 방향 초기화 cur=[0,0] x,y =[0],[0] move = [0,1] # 문장길이만큼 반복 for j in range(len(arr[i])): #이동 거리 초기화 distance = 0 # 90도 이동 if arr[i][j]=='R': move[0],mov...
Coding-Test-Study-Group/Coding-Test-Study
yunhwan/백준 8911 거북이.py
백준 8911 거북이.py
py
967
python
ko
code
4
github-code
13
16426891221
""" @author Mrinal Pandey @date: 2nd April, 2019 @day_time Tuesday 22:31 """ def displayData(a, n): #Loop to print data for i in range(n): print (a[i], end = '\t') print() #To change line #Sub-routine to sort elements in the array using Selection Sort def selectionSort(a, n): #Outer loop ...
primyt/SelectionSort
SelectionSort.py
SelectionSort.py
py
1,020
python
en
code
0
github-code
13
15220681772
import random import discord from discord.ext import commands class Speech(commands.Cog): """Speech Cog""" def __init__(self, client): # sets client variable so it can be used in cog self.client = client self._last_member = None @commands.command() async def hello(self, ctx,...
solorzao/wolf-pack-bot
cogs/speech.py
speech.py
py
3,158
python
en
code
0
github-code
13
2686500447
"""Trains a simple deep NN on the MNIST dataset. Gets to 98.40% test accuracy after 20 epochs (there is *a lot* of margin for parameter tuning). 2 seconds per epoch on a K520 GPU. """ from keras import Sequential from keras.datasets import mnist from keras.layers import Dense, Dropout from keras.optimizers import RMSp...
mcai/Tidbits.Foresight
predictor_mlp.py
predictor_mlp.py
py
1,788
python
en
code
0
github-code
13
20691864807
#!/usr/bin/python3.6 import os, sys, time, datetime, subprocess import shutil import yaml AB_PATH = os.path.abspath(__file__) CUR_DIR = os.getcwd() timestr = time.strftime("%Y%m%d-%H%M%S") now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') def load_yaml_list(target_yaml='vid_config.yaml', the_key='vid...
maxnotmin/uotuw
dl.py
dl.py
py
2,571
python
en
code
0
github-code
13
32466199242
import PythonNmap as nmap import json import datetime import time import utils def callback_print_and_record(host, ports, scan_data, output_file): print("--------------------") print(host) print(ports) print(scan_data) if output_file: with open(output_file, "a") as file: ...
FlyTweety/ExtendNmapMetasploit
AsyncNmap.py
AsyncNmap.py
py
3,627
python
en
code
0
github-code
13
71471438417
import numpy as np import onnx from onnx.backend.test.case.base import Base from onnx.backend.test.case.node import expect class StringConcat(Base): @staticmethod def export() -> None: node = onnx.helper.make_node( "StringConcat", inputs=["x", "y"], outputs=["resul...
onnx/onnx
onnx/backend/test/case/node/string_concat.py
string_concat.py
py
1,862
python
en
code
15,924
github-code
13
3532010382
import matplotlib.pyplot as plt import numpy as np import math def show_histogram(data, bins=100, title=None, x_axis_label=None, y_axis_label=None): """ Show the histogram of the data :param data: data with ND-array :param bins: num of bins in the histogram :param title: figure title :param x_a...
sfu-gruvi-3dv/sanet_relocal_demo
visualizer/visualizer_2d.py
visualizer_2d.py
py
2,683
python
en
code
51
github-code
13
10687571889
import random import copy POPULATION_SIZE = 100 TOPK= 10 QUEENS = int(input("Enter The Number Of Queens: ")) gen = 1 def InitialPopulation(PoP): for i in range(POPULATION_SIZE): temp = [] for i in range(QUEENS): temp.append(random.randint(1,QUEENS)) PoP.append(temp) return ...
vineetjoshi253/CSE-643-Artificial-Intelligence
Assignment-1/N-Queen/GeneticN.py
GeneticN.py
py
3,607
python
en
code
1
github-code
13
13614130570
class Solution(object): # solution1, need O(n) extra space and O(nlog n) running time def wiggleSort(self, nums): temp = sorted(nums) mid = (len(temp) + 1) / 2 k = 0 for i in reversed(xrange(mid)): nums[k] = temp[i] k += 2 j = 1 ...
clovery410/mycode
leetcode_review2/324wiggle_sort2.py
324wiggle_sort2.py
py
502
python
en
code
1
github-code
13
32417951408
import numpy as np import seaborn as sn import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.patches as mpatches from matplotlib.dates import DateFormatter import datetime def plot_test_train_splits(train, test): """ Plots test train splits...
rymc/bHealth
bhealth/visualisations.py
visualisations.py
py
21,861
python
en
code
2
github-code
13
585556547
from pyowm import OWM from pyowm.utils import config from pyowm.utils import timestamps owm = OWM('4f1d4d06b8d0c706cbd6971dfd330188') mgr = owm.weather_manager() from pyowm.utils.config import get_default_config config_dict = get_default_config() config_dict['language'] = 'ru' place = input("Введи город "...
TheSnow1/pogoda
mmm.py
mmm.py
py
1,161
python
ru
code
0
github-code
13
24044234166
# 在运行前或运行后替换 # 如果想在父类中定义的内容运行之前或者之后再修改行为. # 可以覆盖函数,再接着用super来调用父类的版本 class Parent(object): def altered(self): print("PARENT altered()") class Child(Parent): def altered(self): print("CHILD, BEFORE PARENT altered()") super(Child, self).altered() print("CHILD, AFTER PARENT alte...
NullPointerC/Learn-Python-The-Hard-Way-Source-Code
ex44c.py
ex44c.py
py
494
python
zh
code
0
github-code
13
12522775863
from enum import Enum import pandas as pd import tkinter as tk from tkinter import ttk from matplotlib.backends.backend_tkagg import ( FigureCanvasTkAgg, NavigationToolbar2Tk) from matplotlib.figure import Figure import matplotlib.pyplot as plt from matplotlib import gridspec from dataclasses import dataclass fro...
David-Durst/csknow
learn_bot/learn_bot/recoil/vis.py
vis.py
py
14,690
python
en
code
13
github-code
13
40177493213
import turtle as t import random def turn_up(): #위에 키 눌렀을 때 호출되는 함수 t.left(2) #거북이를 왼쪽으로 2도 돌림 def turn_down(): #아래 키 눌렀을 때 호출되는 함수 t.right(2) #거북이를 오른쪽으로 2도 돌림 def fire(): #스페이스바 눌렀을 때 호출되는 함수 ang = t.heading() #현재 거북이가 바라보는 각도를 기억 while t.ycor() > 0: #거북이가 땅 위에 있는 동안 반복 t.forward(15...
mongsil0219/2023.01.18
16A_cannon.py
16A_cannon.py
py
1,825
python
ko
code
0
github-code
13
31740649655
import numpy as np from machinelearn.linear_model_03.closed_form_sol.LinearRegression_CFSol import LinearRegressionClosedFormSol from machinelearn.model_evaluation_selection_02.Polynomial_feature import PolynomialFeatureData import matplotlib.pyplot as plt def objective_fun(x): # return 0.5 * x ** 2 + x + 2 r...
lixixi89055465/py_stu
machinelearn/model_evaluation_selection_02/learning_curve/test_polynomial_fit.py
test_polynomial_fit.py
py
2,643
python
en
code
1
github-code
13
12210404993
import os import urllib from google.appengine.api import users from google.appengine.ext import ndb import jinja2 from bottle import Bottle, request, redirect, debug debug(True) bottle = Bottle() JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['...
Durell/appengine
bottle_guestbook/guestbook.py
guestbook.py
py
2,529
python
en
code
0
github-code
13
2005403290
import nibabel as nib import glob as glob import numpy as np from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import os from keras.models import * from keras.layers import * from keras.optimizers import * from keras.callbacks import ModelChe...
rutugandhi/MDA-Net
Sagittal/Proposed/mda_net_144.py
mda_net_144.py
py
26,277
python
en
code
0
github-code
13
9556335324
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: s=sum(nums[:k]) ans=s/k j=k i=0 while(j<len(nums)): s+=(nums[j]-nums[i]) ans=(max(ans,s/k)) i+=1 j+=1 return ans
eyoaab/Solution-_pack
maxAverage.py
maxAverage.py
py
303
python
en
code
0
github-code
13
35644404655
import pandas as pd from sqli_detect import getFeatures import time import pickle if __name__ == '__main__': while 1: payload = input("please input your url:") print('start process data') start = time.time() result = pd.DataFrame(columns=('sql','length','key_num','capital_f','num_f'...
scusec/Data-Mining-for-Cybersecurity
Homework/2019/Task5/12/code/predict_sql.py
predict_sql.py
py
868
python
en
code
66
github-code
13
72337985619
"""Adversarial attack class """ import os import torch class Attack(object): """Base class for attacks Arguments: object {[type]} -- [description] """ def __init__(self, attack_type, model): self.attack_name = attack_type self.model = model.eval() self.device = next(mod...
lepoeme20/Adversarial-Detection
attacks.py
attacks.py
py
2,230
python
en
code
0
github-code
13
74218108176
def is_matrix_rectangular(matrix): return all(len(row) == len(matrix[0]) for row in matrix) def count_non_zero_columns(matrix): if not matrix: return 0 if not is_matrix_rectangular(matrix): return -1 #не прямоугольная, возвращаем -1 num_rows = len(matrix) num_cols = len(matrix[0])...
lkrvtsk/Python
Лабораторная №2/Лаб_2_задание_3.py
Лаб_2_задание_3.py
py
1,778
python
ru
code
0
github-code
13
73772401937
def anima():#Animação from random import randint import colorama from time import sleep from colorama import Fore, Back, Style colorama.init(autoreset=True) lista = [Fore.RED, Fore.YELLOW, Fore.BLUE, Fore.MAGENTA, Fore.GREEN, Fore.CYAN, Fore.WHITE, Fore.LIGHTRED_EX] nome = ["L", "u", "c...
Firestormant/Alguns-projetos-que-eu-gostei
Animação*1000.py
Animação*1000.py
py
648
python
en
code
1
github-code
13
29245575126
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import pandas as pd import seaborn as sns from sklearn.decomposition import PCA, SparsePCA from sklearn.cluster import DBSCAN, KMeans, AgglomerativeClustering from sklearn.preprocessing import StandardScaler, MinMaxScaler from scipy.stats import po...
JohnSegerstedt/DATX02-19-81
Fredrik_Hs_mapp/Methods.py
Methods.py
py
35,432
python
en
code
4
github-code
13
23422879323
from lib.coefficients import Coefficients from utils.menu import main_menu while True: combustible = main_menu() if combustible: coefficients = Coefficients(*combustible) print(f"Mean specific heat of {coefficients.combustible.name.title()} at {coefficients.t_gh + 273.15}°C is:\n" f"...
KoteTheInnkeeper/cp_flue_gas
app.py
app.py
py
367
python
en
code
0
github-code
13
2349306340
import botsdk.util.HttpRequest import json from botsdk.BotModule.Adapter import Adapter class MiraiAdapter(Adapter): def init(self, data): self.url = data["path"] async def get(self, parameter, **kwargs): return json.loads( await botsdk.util.HttpRequest.get( (self....
f88af65a/XyzB0ts
bot/Mirai/Adapter.py
Adapter.py
py
603
python
en
code
6
github-code
13
34919425339
import pandas as pd import scipy.sparse as sp import os def create_URM_matrix(ratings_df): URM_all = sp.csr_matrix((ratings_df["data"].values, (ratings_df["user_id"].values, ratings_df["item_id"].values))) return URM_all def create_ICM_matrix(dataframe): csr_matrix = sp.csr...
redaellimattia/RecSys-Competition-2022-Polimi
utils/data_util.py
data_util.py
py
4,702
python
en
code
0
github-code
13
43142128576
# -*- coding: utf-8 -*- ################################################################################################# import logging import sqlite3 import sys import traceback import xbmc import xbmcgui import xbmcplugin import xbmcvfs from views import Playlist, VideoNodes from utils import wind...
CaoZ/plugin.video.emby
resources/lib/database.py
database.py
py
8,342
python
en
code
0
github-code
13