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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
26038374198 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 12 14:24:45 2021
@author: Gustavo
"""
import requests
import time
import re
import ast
import numpy as np
import pandas as pd
import asyncio
import concurrent.futures
import nest_asyncio
import os.path
import random
from collections import defaultd... | gusvilalima/JungleScoutWeb | productScraper.py | productScraper.py | py | 14,137 | python | en | code | 0 | github-code | 13 |
32842083792 | import glob
import os
import shutil
import sys
import termios
import time
import tty
import uuid
from shutil import copyfile
import subprocess
import common.color
from common.color import WARNING_PREFIX, ERROR_PREFIX, FAIL, WARNING, ENDC, OKGREEN, BOLD, OKBLUE, INFO_PREFIX, OKGREEN
from common.debug import logger
__a... | nyx-fuzz/packer | packer/common/util.py | util.py | py | 5,308 | python | en | code | 15 | github-code | 13 |
71163200019 | from tests.TestCode import *
from Contracts.Contract import *
from hypothesis import given
from hypothesis.strategies import booleans
from pytest import raises
from Contracts.ContractLevel import OFF
def test_debugLevel():
assert QQQ(10,5) == 20
assert T(2, 5, 2) == 10
t = TTT(0)
empty(29)
def tes... | Fracture17/contracts | tests/test_ing.py | test_ing.py | py | 1,638 | python | en | code | 0 | github-code | 13 |
39131354811 | import socket
from urllib.parse import urlparse
from 装饰器.无参装饰器 import outer
@outer
def get_url(url):
# 解析url
url = urlparse(url)
# 获得主域名
host = url.netloc
# 获得子路经
path = url.path
if path == '':
path = '/'
# 建立socket连接
client = socket.socket(socket.AF_INET, socket.SOCK_STREA... | dsdcyy/python- | python进阶/网络编程/03socket模拟http请求.py | 03socket模拟http请求.py | py | 854 | python | en | code | 0 | github-code | 13 |
16056951661 | from sys import stderr, exit, argv
import numpy as np
from scipy.io import loadmat
import os
from os.path import isfile, isdir, realpath, dirname, exists
def preprocessStringerNeuropixelsData(data_path, output_path):
# Only accept neurons with at least 40 minutes recording length
minRecLength = 2400.
rawD... | Priesemann-Group/historydependence | exe/preprocess_data.py | preprocess_data.py | py | 9,605 | python | en | code | 2 | github-code | 13 |
73585505617 | from tkinter import *
from typing import Match
from decimal import *
root = Tk()
root.title("Simple Calculator")
root.iconbitmap('.../Calc/favicon.ico')
e = Entry(root, width=40, borderwidth=5)
e.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
e.insert(0, "0")
def button_click(number):
current = e.get()
... | amacher/calculator | calculator.py | calculator.py | py | 5,059 | python | en | code | 0 | github-code | 13 |
29343884049 | '''
Numa eleição existem três candidatos. Faça um programa que peça o número total de eleitores.
Peça para cada eleitor votar e ao final mostrar o número de votos de cada candidato.
'''
total_eleitores = int(input('Numero de eleitores: '))
canditato_A = []
canditato_B = []
canditato_C = []
for i in range(total_eleit... | paulocesarcsdev/ExerciciosPython | 3-EstruturaDeRepeticao/26.py | 26.py | py | 756 | python | pt | code | 0 | github-code | 13 |
21909724545 | """
Implementations of network analyses, like contact networks or adjacency matrices.
"""
import numpy as np
from sklearn.neighbors import KDTree
from pepe.preprocess import circularMask
from pepe.analysis import gSquared
def adjacencyMatrix(centers, radii, contactPadding=5, neighborEvaluations=6):
"""
Cal... | Jfeatherstone/pepe | pepe/analysis/NetworkAnalysis.py | NetworkAnalysis.py | py | 5,046 | python | en | code | 1 | github-code | 13 |
74300184338 | import gym
import numpy as np
import random
env = gym.make("Pendulum-v0")
#env = gym.make("MountainCar-v0")
LEARNING_RATE = 0.1
DISCOUNT = 0.95
EPISODES = 24100
SHOW_EVERY = 3000
epsilon = 0.2
START_EPSILON_DECAY = 1
END_EPSILON_DECAY = 25000
epsilon_decay = epsilon/(END_EPSILON_DECAY - START_EPSILON_DECAY)
DISCR... | spacebot29/PendulumRL | GymPendulum-QLearning.py | GymPendulum-QLearning.py | py | 2,495 | python | en | code | 0 | github-code | 13 |
17046175144 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipaySecurityRiskGravityWorkflowCreateModel(object):
def __init__(self):
self._auth_feature_tables = None
self._check_sample_tables = None
self._contract_id = None
... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/AlipaySecurityRiskGravityWorkflowCreateModel.py | AlipaySecurityRiskGravityWorkflowCreateModel.py | py | 5,357 | python | en | code | 241 | github-code | 13 |
25146338026 |
# 剪裁1280x720
import os
import cv2
import numpy as np
import numpy.linalg as npl
def colorSim(c1, c2, thr):
return npl.norm(c1[:3] - c2[:3]) < thr
def isVertBlack(img, x):
for y in range(10, img.shape[0] - 10, 10):
pixel = img[y, x]
if (not colorSim(pixel, (0, 0, 0), 30)):
retur... | xdedss/cvmaj | templates/multiple/crop.py | crop.py | py | 1,358 | python | en | code | 3 | github-code | 13 |
16025338977 | from functools import lru_cache
import bson
from core.config import settings
from core.db import get_mongo_worker_client
from pymongo.collection import Collection
from pymongo.database import Database
class MongoDbManager:
def __init__(self, mongo_db: Database):
self.mongo_client: Database = mongo_db
... | montekrist0/notifications_sprint_1 | worker/src/services/db_manager.py | db_manager.py | py | 1,651 | python | en | code | 1 | github-code | 13 |
7524169549 | from django.contrib import admin
from .models import Model, User
# Register your models here.
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
list_filter = ('username',)
list_display = ('username', 'email', 'last_login')
fields = ('username',
'email',
'password',
... | opensim-org/opensim-viewer | src/backend/backend/backend/admin.py | admin.py | py | 791 | python | en | code | 7 | github-code | 13 |
44736992014 | import csv
from .helpers import Importer, fetch
def run():
url = 'https://codeforiati.org/country-codes/country_codes.csv'
lookup = [
('code', 'code'),
('name_en', 'name_en'),
('name_fr', 'name_fr'),
]
r = fetch(url)
reader = csv.DictReader(r.iter_lines(decode_unicode=True... | codeforIATI/codelist-updater | importers/country.py | country.py | py | 731 | python | en | code | 2 | github-code | 13 |
10545954145 | # from cipherart import logo
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v... | antwolfe/Python-Projects | cipher.py | cipher.py | py | 1,089 | python | en | code | 0 | github-code | 13 |
14183302100 | """
This Code Controll The Arena Arena
"""
from Parameters import *
class Arena():
def __init__(self, gridsize, screen):
"""
:param gridsize: is how big the grid (rectangel). Find setting in Parameters.py
:param screen: Which Screen i want to show the arena
"""
self.gridSi... | Verietoto/Playing-Snake-Using-Artificial_Intelligence-and-Neural_Network | Arena.py | Arena.py | py | 5,298 | python | en | code | 0 | github-code | 13 |
71645480339 | from urllib import response
import discord
from discord.ext import commands, tasks
import random
from itertools import cycle
import os
from discord import Color
from discord.utils import get
import asyncio
token = 'YOUR_API_KEY'
#sets what the bot is intended for, set to all as default
intents = discord.... | BorderDestroyer/GarrettBot | bot.py | bot.py | py | 6,668 | python | en | code | 0 | github-code | 13 |
36569422921 | # 2126 - procurando subsequencias
# algoritmo KMP
def computar_prefixo(padrao, m, prefixo):
tam = 0
prefixo[0] = 0
i = 1
while i < m:
if padrao[i] == padrao[tam]:
tam += 1
prefixo[i] = tam
i += 1
else:
if tam != 0:
t... | ltakuno/arquivos | python/URI/Basico/uri2126.py | uri2126.py | py | 1,434 | python | pt | code | 0 | github-code | 13 |
73175399378 | class StackNode():
def __init__(self, value, nxt):
self.value = value
self.next = nxt
def __repr__(self):
nval = self.next and self.next.value or None
return f'[{self.value}:{repr(nval)}]'
class Stack():
def __init__(self):
self.top = None
def push(self, obj):
... | LowTechTurtle/More_Python_THW | data_structure/ex17/ex15_stack.py | ex15_stack.py | py | 1,001 | python | en | code | 0 | github-code | 13 |
11217100976 | from django.urls import path
from . import views
urlpatterns = [
path('detail/<int:id>', views.detail_post, name="detail-post"),
path('category/<ctg_name>', views.category_post, name="category-post"),
path('search', views.search_post, name='search'),
path('create/category', views.create_category, name=... | talhajubair100/bootstrap_blog | blog/urls.py | urls.py | py | 408 | python | en | code | 0 | github-code | 13 |
74449852817 | from delegations.models import Billing, Delegation, BusinessExpenses, UsersDelegations
# def createDelegationsCompanionObjects(delegation_id):
# billing = Billing.objects.create(
# FK_delegation=Delegation.objects.get(id_delegation=delegation_id))
# BusinessExpenses.objects.create(FK_billing=Billing.o... | LeviSforza/PO-Projekt | delegations/utils.py | utils.py | py | 925 | python | en | code | 0 | github-code | 13 |
37412146119 | import re
import time
import operator
import sys
sys.path.append("../../")
import kaggle
import popular
training = "../data/train.csv"
extra = "../data/sku_names.csv"
testing = "../data/test.csv"
def train(data, ngram=1):
data = kaggle.format_words(data)
output = kaggle.word_count_hash(data, ngram)
return output
... | pmiller10/best_buy | best_buy/models/tf_idf.py | tf_idf.py | py | 5,892 | python | en | code | 0 | github-code | 13 |
2051641616 | #
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# ... | goofacz/smile-python | smile/area.py | area.py | py | 2,480 | python | en | code | 0 | github-code | 13 |
4632080505 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 6 12:13:17 2018
@author: pinaki
"""
import pandas as pd
from sklearn.preprocessing import StandardScaler
dataset=pd.read_csv("criminal_train.csv")
X = dataset.iloc[:, 2:71].values
y = dataset.iloc[:, 71].values
# Splitting the dataset into the ... | PinakiGhosh/HackerearthCompetitions | PredictTheCriminal/06-12-18_FirstTry.py | 06-12-18_FirstTry.py | py | 3,845 | python | en | code | 0 | github-code | 13 |
70873002897 | import sys
sys.path.append('../../modules')
from env.tic_tac_toe import TicTacToe
import numpy as np
# ***** welcome messages *****
print('==============================')
print('Welcome to the rollout tic-tac-toe AI.')
# ***** player choice of first-hand or second-hand *****
while True:
first_hand = input('Who g... | zhihanyang2022/classic_rl | examples/rollout/tic_tac_toe_ai.py | tic_tac_toe_ai.py | py | 3,451 | python | en | code | 0 | github-code | 13 |
14881338269 | from .app import app, ldap_obj
import ldap
def server_dn():
return 'cn=DHCP Config,cn=dhcpsrv,dc=%s,dc=%s' % (
app.config['openldap_server_domain_name'].split('.')[0],
app.config['openldap_server_domain_name'].split('.')[1])
def _deep_delete(dn):
try:
objects = ldap_obj.search_... | GR360RY/dhcpawn | flask_app/ldap_utils.py | ldap_utils.py | py | 767 | python | en | code | 2 | github-code | 13 |
14982135260 | import csv
from assignment3.min_wise_sample import MinWiseSample
from assignment3.utils import *
from assignment3.packet import *
reservoir_size_range = [100, 1000, 10000, 100000]
samples = []
addresses = []
ip_freq = dict()
ip_amt = 0
k = 10
# Define the host IPs you are interested in.
infected_host_ips = ['147.32.8... | Michieldoesburg/cyber_data_analytics | assignment3/sampling.py | sampling.py | py | 2,921 | python | en | code | 2 | github-code | 13 |
22787880421 | class Solution(object):
def isValid(self, s):
a = list()
for s0 in s:
if s0 in ['[', '{', '(']:
a.append(s0)
else:
if len(a) == 0:
return False
s1 = a.pop()
if not (s1 == '[' and s0 ... | lmb633/leetcode | 20isValid.py | 20isValid.py | py | 572 | python | en | code | 0 | github-code | 13 |
3529928431 | from itertools import product
import time
import warnings
import numpy as np
from numpy.testing import assert_raises, assert_
import pytest
from mrrt.operators import (
TV_Operator,
FiniteDifferenceOperator,
DiagonalOperator,
IdentityOperator,
CompositeLinOp,
BlockDiagLinOp,
BlockColumnLin... | mritools/mrrt.operators | mrrt/operators/tests/test_block.py | test_block.py | py | 11,670 | python | en | code | 1 | github-code | 13 |
14551996293 | import sys
NO_LETTER = 0
LETTER_EXISTS = 1
LETTER_TERMINAL = 2
class LetterNode:
def __init__(self):
self.is_terminal = NO_LETTER
self.next = None
class Trie:
def __init__(self):
self.chars = [LetterNode() for _ in range(26)]
@staticmethod
def char_num(char):
return... | StepDan23/MADE_algorithms | hw_14/d.py | d.py | py | 1,772 | python | en | code | 0 | github-code | 13 |
34132412230 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.contrib.postgres.fields
class Migration(migrations.Migration):
dependencies = [
('statistik', '0006_auto_20151114_0029'),
]
operations = [
migrations.AddField(
... | benhgreen/statistik | statistik/migrations/0007_auto_20151114_0154.py | 0007_auto_20151114_0154.py | py | 1,131 | python | en | code | 3 | github-code | 13 |
7042094650 | import eqsig
import numpy as np
import tempfile
import o3seespy as o3
from o3seespy import extensions
import os
def get_inelastic_response(tmp_file, mass, k_spring, f_yield, motion, dt, xi=0.05, r_post=0.0):
osi = o3.OpenSeesInstance(ndm=2, state=3)
# Establish nodes
bot_node = o3.node.Node(osi, 0, 0)
... | o3seespy/o3seespy | tests/test_extensions.py | test_extensions.py | py | 4,454 | python | en | code | 16 | github-code | 13 |
33946993135 | """
Зробити такі вибірки з отриманої бази даних:
Знайти 5 студентів із найбільшим середнім балом з усіх предметів.
Знайти студента із найвищим середнім балом з певного предмета.
Знайти середній бал у групах з певного предмета.
Знайти середній бал на потоці (по всій таблиці оцінок).
Знайти які курси читає певний викла... | F1r3n25/hw6 | create_table.py | create_table.py | py | 4,398 | python | uk | code | 0 | github-code | 13 |
10419599363 | import pickle
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib_venn import venn3
from util import get_args
def main(args):
sis_df = pd.read_csv('./data/sis.csv')
ling_fts = pickle.load(open('./ling_fts_new_df.p', 'rb'))
bert_fail_idx = []
ft_fail_idx = []
hybrid_fail_idx = []... | jadeleiyu/symmetry_inference | model_evaluation.py | model_evaluation.py | py | 2,142 | python | en | code | 0 | github-code | 13 |
39702778067 | #!/usr/bin/env python3
####################################################
### Installation script for the Juelich KKR code ###
####################################################
# import modules
import os
import sys
import getopt
import shutil
#####################################################################... | JuDFTteam/JuKKR | install.py | install.py | py | 11,093 | python | en | code | 5 | github-code | 13 |
42231872922 | # imports -----------------------------------------
import OpenGL
from OpenGL.GLU import gluLookAt
OpenGL.ERROR_ON_COPY = True
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.constants import GLfloat
import sys, os, random, time
from math import sin, cos, sqrt, pi
import numpy as np
# view settings
(vi... | tszalay/DNA-MCMC | Python/sim_draw.py | sim_draw.py | py | 3,819 | python | en | code | 0 | github-code | 13 |
37535280973 | from readMail import *
from config import FROM_EMAIL,EXCEL_CONFIG,CONTENT_EMAIL,LOGO
from excel_manager import *
from sendMail import *
from pdf_gen import *
excel_dict = read_pdf_in(EXCEL_CONFIG)
for key,value in excel_dict.items():
# Check if the row status is Not Sent
if value['Status'] == 'Not Sent':... | Animesh420/automated_email | orchestra.py | orchestra.py | py | 2,300 | python | en | code | 0 | github-code | 13 |
15236342952 | def isMonotonic(array):
if len(array) <= 2:
return True
direction = array[0] - array[1]
for i in range(1, len(array) - 1):
#print(f'direction: {direction}')
if direction == 0:
direction = array[i] - array[i + 1]
continue
if breaksDirection(direction, array[i], array[i + 1]):
return False
return Tr... | nssathish/python-dsa | algoexpert/IsMonoticArray_V2.py | IsMonoticArray_V2.py | py | 623 | python | en | code | 0 | github-code | 13 |
1378079071 | # Write a Python program to create and display all combinations of letters,
# selecting each letter from a different key in a dictionary.
# Sample data: {'1': ['a','b'], '2': ['c','d']}
import itertools
# Create a dictionary 'd' with keys '1' and '2', and associated lists of characters as values.
d = {'1': [... | Parth9780/Backend_12-SEP | Python 12_Sep/Assignment/Module_3/Que44.py | Que44.py | py | 698 | python | en | code | 0 | github-code | 13 |
20511182787 | import hashlib
import OpenSSL
import base64
FLAG = 'y0uAr3_S00_K1raK1ra'
SECRET = 'pkuggg::vsylaesl'
with open('cert.pem', 'rb') as f:
cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, f.read())
def getflag(token):
serial = hashlib.sha256((SECRET+token).encode()).hexdigest()[:8]
return ... | PKU-GeekGame/geekgame-0th | src/emoji/game/flag.py | flag.py | py | 598 | python | en | code | 46 | github-code | 13 |
40063655013 | import flask
from flask import request
import requests
# from markupsafe import Markup
print(request.__module__)
app = flask.Flask(__name__)
def topN():
r = requests.get("https://api.binance.com/api/v3/ticker/24hr")
symbol_24hrPercent_volume = [[i.get('symbol'), i.get('priceChangePercent'), i.get('volume')]... | RobinSequeira/CryptoCurrencyScreener | app_grid.py | app_grid.py | py | 3,258 | python | en | code | 0 | github-code | 13 |
5529631391 | '''
Preprocessor for Foliant documentation authoring tool.
Converts EPS images to PNG format.
'''
import re
from pathlib import Path
from hashlib import md5
from subprocess import run, PIPE, STDOUT, CalledProcessError
from foliant.preprocessors.base import BasePreprocessor
class Preprocessor(BasePreprocessor):
... | foliant-docs/foliantcontrib.epsconvert | foliant/preprocessors/epsconvert.py | epsconvert.py | py | 3,989 | python | en | code | 0 | github-code | 13 |
4075538437 | #!/usr/bin/env python3
# This worker now expects to receive an input file in runlist format (without
# the header).
import argparse
from pathlib import Path
import shutil
from subprocess import call
import sys
import time
from zeroworker import LockfileListReader, LockfileListWriter
# from zeroworker import ZmqListR... | lbl-neutrino/calibizer_job | calibizer_worker.py | calibizer_worker.py | py | 2,347 | python | en | code | 0 | github-code | 13 |
39792473322 | #
# TODO:
#
# Add closed connection and re-connection callbacks so callers are aware these
# things happened. The webhook needs this information to tell it to reprocess
# cached message files.
#
# This code is based on the async examples in the pika github repo.
# See https://github.com/pika/pika/tree/master/examples
... | DPIclimate/broker | src/python/api/client/RabbitMQ.py | RabbitMQ.py | py | 10,143 | python | en | code | 2 | github-code | 13 |
72748160979 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = open('README.rst').read()
setup(
name='crossbarhttprequests',
packages=['crossbarhttp'],
version='0.1.6',
description='This is a library for connecting to Crossbar.io HTTP Bridge Services using pyth... | ydaniels/crossbarhttprequests | setup.py | setup.py | py | 1,138 | python | en | code | 1 | github-code | 13 |
73643674577 | # Ejercicio 186: Calcular la distancia euclidiana con math.dist de Python 3.8.0.
# math.dist(p, q)
from math import dist
punto_1 = (2, 3)
punto_2 = (-3, 5)
distancia = dist(punto_1, punto_2)
print(distancia)
| Fhernd/PythonEjercicios | Parte001/ex186_distancia_euclidénea.py | ex186_distancia_euclidénea.py | py | 213 | python | es | code | 126 | github-code | 13 |
38616198386 | from HWdevices.abstract.AbstractGAS import AbstractGAS
from HWdevices.PSI_scheme.libs.parsing import Parser
from HWdevices.PSI_scheme.scheme.command import Command
from HWdevices.PSI_scheme.scheme.scheme_manager import SchemeManager
class GAS(AbstractGAS):
def __init__(self, ID, address):
super(GAS, self)... | SmartBioTech/PBRcontrol | HWdevices/PSI_scheme/GAS.py | GAS.py | py | 4,434 | python | en | code | 1 | github-code | 13 |
18717302585 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import nltk
nltk.download('stopwords')
nltk.download('wordnet')
import multiprocessing as mp
import sys
# The original news documents contain articles which are not json parseable.
# Simply ... | heroapoorva/Novelty-detection | cleaning_function.py | cleaning_function.py | py | 2,649 | python | en | code | 0 | github-code | 13 |
29581604732 | import requests
import pandas as pd
import re
from bs4 import BeautifulSoup
search = input("enter the product")
start_char = search[0]
string = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z']
A_to_G = string[0:7]
H_to_P = str... | rupeshjatav/webscrapping | scrap.py | scrap.py | py | 2,420 | python | en | code | 0 | github-code | 13 |
70169019857 | import math
from datetime import datetime, timedelta
from flask import (
Blueprint, render_template, request, redirect, url_for, session
)
from .auth import login_required
from .db import get_db
from .forecast import forecast
from .models.current_inventory import get_current_inventory
from .models.location import... | gracegreene/Flexchain2.0 | flexchain/insights.py | insights.py | py | 13,780 | python | en | code | 0 | github-code | 13 |
73667101139 | from django.urls import path
from .views import CampaignViewset, SubscriberViewset
urlpatterns = [
path('campaigns/', CampaignViewset.as_view({
'get': 'get_all_campaigns',
'post': 'create_campaign',
})),
path('id/<str:campaign_slug>/', CampaignViewset.as_view({
'get': 'get_id_from_... | DevJoshi030/Next-Demo-API | api/urls.py | urls.py | py | 589 | python | en | code | 0 | github-code | 13 |
17974746913 | #クラスを定義(サイコロ)
class Dice:
#インプットからの値によりサイコロの目を定義するための関数
def __init__(self, num_list):
self.top = num_list[0]
self.front = num_list[1]
self.right = num_list[2]
self.left = num_list[3]
self.back = num_list[4]
self.bottom = num_list[5]
#全ての転がし方を試すための関数
def or... | takumi-kawauchi/Python | AOJ/11/11_B.py | 11_B.py | py | 1,853 | python | ja | code | 0 | github-code | 13 |
13772267607 | import sys
import os
import mediateur
import dateur
from random import randrange
o_ordonate = ["oui","non"]
o_id_user = ["hash", "clair"]
o_date = ["mediane", "fixe", "clair"]
o_hours = ["fixe", "clair"]
o_id_item = ["hash", "clair"]
o_price = ["mediane", "moyenne", "clair"]
o_qty = ["moyenne"]
ordonate = ""
id_user ... | RedSPINE/Projet_Secu | Hall_Script/reparateur_modulaire/reparateur.py | reparateur.py | py | 9,534 | python | fr | code | 0 | github-code | 13 |
39737791193 | from control.TestbenchController import TestbenchController
from utils import Logger
from utils import Utils
from utils import BenchConfig
class CPDBench:
def __init__(self):
self._datasets = []
self._algorithms = []
self._metrics = []
self._logger = None
def start(self) -> N... | Lucew/CPD-Bench | src/interface/CPDBench.py | CPDBench.py | py | 1,380 | python | en | code | 0 | github-code | 13 |
15153125108 | def shellSort(arr):
#start with a big gap then reduce the gap
n=len(arr)
gap=n//2
#Do a gapped insertion sort for this gap size
#the first gap elements a[0..gap-1] are already in gapped
#order keep adding one or more element until the entire array
#is gap sorted
while gap>0:
for ... | amanlalwani007/important-python-scripts | shell sort.py | shell sort.py | py | 836 | python | en | code | 0 | github-code | 13 |
72460465617 | #!/usr/bin/env python
import os
import re
from distutils.core import setup, Extension
SDL_VERSION = '1.2.14'
def get_sources_from_dir(d):
return map(lambda x: os.path.join(d, x),
filter(lambda x: re.search(r'\.cc?$', x), os.listdir(d)))
extra_compile_args = ['-std=gnu99', '-I%s' % os.getcwd()]
extra_lin... | holtrop/pysdl2 | setup.py | setup.py | py | 1,052 | python | en | code | 4 | github-code | 13 |
71141528659 | from email import message
from turtle import title
from discord.ext import commands
from requests import get
from libs.help import EmbedHelp
from libs.embed import Embed
from typing import Any
class Explain(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def expla... | git-vamp/WitheredBot | plugins/explain_plugin.py | explain_plugin.py | py | 2,226 | python | en | code | 1 | github-code | 13 |
29835220619 | import random
import chess
from engines.game_data import GameData
from engines.zobrist_hash import ZobristHash
board = [[" " for x in range(8)] for y in range(8)]
piece_list = ["R", "N", "B", "Q", "P"]
def place_kings(brd):
while True:
rank_white, file_white, rank_black, file_black = (
rando... | Marius-likes-coding/chess-engine | chess-bot/test_zobriest.py | test_zobriest.py | py | 4,823 | python | en | code | 0 | github-code | 13 |
36333270615 | import sys
n, x = map(int, sys.stdin.readline().split(' '))
# print(n,x)
arr = list(map(int, sys.stdin.readline().split(' ')))
# print(arr)
end = x
res = 0
for i in range(end):
res += arr[i]
maxRes = res
cnt = 1
for i in range(end, n, 1):
start = i - x
res = res + arr[i] - arr[start]
if res > maxRes:
... | bywindow/Algorithm | src/DP/백준_21921_S3.py | 백준_21921_S3.py | py | 468 | python | en | code | 0 | github-code | 13 |
4241619036 | from .models import *
import yfinance as yf
import math
import pandas as pd
import time as tim
from smartapi import SmartConnect
from smartapi import SmartWebSocket
import traceback
from pytz import timezone
import json
from datetime import time, datetime
# import telepot
# bot = telepot.Bot("5448843199:AAEKjMn2zwAyZ5t... | sudhanshu8833/porfolio_management | datamanagement/data_collection.py | data_collection.py | py | 5,183 | python | en | code | 1 | github-code | 13 |
71473383697 | import unittest
import automatic_conversion_test_base
import numpy as np
import parameterized
import onnx
from onnx import helper
#####################################################################################
# Every test calls _test_op_conversion to downgrade a model from the most recent opset version
# to a... | onnx/onnx | onnx/test/version_converter/automatic_downgrade_test.py | automatic_downgrade_test.py | py | 3,187 | python | en | code | 15,924 | github-code | 13 |
10045654395 | #zad1
napis = 'ala ma kota'
ls = [(slowo, len(slowo)) for slowo in napis.split()]
print (ls)
#zad2
n = int(input('podaj ilosc elementow'))
def fibonacci(n):
fib1, fib2 = 0, 1
for i in range(n):
fib1, fib2 = fib2, fib1 + fib2
yield fib1
fib = [x for x in fibonacci(n)]
print(fib)
#zad3
def f1(n):... | burlakaann/Python | cw2/cw2.py | cw2.py | py | 1,438 | python | en | code | 0 | github-code | 13 |
41805750023 | # 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 recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify... | superwhd/LeetCode | 99 Recover Binary Search Tree.py | 99 Recover Binary Search Tree.py | py | 1,359 | python | en | code | 1 | github-code | 13 |
15791591230 |
def pageCount(n, p):
# Write your code here
if p==1 or n==p:
return 0
else:
if (n-p)<p:
if n-p <=1 and p%2!=0:
return 1
else:
return (n-p)//2
else:
return p//2
if __name__ == '__main__':
fptr = open(os... | Joshwa034/testrepo | pages.py | pages.py | py | 494 | python | en | code | 0 | github-code | 13 |
17080884214 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.MedicalUserMessageSubcriptionInfo import MedicalUserMessageSubcriptionInfo
class AlipayCommerceMedicalUsermessageSubscriptionQueryResponse(AlipayResponse):
def _... | alipay/alipay-sdk-python-all | alipay/aop/api/response/AlipayCommerceMedicalUsermessageSubscriptionQueryResponse.py | AlipayCommerceMedicalUsermessageSubscriptionQueryResponse.py | py | 1,742 | python | en | code | 241 | github-code | 13 |
40109589541 | import pytest
from src.problem_0025.listnode import ListNode
from src.problem_0025.problem_0025 import Solution
@pytest.fixture
def solution() -> Solution:
return Solution()
def list_to_listnode(list_: list[int]) -> ListNode:
"""Convert a list to a ListNode object.
Args:
list_ (list[int]): The... | firattamur/leetcode-python | tests/test_problem_0025.py | test_problem_0025.py | py | 1,523 | python | en | code | 0 | github-code | 13 |
4468052369 | from openpyxl.workbook import Workbook
from openpyxl import load_workbook
# Load workbook
wb = load_workbook('./data/regions.xlsx')
new_sheet = wb.create_sheet('ImportedSheet')
active_sheet = wb.active
# Select cell
cell = active_sheet['A1']
# Print selected cell in active sheet
print(cell)
# Print selected cell va... | pchmielecki87/PythonScripts | Excel/Openpyxl/openpyLoadWorkbook.py | openpyLoadWorkbook.py | py | 493 | python | en | code | 0 | github-code | 13 |
15725718510 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
file = open("./sample.txt","r")
read_file = file.read()
read_file = file.lower()
file.close()
sampleWordList = []
read_file = read_file.replace("2,000th","2000th")
puntuationList = [".",",","!","?","-","\'","\"","\n"]
for puntuation in puntuationList:
read_file = read... | PeterWolf-tw/ESOE-CS101-2016 | homework01_b05505037.py | homework01_b05505037.py | py | 1,015 | python | en | code | 15 | github-code | 13 |
17056975494 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.NimitzRange import NimitzRange
class NimitzRangeCond(object):
def __init__(self):
self._key = None
self._range = None
@property
def key(self):
... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/NimitzRangeCond.py | NimitzRangeCond.py | py | 1,387 | python | en | code | 241 | github-code | 13 |
74760616337 | from itertools import product
def shift_picture_to_frame_start(
frame: list[list[int]],
pic_width: int,
pic_height: int,
pic_x: int,
pic_y: int
) -> None:
"""Shifts a picture's elements to the top left corner of a frame."""
_validate_input(frame, pic_width, pic_height, pic_x, pic_y)
... | ForeverProglamer/game-logic-dev-test-tasks | task-1/core.py | core.py | py | 1,215 | python | en | code | 0 | github-code | 13 |
16711192134 | from selenium import webdriver
import time
driver = webdriver.Chrome()
url = 'http://c.m.163.com/news/l/107212.html?w=4'
count = 12
while count > 0:
driver = webdriver.Chrome()
for j in range(5):
driver.execute_script('''window.open("%s","_blank");''' % url)
# driver.refresh()
print... | liuzhy520/PYWebChecker | pywebrefresher/src/run.py | run.py | py | 454 | python | en | code | 0 | github-code | 13 |
5517187535 | """ Take standard deviation of residuals after explaining them by inputs """
# for grad
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import numpy as np
from numpy.polynomial.polynomial import Polynomial
from itertools import combinations
import statsmodels.api as sm
import numpy as np
import rando... | Scriddie/CCSL-ID | src/seq/std_vsb_exploit/hetero.py | hetero.py | py | 2,569 | python | en | code | 0 | github-code | 13 |
36647166611 | # for loop iterating over loop
l = [4,1,11,13]
ages = []
for person in l:
petyears = person*7
ages.append(petyears)
print(ages) # [28,7,77,91]
#comprehension
ages = [person*7 for person in l]
#only younger than 10
ages = [person*7 for person in l if person < 10]
###############################
#old way
list... | cjredmond/class_notes | week2/day1_comprehensions.py | day1_comprehensions.py | py | 1,377 | python | en | code | 0 | github-code | 13 |
5122160948 | import pygame
class Menu:
def __init__(self, game):
self.game = game
self.settings = self.game.settings
self.screen = game.screen
self.screen_rect = self.screen.get_rect()
self.initialize_menu_vars()
def initialize_menu_vars(self):
s... | sunnad99/Fantasy-Ludo-Game | menu.py | menu.py | py | 19,056 | python | en | code | 0 | github-code | 13 |
22456483186 | import os
# this get our current location in the file system
import inspect
HERE_PATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
# adding parent directory to path, so we can access the utils easily
import sys
root_path = os.path.join(HERE_PATH, '..')
sys.path.append(root_path)
import... | croningp/crystal_active_learning | simulation/plot_perf.py | plot_perf.py | py | 3,186 | python | en | code | 4 | github-code | 13 |
17051259244 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class DiscountDetail(object):
def __init__(self):
self._discount_amount = None
self._discount_desc = None
self._discount_type = None
self._id = None
self._is_hit... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/DiscountDetail.py | DiscountDetail.py | py | 4,216 | python | en | code | 241 | github-code | 13 |
29405519938 | # -*- coding: utf-8 -*-
"""
@author: MD.Nazmuddoha Ansary
"""
from __future__ import print_function
from termcolor import colored
import numpy as np
import matplotlib.pyplot as plt
import cv2
import scipy.signal
from scipy.ndimage import rotate
from scipy.ndimage.measurements import center_of_mass
from scipy.ndimage... | mnansary/pyHOCR | segmentation/script.py | script.py | py | 5,398 | python | en | code | 3 | github-code | 13 |
10977220224 | # dockstring for my file
""" This is tic tac toe console python game """
class GameSession:
""" This is class for creatin tic tac toe game session """
def __init__(self):
self.coords = []
self.value = 'O'
self.end_game = False
self.check_value = False
# curre... | PaulusSE/tic-tac-toe | game_ttt.py | game_ttt.py | py | 4,398 | python | en | code | 0 | github-code | 13 |
22074680915 | #!/usr/bin/env python3
"""
Simple client to get an object from the NPO Frontend API media endpoint. This version accepts explicit key, secret origins.
"""
from npoapi.media import Media
def check_credentials():
client = Media().command_line_client(
description="Get an media object from the NPO Frontend... | npo-poms/pyapi | src/npoapi/bin/npo_check_credentials.py | npo_check_credentials.py | py | 952 | python | en | code | 0 | github-code | 13 |
221561886 |
import torch
from torch.autograd import Function
from torch.autograd import gradcheck
import torch.nn as nn
#import torchvision
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from datamaestro import prepare_dataset
import torch.nn.functional as F
#Dataset et Dataloader
class MonDataset(... | Salomelette/AMAL2 | AMAL2/TME3/TME3.py | TME3.py | py | 2,645 | python | en | code | 0 | github-code | 13 |
38025000752 | #!/usr/bin/python3
import sys
def calculate(n, w1, maximum):
startIndex = 0
for currIndex in range(1, n):
if w1[startIndex] < maximum:
startIndex = currIndex
continue
if w1[startIndex] == w1[currIndex]:
if startIndex != currIndex:
startInde... | hmichelova/inf237 | set03/weights.py | weights.py | py | 909 | python | en | code | 0 | github-code | 13 |
74101533136 | import argparse
import csv
import codecs
import glob
import pickle
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument("--source", help="flag for path to data")
parser.add_argument("--target", help="flag for path to destination (must have a folder there)")
parser.add_argument("--include", hel... | danielsoutar/CS4098 | extract.py | extract.py | py | 7,202 | python | en | code | 0 | github-code | 13 |
71454125459 | import pygame
import sys
import os
import random
import json
# Platform independent paths
main_dir = os.path.split(os.path.abspath(__file__))[0]
img_dir = os.path.join(main_dir, 'images')
sound_dir = os.path.join(main_dir, 'audio')
font_dir = os.path.join(main_dir, 'font')
data_dir = os.path.join(main_dir, 'data')
de... | tonypham04/Robot-Hand-Asteroid-Smasher | game.py | game.py | py | 13,169 | python | en | code | 0 | github-code | 13 |
25229335373 | import random
from random import seed
import math
random.seed(1)
# ----------------- STEP 1: -----------------
# Network initialisation:
def makeNetwork(inputs,neuronsCount,output):
hiddenLayer = [{'weights':[random.random() for i in range(inputs+1)]} for i in range(neuronsCount)]
outputLayer = [{'weights':[ra... | yasharma2301/NeuralNetwork_From_Scratch | neural.py | neural.py | py | 7,752 | python | en | code | 0 | github-code | 13 |
22788031061 | class Solution(object):
def findContinuousSequence(self, target):
length = target // 2 + 1
print(length)
i = 1
j = 1
result = []
temp_sum = 0
while i <= j and j <= length:
while j <= length and temp_sum < target:
temp_sum ... | lmb633/leetcode | 57findContinuousSequence.py | 57findContinuousSequence.py | py | 924 | python | en | code | 0 | github-code | 13 |
40734928378 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os, json
from datetime import datetime
_timeString = datetime.today().strftime("%y%m%d%H%M%S")
rootDirectory = os.getcwd()
#rootDirectory = os.path.dirname(rootDirectory)
dataDirectory = os.path.join(rootDirectory, "Data")
readingListDirectory = os.path.join(root... | themadman0980/ReadingListManager | readinglistmanager/filemanager.py | filemanager.py | py | 1,955 | python | en | code | 1 | github-code | 13 |
6021059507 | #!/usr/bin/python3
# Write a function that computes the square value of all integers of a matrix.
def square_matrix_simple(matrix=[]):
# new list
new = []
# square each element
for i in matrix:
new.append([x**2 for x in i])
# return new list
return new
| johnkoye19/alx-higher_level_programming | 0x04-python-more_data_structures/0-square_matrix_simple.py | 0-square_matrix_simple.py | py | 287 | python | en | code | 1 | github-code | 13 |
23178428264 | # coding=UTF-8
__author__ = 'wangtao'
import unittest
import os
import glob
from appium import webdriver
PATH = lambda p: os.path.abspath(
os.path.join(os.path.dirname(__file__), p))
success = True
class XcfAndroidTests(unittest.TestCase):
def setUp(self):
desired_caps = {}
desired_caps['pla... | taozitao/UIautomatorForXCF | loginDemo/__init__.py | __init__.py | py | 1,275 | python | en | code | 0 | github-code | 13 |
10635751623 | # CTI-110
# M3HW2 - Software Sales
# Juan Santiago
# 9-21-17
#
#A software company sells a package that retails for $99.
#They offer bulk discounts for volume purchases
#(for example, buying many copies to install in a college classroom).
#The discounts are as follows:
#Quantity 10-19: 10% discount
#Quant... | JSantiago2007/cti110 | M3HW2_SoftwareSales_Santiago.py | M3HW2_SoftwareSales_Santiago.py | py | 1,016 | python | en | code | 0 | github-code | 13 |
18392043824 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 21 13:49:06 2019
@author: rajat
"""
# import the modules used
import cv2
import numpy as np
import scipy.io as scsio
import matplotlib.pyplot as plt
from skimage.transform import AffineTransform
from skimage.measure import ransac
# load the positio... | rajatsaxena/MultiCameraPositionAlignment | mcpa.py | mcpa.py | py | 14,095 | python | en | code | 1 | github-code | 13 |
33121620336 |
import numpy as np
import scipy.linalg as linalg
from tqdm import tqdm
from numba import njit
# @njit
def ftcs(N, M, T, S_0, S_max, K, r, sigma, optimal_delta=True):
'''
N -> Number of time steps
M -> Number of grid spaces
S_max -> Maximum stock price
'''
S_max = 2 * S_0
if optimal_delta:... | DaanMoll/ComputationalFinance | assignment3/plots/ftcs_mat.py | ftcs_mat.py | py | 2,232 | python | en | code | 0 | github-code | 13 |
23804444876 | """
My MQTT library for ease of deploying HA agents.
The following entries are expected in the config dictionary:
[main]
mqttServer
mqttPort
mqttUser
mqttPass
mqttSet
mqttState
mqttId
"""
# TODO: augment LWT with interrupt handler to call specified function
import socket, time
import simplejson ... | jerobins/dmx-uplights | bin/lib/mymqtt.py | mymqtt.py | py | 4,360 | python | en | code | 0 | github-code | 13 |
6767243788 | #wainwright
import matplotlib.pyplot as plt
import numpy as np
import re
import retrace_path
import create_maze
import path_finding_old
#use haversine distance
def calculateDistance(long1,long2,lat1,lat2):
dlo=long1-long2
dla=lat1-lat2
R=6371e3 #metres
a=np.power(np.sin(0.5*dla... | JordanBarton/carrot47 | wainwright.py | wainwright.py | py | 5,797 | python | en | code | 0 | github-code | 13 |
5328833642 | from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
# Create your views here.
def main(request):
template = loader.get_template('main.html')
context = {}
return HttpResponse(template.render(context, request))
def detalle(request, post_id):
... | billygl/blog | posts/views.py | views.py | py | 506 | python | en | code | 0 | github-code | 13 |
28601505840 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 16:07:43 2019
@author: dxh
test convolving two func
"""
import numpy as np
import astropy.io.fits as pyfits
import matplotlib.pyplot as plt
from scipy.integrate import quad
import matplotlib as matt
import matplotlib.lines as mlines
from matplo... | dartoon/my_code | test_code/convolve_two_fun.py | convolve_two_fun.py | py | 1,996 | python | en | code | 0 | github-code | 13 |
33974877573 | from django.urls import path
from website.views import home,logout_user,register_user,customer_record,delete_record,Add_record,update_record
urlpatterns = [
path('', home, name='home'),
path('logout/',logout_user,name='logout'),
path('register/',register_user,name='register'),
path('record/<int:pk>/',customer_record,n... | HellyModiKalpesh/CRM-internship | website/urls.py | urls.py | py | 524 | python | en | code | 1 | github-code | 13 |
7834216340 | """add checksum columns and revoke token table
Revision ID: b58139cfdc8c
Revises: f2833ac34bb6
Create Date: 2019-04-02 10:45:05.178481
"""
import sqlalchemy as sa
from alembic import op
from journalist_app import create_app
from models import Reply, Submission
from sdconfig import SecureDropConfig
from store import St... | freedomofpress/securedrop | securedrop/alembic/versions/b58139cfdc8c_add_checksum_columns_revoke_table.py | b58139cfdc8c_add_checksum_columns_revoke_table.py | py | 3,226 | python | en | code | 3,509 | github-code | 13 |
12430091908 | # This is a Python Program to compute prime factors of an integer.
n = int(input("\nEnter any Number = "))
print("-------------------------")
print("Prime Factors of {0} are:".format(n))
print("-------------------------")
for i in range (2, n+1):
if n%i == 0:
count = 0
for j in range (1, i+1): ... | Prashant1099/Python-Programming-Examples-on-Mathematical-Functions | 6. Compute Prime Factors of an Integer.py | 6. Compute Prime Factors of an Integer.py | py | 494 | python | en | code | 0 | github-code | 13 |
74675201616 | import os
from .system import System
from ..forcefield import *
from ..topology import *
from .. import logger
class LammpsExporter():
'''
LammpsExporter export a non-polarizable :class:`System` to input files for LAMMPS.
LAMMPS is powerful and flexible. But the input file for LAMMPS is a mess and cannot... | z-gong/mstk | mstk/simsys/lmpexporter.py | lmpexporter.py | py | 12,785 | python | en | code | 7 | github-code | 13 |
74673694416 | import numpy as np
import pandas as pd
from packaging import version
from scipy.sparse import csr_matrix
from typing import Mapping, List, Tuple, Union
from sklearn.metrics.pairwise import cosine_similarity
from bertopic.representation._base import BaseRepresentation
from sklearn import __version__ as sklearn_version
... | MaartenGr/BERTopic | bertopic/representation/_keybert.py | _keybert.py | py | 9,223 | python | en | code | 4,945 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.