seq_id stringlengths 7 11 | text stringlengths 156 1.7M | repo_name stringlengths 7 125 | sub_path stringlengths 4 132 | file_name stringlengths 4 77 | file_ext stringclasses 6
values | file_size_in_byte int64 156 1.7M | program_lang stringclasses 1
value | lang stringclasses 38
values | doc_type stringclasses 1
value | stars int64 0 24.2k ⌀ | dataset stringclasses 1
value | pt stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
5300353352 | """
You have a matrix MxN that represents a map. There are 2 possible states on the map: 1 - islands, 0 - ocean. Your task is to calculate the number of islands in the most effective way. Please write code in Python 3.
Inputs:
M N
Matrix
Examples:
Input:
3 3
0 1 0
0 0 0
0 1 1
Output: 2
Input:
3 4
0 0 0 1
0 0 1 0
0 ... | pawel-jasnowski/Quantum_python_coding | Islands.py | Islands.py | py | 1,789 | python | en | code | 0 | github-code | 6 |
30727489542 | from pydantic import BaseModel, Field, validator
class Address(BaseModel):
region: str
city: str
street_type: str
street: str
house_type: str
house: str
value: str
lat: float
lng: float
class Salary(BaseModel):
from_: int = Field(alias='from')
to: int
currency: str
... | SayKonstantin/data_validation | models.py | models.py | py | 1,625 | python | en | code | 0 | github-code | 6 |
22042359096 | #Developed By: Tonumoy Mukherjee
import os
from scipy.io import wavfile
import scipy
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from keras.layers import Conv2D, MaxPool2D, Flatten, LSTM
from keras.layers import Dropout, Dense, TimeDistributed
from keras.models imp... | Tonumoy/MFCCNet-A-Network-for-Earthquake-Early-Warning-Applications-using-Speech-Recognition-Techniques | model.py | model.py | py | 13,362 | python | en | code | 0 | github-code | 6 |
70383310909 | from gobigger.utils import SequenceGenerator
from gobigger.players import HumanSPPlayer
from .player_manager import PlayerManager
class PlayerSPManager(PlayerManager):
def __init__(self, cfg, border, team_num, player_num_per_team, spore_manager_settings,
random_generator=None, sequence_generato... | opendilab/GoBigger | gobigger/managers/player_sp_manager.py | player_sp_manager.py | py | 1,460 | python | en | code | 483 | github-code | 6 |
42976695103 | def isPrime(num):
if num == 1:
return False
else:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
i = int(input())
while True:
i = list(str(i))
if i == i[::-1]:
if isPrime(int(''.join(i))):
print(''.join(i))
break
i = int(''.join(i... | jinhyo-dev/BOJ | 소수&팰린드롬.py | 소수&팰린드롬.py | py | 331 | python | en | code | 1 | github-code | 6 |
426353070 | """
Function in this module shuffles sentence with leaving it readable.
"""
from random import randint, shuffle
def shuffle_string(string):
while True:
symbols_list = list(string)
shuffle(symbols_list)
result = ''.join(symbols_list)
if result != string:
return result... | YanaSharkan/Homework | lesson_7_hw_6/task_6_permutuate.py | task_6_permutuate.py | py | 1,107 | python | en | code | 0 | github-code | 6 |
27937808825 | import logging
import time
import sys
from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.ke... | Zyniel/DansePlanningManager | src/app/whatsapp_bot.py | whatsapp_bot.py | py | 3,082 | python | en | code | 0 | github-code | 6 |
31434243930 | #!/usr/bin/python3
# Coding: utf-8
# Author: Rogen
# Description: 專家系統功能集
from os import walk
from tkinter import *
from PIL import ImageTk, Image
from tkinter import ttk, messagebox, font, filedialog
from tkintertable.TableModels import TableModel
from tkintertable.Tables import TableCanvas
from matplotlib.backends.... | NCHU-rogen/ExpertSystem_Project | ExpertSystem_Functions.py | ExpertSystem_Functions.py | py | 33,877 | python | en | code | 0 | github-code | 6 |
74150991549 | import numpy as np
import pygame as pyg
from math import cos, sin
from src.objects.point import Point
class Cube(Point):
def __init__(self, x: int, y: int, z: int, side:int, rotation: str = 'xyz', static: bool = False) -> None:
super().__init__(x, y, z, rotation, static)
self.center =... | FukuInTheCode/pythonMath | src/objects/cube.py | cube.py | py | 1,309 | python | en | code | 1 | github-code | 6 |
40189093783 | __author__ = 'eladron'
import folium
#variables
lat = 32.12830
long = 34.79269
loc = [lat,long]
zs = 18
tls = 'Stamen Terrain'
map_path = 'App2-Leaflet_Webmaps/map_test.html'
map = folium.Map(location=loc, zoom_start = zs)
map.simple_marker(location=loc, popup='My address' , marker_color='purple')
map.create_... | Elad73/PythonTutorials | python/Udemy/Mega_Course/App2-Leaflet_Webmaps/map.py | map.py | py | 334 | python | en | code | 0 | github-code | 6 |
6757308419 | # exclude from patching
DONT_PATCH_MY_STAR_IMPORTS = True
from mods.RiftOptimizer.Patcher import *
import threading
import queue
import Level
import LevelGen
import inspect
import logging
import SteamAdapter
import Game
import os
import pygame
import dill as pickle
import mods.RiftOptimizer.RiftOptimizer as RiftOptim... | anotak/RiftOptimizer | ThreadedIO.py | ThreadedIO.py | py | 9,785 | python | en | code | 1 | github-code | 6 |
18212175699 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 8 12:22:49 2019
@author: Swathi
"""
import math
def partition(items,left,right):
print("The current items are ",items)
pivot=items[math.floor((left+right)/2)]
l=left
r=right
print("--pivot is ",pivot)
print("--left element is and it's index is ",i... | swathi1810/DailyCodingProblems | quicksort.py | quicksort.py | py | 1,832 | python | en | code | 0 | github-code | 6 |
2523151507 | from doubly_linked_list import DoublyLinkedList
import math
import random
class HashTable:
def __init__(self, items, table_size, auxiliary_hash_method='universal', collision_resolution='chaining'):
self.items = items
self.collision_resolution = collision_resolution
self.auxiliary_hash_meth... | rb05751/Algorithms | Python/data_structures/hash_table.py | hash_table.py | py | 5,779 | python | en | code | 0 | github-code | 6 |
9185141020 | import os
from absl import flags
FLAGS = flags.FLAGS
def get_executable_path(py_binary_name):
"""Returns the executable path of a py_binary.
This returns the executable path of a py_binary that is in another Bazel
target's data dependencies.
On Linux/macOS, the path and __file__ has the same root director... | bazelbuild/bazel | third_party/py/abseil/absl/testing/_bazelize_command.py | _bazelize_command.py | py | 1,658 | python | en | code | 21,632 | github-code | 6 |
37377572966 | import os
import gym
import joblib
import cv2
import numpy as np
import tensorflow as tf
from collections import deque
from argparse import ArgumentParser
from gym import spaces
from tensorflow.python.training.moving_averages import assign_moving_average
cv2.ocl.setUseOpenCL(False)
try:
import const
except:
... | fangchuan/carla-DRL | utils/common.py | common.py | py | 16,371 | python | en | code | 0 | github-code | 6 |
41550408574 | import time
from enum import IntEnum
from .. util import log
from .. project import attributes, load
DEFAULT_FPS = 24
class STATE(IntEnum):
ready = 0
running = 1
complete = 2
canceled = 3
max_steps = 4
timeout = 5
class Runner(object):
def __init__(self, *, amt=1, fps=0, sleep_time=0, ... | ManiacalLabs/BiblioPixel | bibliopixel/animation/runner.py | runner.py | py | 2,884 | python | en | code | 263 | github-code | 6 |
2116138484 | """
Tests for QCFractals CLI
"""
import os
import time
import tempfile
import pytest
from qcfractal import testing
from qcfractal.cli.cli_utils import read_config_file
import yaml
# def _run_tests()
_options = {"coverage": True, "dump_stdout": True}
_pwd = os.path.dirname(os.path.abspath(__file__))
@pytest.fixture... | yudongqiu/QCFractal | qcfractal/cli/tests/test_cli.py | test_cli.py | py | 6,785 | python | en | code | null | github-code | 6 |
21490215145 | #
# PyParagraph
# Ryan Eccleston-Murdock
# 28 November 2020
#
# Purpose: Convert old employee records into the new format.
#
# Sources:
import os
import re
in_path = './raw_data'
in_file_name = 'paragraph_1.txt'
in_filepath = os.path.join(in_path, in_file_name)
def findPuncuation(word):
one_sentence = 0
for l... | reccleston/python-challenge | PyParagraph/main.py | main.py | py | 1,109 | python | en | code | 0 | github-code | 6 |
6944102064 | # Hangman game
#
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
WORDLIST_FILENAME = "words.txt"
def loadWords():
"""
Returns a list of valid words.... | git786hub/hango | hangman/hangman.py | hangman.py | py | 5,849 | python | en | code | 0 | github-code | 6 |
17634455157 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from re import I
from flask import Flask
from flask import request
import chromadb
from chromadb.config import Settings
app = Flask(__name__)
client = chromadb.Client(Settings(chroma_api_impl='rest',
chroma_server_host='localhost',
... | aravindcz/mygpt-chromadbwrapper | controller/controller.py | controller.py | py | 2,166 | python | en | code | 0 | github-code | 6 |
41385226539 | #!/usr/bin/env python
# coding: utf-8
# # Design of a Multi-Zone VAV System (the Shorter Way)
# ---
# In this notebook the example from the previous notebook **Design of a Multi-Zone VAV System (the Long Way)** is repeated, but now the `VAVSystem` class will be used, which automates the design procedure of a multi-zo... | TomLXXVI/Air-Conditioning | _build/jupyter_execute/vav_multizone_design_p2.py | vav_multizone_design_p2.py | py | 11,004 | python | en | code | 2 | github-code | 6 |
41045579026 | import machine
import utime
# Get the temperature from the internal RP2040 temperature sensor.
sensor_temp = machine.ADC(4)
# See Raspberry Pi Pico datasheet for the conversion factor.
conversion_factor = 3.3 / (65535)
temp = []
file = open ("temps.text", "w")
#Go into a loop
while True:
# Get a temperature read... | simonSlamka/UCL-ITtech | project/romulus/Week39_justTemp.py | Week39_justTemp.py | py | 777 | python | en | code | 2 | github-code | 6 |
12610527769 | from ..utils import *
##
# Minions
class BT_022:
"""Apexis Smuggler"""
events = Play(CONTROLLER, SECRET).after(DISCOVER(RandomSpell()))
class BT_014:
"""Starscryer"""
deathrattle = ForceDraw(RANDOM(FRIENDLY_DECK + SPELL))
class BT_028:
"""Astromancer Solarian"""
deathrattle = Shuffle(CONT... | jleclanche/fireplace | fireplace/cards/aoo/mage.py | mage.py | py | 1,576 | python | en | code | 645 | github-code | 6 |
29431482505 | import os
import numpy as np
import cv2
import glob
srcw, srch = 1920, 1080
x, y, w, h = 6, 599, 517, 421
app_name = 'gpu_math.exe'
app_dir = 'D:\\Code\\gpu_tracking\\gpu-object-tracking\\build\\bin'
yuv_file = '%s\\test.yuv'%app_dir
roi_file = '%s\\dump.gpu-roi.0000.517x421.yuv'%app_dir
aff_file = '%s\\dump.gpu-affin... | mintaka33/gpu-object-tracking | run.py | run.py | py | 3,904 | python | en | code | 1 | github-code | 6 |
73876828348 | from .util import *
from ..index import IndexAccessor, IndexValue
from ..util import Stack
# Evaluator objects evaluate postfix boolean expressions and return the document IDs associated with the
# evaluated expression. The validity of the boolean expression is implicitly assumed and behaviour in violation
# of this p... | tsontario/minerva | pkg/booleanretrieval/evaluator.py | evaluator.py | py | 2,491 | python | en | code | 2 | github-code | 6 |
4970677598 | # Importing Modules
import matplotlib.pyplot as plt
#%matplotlib inline
# Graph Rev 7
x_values = range(1, 1001)
y_values = [x**2 for x in x_values]
plt.style.use('seaborn')
#fig, ax = plt.subplots()
fig, ax = plt.subplots(figsize=(5,3))
# Using Colormap
# Colormap references:
ax.scatter(x_values, y_values, c = y_v... | RaulMaya/Data-Visualization | python_programs/generating data/scatter_squares.py | scatter_squares.py | py | 791 | python | en | code | 0 | github-code | 6 |
1688662512 | from selenium import webdriver
import time
import csv
# driver = webdriver.Chrome(r'path\to\the\chromedriver.exe')
driver = webdriver.Chrome()
# Go to the page that we want to scrape
driver.get("https://blog.feedspot.com/usa_news_websites/")
#close the pop up
time.sleep(2)
close_button = driver.find_element_by_xpath... | skyyaya28/NYCDSA-Webscraping | feedspot_seleium.py | feedspot_seleium.py | py | 2,100 | python | en | code | 0 | github-code | 6 |
15251411062 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nearsight', '0003_auto_20170718_1326'),
]
operations = [
migrations.AlterField(
model_name='layer',
... | venicegeo/nearsight | nearsight/migrations/0004_auto_20170718_1327.py | 0004_auto_20170718_1327.py | py | 426 | python | en | code | 0 | github-code | 6 |
72064206267 | # -*- coding: utf-8 -*-
# @Time : 2022/7/24 15:46
# @Author : 4v1d
# @File : 中国招标网.py
# @Software: PyCharm
import httpx
url = 'https://www.baidu.com'
res = httpx.get(url)
print(res.text) | daweiTech/Spider | 爬虫/01-网络爬虫通讯原理/demo1.py | demo1.py | py | 217 | python | en | code | 0 | github-code | 6 |
71276693308 | from src.toy_robot import ToyRobot
from src.table import Table
from src.parse_input import ParseInput
from src.errors import * # import all the error classes
class Run(object):
def __init__(self):
self.parse_input = ParseInput()
self.reset()
def reset(self):
self.table = Table(5,5) # a... | r3gm1/toy-robot-challenge | src/run.py | run.py | py | 1,270 | python | en | code | 0 | github-code | 6 |
650430067 | #! /bin/python
import os
import sys
import json
import numpy as np
import luigi
import vigra
import nifty
import nifty.tools as nt
import cluster_tools.utils.volume_utils as vu
import cluster_tools.utils.function_utils as fu
from cluster_tools.cluster_tasks import SlurmTask, LocalTask, LSFTask
#
# Orphan Filter Ta... | constantinpape/cluster_tools | cluster_tools/postprocess/orphan_assignments.py | orphan_assignments.py | py | 4,673 | python | en | code | 32 | github-code | 6 |
31963106071 | from sys import stdin
input = stdin.readline
n = int(input())
sets = set()
for _ in range(n):
input_string = input().split()
if input_string[0] == "all":
sets = set([x for x in range(1, 21)])
elif input_string[0] == "empty":
sets = set()
else:
transaction, numb = inp... | yongwoo-jeong/Algorithm | 백준/Silver/11723. 집합/집합.py | 집합.py | py | 825 | python | en | code | 0 | github-code | 6 |
36177564083 | tu_dien = {'dog':'con chó','cat':'con mèo'}
keys = tu_dien.keys()
values = tu_dien.values()
print(keys,values)
def back():
print('{:?^70}'.format(' 1.Quay lại 2.Thoát '))
try:
l = int(input('Entry your choose:'))
if l == 1:
control()
if l == 2:
print('Xin c... | Thanhsobad/Demo123456_16A2 | C11/baitap11.15.py | baitap11.15.py | py | 2,260 | python | vi | code | 0 | github-code | 6 |
21998697826 | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n < 0:
return False
cnt = 0
while n:
n &= (n - 1)
cnt += 1
return cnt == 1
so = Solution()
print(so.isPowerOfTwo(5))
| hangwudy/leetcode | 200-299/231. 2 的幂.py | 231. 2 的幂.py | py | 250 | python | en | code | 0 | github-code | 6 |
36303671169 | from pygame import *
from time import sleep
from random import randint
#создай игру "Лабиринт"!
win_width = 700
win_height = 500
window = display.set_mode((win_width, win_height))
display.set_caption("Шутер")
background = transform.scale(
image.load("road.png"),
(win_width, win_height)
)
seconds_l... | deathelis/ping_pong | auto_racing/auto_racing.py | auto_racing.py | py | 2,456 | python | en | code | 0 | github-code | 6 |
6589196869 | #entrada
numeroPaquetes=int(input('cantidad de cajas'))
costoTotal=0
for i in range (numeroPaquetes):
alto=float(input('alto'))
ancho=float(input('ancho'))
profundo=float(input('profundo'))
#proceso
volumen=alto*ancho*profundo
costo=(volumen*5)
print(volumen)
if alto>30:
costo=costo... | fernando-tejedor/practicas-python | practica examen 2.py | practica examen 2.py | py | 484 | python | es | code | 0 | github-code | 6 |
37974301119 | '''
Time calculations
Author: Howard Webb
Date: 2/9/2023
'''
from datetime import datetime
import time
import math
from MARSFarm_Util import *
def get_day(start_date):
# calculate number of days since start_date (as timestamp)
now = datetime.now().timestamp()
dif = now - start_date
days = math.ceil(di... | webbhm/MARSFarm-VX | Time_Util.py | Time_Util.py | py | 1,423 | python | en | code | 0 | github-code | 6 |
7326203114 | import hls4ml
import os
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import tarfile
import shutil
PARSE = False
data = []
data_path = 'data_pickles/data6.pkl'
saved_dir = os.getcwd()
if PARSE:
df = pd.read_pickle(data_path)
os.chdir('/eos/home-n/nghielme/')
ids = df['ID'].tolis... | nicologhielmetti/enet-script | analyze_results.py | analyze_results.py | py | 5,105 | python | en | code | 0 | github-code | 6 |
35605543653 | import numpy as np
import init_lattice as lat
import MH_algorithm as MH
import Wolff_algorithm as W
import autocorrelation_functions as acf
import importlib
importlib.reload(MH)
importlib.reload(W)
importlib.reload(lat)
importlib.reload(acf)
# Produces data of internal energy autocorrelation against sweeps and the auto... | Part-II-Computational-Physics/cluster-algorithms-for-monte-carlo-jbd29 | figure_12_E.py | figure_12_E.py | py | 2,040 | python | en | code | 0 | github-code | 6 |
36767887159 | def main():
t = int(input())
for _ in range(t):
n = int(input())
arr = [2**i for i in range(1, n+1)]
if n > 3:
print(abs((sum(arr[:(n//2)-1])+arr[-1]) - sum(arr[(n//2)-1:-1])))
else:
print(2)
if __name__ == '__main__':
main()
| arbkm22/Codeforces-Problemset-Solution | Python/A_Phoenix_and_Balance.py | A_Phoenix_and_Balance.py | py | 296 | python | en | code | 0 | github-code | 6 |
9369626600 |
def rotate_image(matrix) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
# [[7, 8, 9], [4, 5, 6], [1, 2, 3]]
# matrix.reverse()
# print(matrix)
# for i in range(len(matrix)):
# for j in range(i):
# print("m[i][j]-->",matrix[i][j] , "m[j][i]-->", ... | HamzaQahoush/Problem-Solving | rotate_image.py | rotate_image.py | py | 591 | python | en | code | 0 | github-code | 6 |
24486961270 | from airflow import DAG
from airflow.providers.http.operators.http import SimpleHttpOperator
from airflow.hooks.base import BaseHook
from airflow.operators.python import PythonOperator
import datetime
import requests
import json
dag = DAG(
dag_id='533_api_generate_report',
schedule_interval='0 0 * * *',
start_date... | Artem-ne-Artem/Data-engineering-by-Yandex-Practicum | s3-lessons/Theme_5/Task_5.3.3.py | Task_5.3.3.py | py | 1,229 | python | en | code | 0 | github-code | 6 |
37694828992 | from sgm_lang.DataType import DataType
from sgm_lang.TokenType import TokenType
from sgm_lang.CompoundToken import CompoundToken
class TokenizerError(Exception):
pass
class Tokenizer:
def __init__(self, code):
self.position = 0
self.code = code
self.splitCode = []
self.token... | GrzegorzNieuzyla/sgm-lang | sgm_lang/tokenizer.py | tokenizer.py | py | 6,142 | python | en | code | 0 | github-code | 6 |
38903193024 | import argparse
import csv
class MergeDataset:
def __call__(self, positive_handle, negative_handle, out_handle, delimiter=",", quote_character='"'):
csv_writer = csv.writer(out_handle, delimiter=delimiter, quotechar=quote_character)
# Write positive
for r in positive_handle:
... | elangovana/sentimentanalysis-chainer-sagemaker | custom_chainer/datasetmovies/MergeDataset.py | MergeDataset.py | py | 1,092 | python | en | code | 0 | github-code | 6 |
4086714077 | import random
import typing as t
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from langchain.embeddings import HuggingFaceInstructEmbeddings
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.preprocessing import MinMaxScaler
from bunkatopics.datamodel import Bour... | charlesdedampierre/BunkaTopics | bunkatopics/visualisation/bourdieu.py | bourdieu.py | py | 20,127 | python | en | code | 35 | github-code | 6 |
72779091069 | from typing import List
import hikari
async def alert(event: hikari.GuildMessageCreateEvent, command: str, config, *args) -> None:
guild: hikari.GatewayGuild = event.get_guild()
roles: List[hikari.Role] = guild.get_roles().values()
for role in roles:
if role.mention == args[0] and role.name not i... | Angry-Maid/DiscordAlertBot | commands/alert.py | alert.py | py | 514 | python | en | code | 1 | github-code | 6 |
10565146032 | from matplotlib import pyplot
import matplotlib.pyplot as plt
import random, operator, math
from collections import defaultdict
def import_data(filename):
with open (filename, "r") as f:
dataPoints = [(float(line.split()[1]), float(line.split()[2])) \
for line in f if '#' not ... | steffervescency/compling | exercise8/coli_ex_8.py | coli_ex_8.py | py | 4,401 | python | en | code | 0 | github-code | 6 |
3795696476 | # -*- coding: utf_8 -*-
import sys
import time
import json
import re
import datetime
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebD... | 1neoneo3/scrape | scraping1.py | scraping1.py | py | 2,819 | python | en | code | 0 | github-code | 6 |
33902526132 | import asyncio
import ssl
from itertools import zip_longest
import click
from aiohttp import TCPConnector
from aiohttp.http import HeadersParser
from hls_get.downloader import HLSDownloader
async def download(links, path, names, coros, headers, timeout, clean_up, verify):
headers_parser = HeadersParser()
he... | SoulMelody/hls-get | hls_get/cli.py | cli.py | py | 2,929 | python | en | code | 39 | github-code | 6 |
35696320275 | from flask import Flask ,request,Response,session,jsonify,render_template,redirect,url_for
from flask.json import JSONDecoder
from google.protobuf import message
from keras.utils.generic_utils import default
from db import create_db,db
from models import imgModel,User
from flask_restful import marshal_with,fields,abort... | yussif-issah/finalwork | main.py | main.py | py | 18,083 | python | en | code | 0 | github-code | 6 |
4642597194 | class fifo:
a = []
def printstk(a):
for i in a:
print(i)
def push(a):
ele=int(input('Enter element : '))
a.append(ele)
def pop(a):
if(top!=-1):
print(a.pop(),'Popped')
else : print('Stack Underflow')
... | aichaitanya/Python-Programs | fifo.py | fifo.py | py | 827 | python | en | code | 0 | github-code | 6 |
15177048765 | import tkinter as tk
window = tk.Tk()
entry = tk.Entry()
def handle_submit():
try:
print("Processing Submission")
text = entry.get()
if not text:
print("No text entered")
entry.delete(0, tk.END)
return entry.insert(0,"No text entered!")
JAAR = ... | Serakoi/p1.3.5 | app.py | app.py | py | 1,000 | python | en | code | 0 | github-code | 6 |
75163153466 | import werkzeug
def test_CVE_2019_14806():
"""
CVE-2019-14806
high severity
Vulnerable versions: < 0.15.3
Patched version: 0.15.3
https://github.com/advisories/GHSA-gq9m-qvpx-68hc
Pallets Werkzeug before 0.15.3, when used with Docker,
has insufficient debugger PIN randomness because ... | e-ruiz/big-data | 01-NoSQL/atividade-04/src/tests/test_security.py | test_security.py | py | 533 | python | en | code | 1 | github-code | 6 |
73765860989 | import asyncio
import collections
import contextlib
import datetime
import functools
import io
import multiprocessing
import multiprocessing.pool
import os
import signal
import tempfile
from aiohttp import web
import marshmallow
from oslo_config import cfg
from oslo_log import log
LOG = log.getLogger(__name__)
CONF... | indigo-dc/DEEPaaS | deepaas/model/v2/wrapper.py | wrapper.py | py | 12,808 | python | en | code | 31 | github-code | 6 |
26253976434 | import re
from bowler import Query
from fissix.pytree import Node, Leaf
from fissix.fixer_util import FromImport, Name, Comma, is_import
from bowler.types import Capture, Filename
def update_regex_to_path(regex: str) -> str:
match = re.findall(r"\(\?P<(\w+)>([^\)]+)\)", regex)
if match:
for name, exp... | aalekseev/healthy-projects | src/django_patches/url_2_path/patch.py | patch.py | py | 1,835 | python | en | code | 0 | github-code | 6 |
72031135549 | #!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2021/1/3 21:23
# @Author : mafei0728
# @Version:V 0.1
# @File : bar.py
# @desc :
# 1)准备数据
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
movie_name = ['雷神3:诸神黄昏', '正义联盟', '寻梦环游记']
first_d... | mafei0728/pythonProject | mateplotlibDemo/day03/bar.py | bar.py | py | 810 | python | en | code | 0 | github-code | 6 |
17007174174 | from scrapy import Spider
from scrapy.selector import Selector
from stack.items import StackItem
with open(r'C:\Users\amarciniak\AppData\Local\Programs\Python\Python35-32\Scripts\stack\stack\spiders\links.txt') as f:
linkList = f.read().splitlines()
class StackSpider(Spider):
name = "sta... | AdamMarciniak/SuperCrawler2 | stack/stack/spiders/stack_spider.py | stack_spider.py | py | 973 | python | en | code | 0 | github-code | 6 |
14159077384 | # coding: utf-8
from __future__ import unicode_literals
from django.db import models
from .utils import get_models_from_file
class DynamicModelManager(models.Manager):
def __init__(self, model, instance=None):
super(DynamicModelManager, self).__init__()
self.model = model
self.instance = i... | ToxicWar/travail-de-tests | testtask/models.py | models.py | py | 2,767 | python | en | code | 0 | github-code | 6 |
43899986443 | import os
import test
import shutil
import unittest
from xml.dom import minidom
from xmp import XMP
class XMPTestCase(unittest.TestCase):
"""Tests for `xmp.py`."""
def test_decode_tag_size(self):
"""decode_tag_size - Read section size from byte pair"""
self.assertEqual(XMP.decode_tag_size(b'\... | ntieman/blender-facebook-360 | test/test_xmp.py | test_xmp.py | py | 3,506 | python | en | code | 1 | github-code | 6 |
44501822840 | from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, FloatField, IntegerField, FileField, validators
class DishForm(FlaskForm):
name = StringField('Name', [
validators.DataRequired(),
validators.Length(min=2, max=100)
])
description = TextAreaField('Description', ... | stroud91/DietCrusherProject | app/forms/dishes.py | dishes.py | py | 668 | python | en | code | 0 | github-code | 6 |
25682902949 | from mylib.lib import extract, load, query, transform, start_spark, end_spark
def main():
extract()
spark = start_spark("WorldCupPred")
df = load(spark)
query(spark, df)
transform(df)
end_spark(spark)
if __name__ == "__main__":
main() | nogibjj/706_Week10_YL | main.py | main.py | py | 264 | python | en | code | 0 | github-code | 6 |
27946258189 | import time
from scrubber_test_base import TestWithScrubber
from telemetry_test_base import TestWithTelemetry
class TestScrubberEvictWithAggregation(TestWithScrubber, TestWithTelemetry):
# pylint: disable=too-many-ancestors
"""Inject Checksum Fault with scrubber enabled
and scrubber threshold set to a ce... | grom72/daos | src/tests/ftest/scrubber/aggregation.py | aggregation.py | py | 3,034 | python | en | code | null | github-code | 6 |
24543970329 | import sys
polymers = sys.stdin.read().strip()
def test(a, b):
if a.lower() != b.lower():
# A does not equal B at all
return False
if a.lower() == a and b.upper() == b:
return True
if a.upper() == a and b.lower() == b:
return True
return False
def collaps(polymers):
... | jonaskrogell/adventofcode2018 | 5.py | 5.py | py | 1,481 | python | en | code | 0 | github-code | 6 |
40883369274 | import sys
from kubernetes import client, config
pods_templates = [
"authservice-",
"cluster-local-",
"istio-citadel-",
"istio-galley-",
"istio-ingressgateway-",
"istio-nodeagent-",
"istio-pilot-",
"istio-policy-",
"istio-security-post-install-",
"istio-sidecar-injector-",
"... | dzhyrov/private-manifests-1.3 | private-manifests/utils/pods-validator.py | pods-validator.py | py | 1,763 | python | en | code | 0 | github-code | 6 |
74636959546 | """Following: https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/"""
import unittest
import numpy as np
from grad.core import Tensor, Graph, Op
from grad.nn import Linear, Sigmoid, MSELoss, SGD, Network
class Model(Op):
def __init__(self):
super().__init__()
w1 = np.array(... | akv17/grad | tests/native/test_train.py | test_train.py | py | 1,874 | python | en | code | 0 | github-code | 6 |
16474430323 | from rest_framework import serializers
from .models import Quizzes, Question, Answer,Score
class QuizSerializer(serializers.ModelSerializer):
class Meta:
model = Quizzes
fields = [
'title','id'
]
class ScoreSerializer(serializers.ModelSerializer):
user = serializers.ReadOn... | Rinz-Code/Fasalu-Rahman-Portfolio | server/quiz/serializers.py | serializers.py | py | 2,218 | python | en | code | 1 | github-code | 6 |
18805694678 | # 6 - Crie um programa que use uma iteração para exibir elementos da
# lista gerada no exercício 4 presentes em posições de índice ímpares:
import random
lista = []
contador = 0
while contador < 10:
n = random.randint(10, 1580)
lista.append(n)
contador += 1
for i in range(1, len(lista), 2):
print(f'... | chrystian-souza/exercicios_em_python | exerciciosAula4/exercicio06.py | exercicio06.py | py | 345 | python | pt | code | 0 | github-code | 6 |
29497895962 | from utils.flask.app import app
from utils.db import Book
from flask import request, jsonify
import json
@app.route('/updatespitslot', methods=['GET', 'POST'])
def upload_spitslotinfo():
data = json.loads(request.get_data(as_text=True))
if data['key'] != 'updatespitslot' or 'stu_uuid' not in data.keys() or 'i... | Emanual20/StuinfoDisplayProject | server/utils/router/spitslot.py | spitslot.py | py | 1,062 | python | en | code | 0 | github-code | 6 |
70911317947 | # -*- coding: utf-8 -*-
import scrapy
class AmazonBooksSpiderSpider(scrapy.Spider):
name = 'amazon_books_spider'
# allowed_domains = ['amazon.com']
start_urls = ['https://www.amazon.com/s?i=stripbooks&bbn=283155&rh=n%3A283155%2Cp_n_publication_date%3A1250226011%2Cp_n_feature_browse-bin%3A618073011&s=revie... | ArRosid/Scrapy-Project | scrapy_project/spiders/amazon_books_spider.py | amazon_books_spider.py | py | 1,322 | python | en | code | 1 | github-code | 6 |
24577754108 | import random
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.... | david-ajax/LGSpider-HydroOJ | main.py | main.py | py | 3,329 | python | en | code | 1 | github-code | 6 |
27641421937 | # by filtering stock that is in the range of 0.5 to 2 pct difference
import os
from dotenv import load_dotenv
load_dotenv()
import os
from supabase import create_client
import numpy as np
import pandas as pd
import requests
from datetime import datetime
from io import StringIO
def preprocess_numeric_value(value):
... | supertypeai/sectors_forecast_growth_rate | code/main_v2.py | main_v2.py | py | 7,738 | python | en | code | 0 | github-code | 6 |
11370435084 | import torch
import torchvision
import gym
import random
import torch.nn as nn
import torch
from torch.autograd import Variable
import torch.autograd as autograd
import torch.nn.functional as F
import gym
import random
import heapq
from gym.envs.registration import register
register(
id='FrozenLakeNotSlippery-v0... | ssainz/reinforcement_learning_algorithms | non_jupyter/Frozen_Lake_Actor_Critic_Batch_NoReplacement.py | Frozen_Lake_Actor_Critic_Batch_NoReplacement.py | py | 17,568 | python | en | code | 0 | github-code | 6 |
7233973656 | import os
import json
import numpy as np
from ortools.sat.python import cp_model
def solve(all_block, wafer_width, wafer_height):
### wafer sampling
# Number of blocks
n = len(all_block)
# wafer Variables
all_wafer_x_st, all_wafer_y_st, all_wafer_x_ed, all_wafer_y_ed, sampled = [], [], [], [], []
... | Jerry-Github-Cloud/OR-Tools-Code | AdvacneProcess/advance_process_1.py | advance_process_1.py | py | 7,607 | python | en | code | 0 | github-code | 6 |
36025296586 | from QAgent import QAgent
import random
import tensorflow as tf
import numpy as np
class NStepQAgent(QAgent):
"""
Asynchronous Methods for Deep Reinforcement Learning
Args:
_model (function): necessary,
return: 1. q func output op, output's dim should be equal with num of actions
... | ppaanngggg/DeepRL | DeepRL/Agent/NStepQAgent.py | NStepQAgent.py | py | 2,903 | python | en | code | 29 | github-code | 6 |
40014308279 | from collections import deque
class Cell:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
class Node:
def __init__(self, pt: Cell, dist: int):
self.pt = pt
self.dist = dist
def is_valid(r, c, tr, tc):
return (r >= 0) and (r < tr) and (c >= 0) and (c < tc)
de... | asmitak11/sample-project | main.py | main.py | py | 1,391 | python | en | code | 0 | github-code | 6 |
9224541444 | from flask import Flask
from flask import request, jsonify
import json, os, util, pickle
app = Flask(__name__)
SIMULATION_RESULT_PATH = './sim_result'
from flask_cors import CORS
CORS(app)
def load(path):
with open(path, 'rb') as f:
obj = pickle.load(f)
return obj
@app.route("/")
def hello_world():
... | Tsinghua-MARS-Lab/InterSim | simulator/dashboard_server.py | dashboard_server.py | py | 5,757 | python | en | code | 119 | github-code | 6 |
45386146936 | """
Serialize data to/from JSON
"""
# Avoid shadowing the standard library json module
from __future__ import absolute_import
from __future__ import unicode_literals
import datetime
import decimal
import json
import sys
from theory.core.serializers.base import DeserializationError
from theory.core.serializers.python... | grapemix/theory | theory/core/serializers/json.py | json.py | py | 3,323 | python | en | code | 1 | github-code | 6 |
13225566797 | from scitools.std import *
import ODESolver
def f(u, t):
return -u
solver = ODESolver.ForwardEuler(f)
solver.set_initial_condition(1.0)
t_points = linspace(0, 3, 31)
u, t = solver.solve(t_points)
plot(t, u)
# Test various dt values and plot
figure()
T = 3
for dt in 2.0, 1.0, 0.5, 0.1:
n = int(round(T/dt))
... | hplgit/scipro-primer | src-3rd/ode2/app1_decay.py | app1_decay.py | py | 1,319 | python | en | code | 181 | github-code | 6 |
70112160829 | import tensorflow as tf
import re
INITIALIZER_FULLY = tf.contrib.layers.xavier_initializer()
INITIALIZER_CON2D = tf.contrib.layers.xavier_initializer_conv2d()
BATCH_SIZE = 128
IMAGE_SIZE = 224
NUM_CLASSES = 10
NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 50000
NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 10000
MOVING_AVERAGE_DECAY = 0.9... | CTGU-SINO/MachineLearning | tensorflow_example/cnn.py | cnn.py | py | 11,298 | python | en | code | 0 | github-code | 6 |
13284399667 | """
https://leetcode.com/problems/powx-n/
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
-100.0 < x < 100.0
n ... | lancerdancer/leetcode_practice | code/binary_search/50_pow(x,n).py | 50_pow(x,n).py | py | 686 | python | en | code | 1 | github-code | 6 |
40688406143 | import unittest
import warnings
from concurrent.futures import Future
from lte.protos.mconfig.mconfigs_pb2 import PipelineD
from magma.pipelined.app.arp import ArpController
from magma.pipelined.bridge_util import BridgeTools
from magma.pipelined.openflow.registers import DIRECTION_REG, Direction
from magma.pipelined.... | magma/magma | lte/gateway/python/magma/pipelined/tests/test_arp.py | test_arp.py | py | 6,698 | python | en | code | 1,605 | github-code | 6 |
39159138446 | from numpy import squeeze, real, mean, pi, float16, array, float16, reshape, float32
from scipy import ndimage as ndi
from skimage.filters import gabor_kernel
from skimage.feature import hog
from skimage import feature
import cv2
import numpy as np
from skimage.transform import rescale, resize, downscale_local_mean
imp... | NaghmeNazer/diabetes-iridology | featureExtraction.py | featureExtraction.py | py | 3,245 | python | en | code | 6 | github-code | 6 |
26403083200 | #
# GaussSum (http://gausssum.sf.net)
# Copyright (C) 2006-2013 Noel O'Boyle <baoilleach@gmail.com>
#
# This program is free software; you can redistribute and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any... | gausssum/gausssum | src/gausssum/geoopt.py | geoopt.py | py | 2,004 | python | en | code | 2 | github-code | 6 |
73505701627 | # coding=utf-8
#
# /**************************************************************************
# ***
# *** File Author: Dell, 2018年 09月 18日 星期二 16:28:12 CST
# ***
# **************************************************************************/
#
import os
import sys
import logging
import argparse
import model
parser = ... | delldu/ImageCNN | train.py | train.py | py | 1,707 | python | en | code | 4 | github-code | 6 |
7276069541 | import pandas as pd
"""
# read in LABR.csv as a dataframe
df_labr = pd.read_csv('LABR.csv', usecols=['OVERALL', 'PICK', 'PLAYER', 'MLB', 'POS', 'BID', 'TEAM', 'OWNER'])
# read in IDMAP.csv as a dataframe
df_idmap = pd.read_csv('IDMAP.csv', usecols=['FANTPROSNAME', 'IDFANGRAPHS'])
# merge the two dataframes on the 'P... | camarcano/labr | labr-boards.py | labr-boards.py | py | 4,130 | python | en | code | 0 | github-code | 6 |
3019098857 |
def hamiltonianoVA(g, sol, sol_f, nodo):
if len(g) + 1 == len(sol) and nodo == sol[0]:
sol_f.append(sol.copy())
else:
for ady in g[nodo]:
if ady not in sol or (ady == sol[0] and len(sol) == len(g)):
sol.append(ady)
sol_f = hamiltonianoVA(g, sol, sol... | medranoGG/AlgorithmsPython | 06.Backtracking/hamiltoniano.py | hamiltoniano.py | py | 672 | python | en | code | 0 | github-code | 6 |
23364168677 | """Module for parse svg file and return the
position of different elements"""
# Global variables ------------------------------------------------------------
GRAPH_PATH = "../ressources/graphes/"
# Imports ---------------------------------------------------------------------
import os
import random
import xml.etree... | Remyb98/chomp-sur-graphes | src/entity/parser.py | parser.py | py | 4,631 | python | en | code | 0 | github-code | 6 |
72307131709 | import apace as ap
import matplotlib.pyplot as plt
import numpy as np
from fodo import make_fodo
from master_thesis import figure_path
angles = [0, np.pi / 8, np.pi / 4]
fodo = make_fodo(angle=angles[1])
d1, b1, q1, q2 = (fodo[name] for name in ("d1", "b1", "q1", "q2"))
twiss = ap.Twiss(fodo)
steps = 1000
lengths = ... | andreasfelix/master-thesis | code/lattice-design/fodo/necktie_plot.py | necktie_plot.py | py | 1,796 | python | en | code | 0 | github-code | 6 |
1514180995 | import numpy as np
import pandas as pd
import os
import seq_sample
#对一支股的数据进行字段筛选,排序
def clean_stock_data(stock_data):
cols = ['close', 'open', 'high', 'low',
'turnover', 'volume']
stock_data.index = pd.to_datetime(stock_data['date'])
stock_data = stock_data[cols]
stock_data = stock_data.sort_index... | asouxuning/fintech | stock_data.py | stock_data.py | py | 3,044 | python | en | code | 0 | github-code | 6 |
34852978450 | #!/usr/local/bin/python3
# -*- coding: utf-8 -*-
import tkinter as tk
import tkinter.messagebox as msgbox
import tkinter.filedialog as filebox
from tkSimpleDialog import Dialog
from ScrabbleGame import ScrabbleGame, _readLines
from math import cos, sin, pi
import platform
import os
#print(tk.TclVersion, tk.TkVersio... | lenaindelaforetmagique/ScrabbleSolver | src/TKinterface.py | TKinterface.py | py | 24,953 | python | en | code | 0 | github-code | 6 |
24998792911 | import time
from osv import osv
from osv import fields
from tools import config
from tools.translate import _
from datetime import datetime
from datetime import timedelta
class hr_payroll_declar(osv.osv):
'''
Decleration Form
'''
_name = 'hr.payroll.declare'
_description = 'Decleration Form'
... | factorlibre/openerp-extra-6.1 | hr_payroll_declare/hr_payroll_declare.py | hr_payroll_declare.py | py | 7,785 | python | en | code | 9 | github-code | 6 |
41491508331 | # ----------- Import statements ------------
import math;
import numpy;
import matplotlib.pyplot as plt;
# ------------ Custom functions ------------
# A-F sums
def A(xlist, ylist, y_uncert):
A = 0;
for i in range(len(xlist)):
A += xlist[i] / (y_uncert[i])**2;
return A;
def B(xlist, ylist, y_unc... | henryshi1/phy-153 | Homework/hw05/shi_homework05.py | shi_homework05.py | py | 5,372 | python | en | code | 0 | github-code | 6 |
19547650475 | import logging
import multiprocessing
import os
from subprocess import run
from Bio import SeqIO, AlignIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from constants import CD_HIT_CLUSTER_REPS_OUTPUT_FILE, CLUSTERS_NT_SEQS_DIR, CLUSTERS_ALIGNMENTS_DIR, \
NUMBER_OF_PROCESSES, FASTA_FILE_TYPE, ALIGNM... | yarivz/pa-pseudogene | external_tools.py | external_tools.py | py | 9,994 | python | en | code | 0 | github-code | 6 |
4166725370 | address_book = {}
def add_details(name, phone_no, email):
contact = {}
contact["Phone no"] = phone_no
contact["email"] = email
address_book[name] = contact
print(address_book)
def update_detail(args):
print(args)
name = args[0]
phone = args[1]
email = args[2]
if name in addre... | CYBER-DEV-100/nothing | address_book.py | address_book.py | py | 2,011 | python | en | code | 0 | github-code | 6 |
910292070 | import numpy as np
__all__ = ['JustOnceClass', 'just_once', 'Cache']
class JustOnceClass(object):
'''Base class for classes with methods that should never be executed twice.
In typically applications, these methods get called many times, but
only during the first call, an actual computation is ca... | theochem/horton | horton/cache.py | cache.py | py | 11,919 | python | en | code | 83 | github-code | 6 |
74543330428 | # Q22. Write a Python program to create and display all combinations of letters, selecting each letter from a different key in a dictionary. Go to the editor
# Sample data : {'1':['a','b'], '2':['c','d']}
# Expected Output:
# ac
# ad
# bc
# bd
data = {'1':['a','b'],'2':['c','d']}
a = []
for i in data :
a.append(dat... | Jija-sarak/python_dictionary | q22.py | q22.py | py | 448 | python | en | code | 0 | github-code | 6 |
12960757699 | from popsycle import synthetic
import numpy as np
import matplotlib.pyplot as plt
from astropy.table import Table
import h5py
def test_h5_output(extra_col= True):
""""
Parameters
----------
extra_col : boolean, defaults to False
Tells the code whether or not the new h5 file will have ... | jluastro/PopSyCLE | popsycle/tests/test_h5_output.py | test_h5_output.py | py | 2,763 | python | en | code | 13 | github-code | 6 |
26070327512 | import re
from validate_email import validate_email
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
class Email():
EMAIL_FIELDS = ["to", "from"]
FIELDS = "to to_name from from_name subject body".split()
def __init__(self, raw_data):
self.populate_fields(raw_data)
... | jasonwang0/email-service | lib/email.py | email.py | py | 976 | python | en | code | 0 | github-code | 6 |
14095916252 | #!/usr/bin/env python
# coding: utf-8
# In[9]:
import json
with open('file1.json','r') as a:
data1 = a.read()
obj1 = json.loads(data1)
with open('file2.json','r') as a:
data2 = a.read()
obj2 = json.loads(data2)
dlt = {i: obj1[i] for i in obj1 if i in obj2 and obj1[i] != obj2[i]}
if len(dlt):
print ("Есть... | Ventelj/Test-Task | test.py | test.py | py | 471 | python | en | code | 0 | github-code | 6 |
24200669844 | import logging
import threading
import types
from collections import namedtuple
from hashlib import sha256
from time import sleep, time
from goTenna.payload import BinaryPayload, CustomPayload
from termcolor import colored
import config
from utilities import de_segment, naturalsize
logger = logging.getLogger("MSGS"... | willcl-ark/lightningtenna | lightningtenna/messages.py | messages.py | py | 5,494 | python | en | code | 10 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.