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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
18174761474 | # Dictionaries are written with curly brackets, and have keys and values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
1:'abc'
}
print(thisdict)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
# Duplicate values will overwrite existing values... | Shwetha21031/python_learning | PYTHON/dictionaries.py | dictionaries.py | py | 3,520 | python | en | code | 0 | github-code | 90 |
25525234978 | import matplotlib.pyplot as plt
import matplotlib.style as style
import matplotlib.cm as cm
def scatter(data, xlabel, ylabel, output):
style.use("seaborn-paper")
style.use("ggplot")
palette = [
"#9861bc",
"#61bc6d",
"#6171bc",
"#bcb061",
"#61bcbc",
"#bc9261... | codingjerk/ultimate-compression-benchmark | benchmark/plot.py | plot.py | py | 841 | python | en | code | 0 | github-code | 90 |
15807351657 | # -*- coding: utf-8 -*-
#
# モデル構造を定義します
#
# Pytorchを用いた処理に必要なモジュールをインポート
import torch.nn as nn
# 作成したinitialize.pyの
# 初期化関数 lecun_initialization をインポート
from initialize import lecun_initialization
class MyDNN(nn.Module):
''' Fully connected layer (線形層) によるシンプルなDNN
dim_in: 入力特徴量の次元数
dim_hidden: 隠れ層の次... | ry-takashima/python_asr | 04dnn_hmm/my_model.py | my_model.py | py | 2,145 | python | ja | code | 75 | github-code | 90 |
302614065 | import warnings
from lxml import etree
import myokit
import myokit.formats.mathml
import myokit.formats.cellml as cellml
import myokit.formats.cellml.v2
from myokit.formats.xml import split
def parse_file(path):
"""
Parses a CellML 2.0 model at the given path and returns a
:class:`myokit.formats.cellml... | myokit/myokit | myokit/formats/cellml/v2/_parser.py | _parser.py | py | 29,396 | python | en | code | 29 | github-code | 90 |
11614930245 | import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
#https://gist.github.com/yusugomori/cf7bce19b8e16d57488a
def sigmoid(x):
return 1. / (1 + np.exp(-x))
def tanh(x):
return np.tanh(x)
def softmax(x):
e = np.exp(x - np.max(x))
if e.ndim == 1:
return e / np.sum(e, a... | bachelor10/recurrent-octo-sniffle | visualization/activation_functions.py | activation_functions.py | py | 3,112 | python | en | code | 2 | github-code | 90 |
18430784999 | import math
import collections
import fractions
import itertools
import functools
import operator
import bisect
def lowmod(a, b, mod):
a -= b
if a >= mod:
a -= mod
return a
def solve():
n = int(input())
s = input()
c = collections.Counter(s)
mod = 10**9+7
ans = 1
for i in c... | Aasthaengg/IBMdataset | Python_codes/p03095/s216348603.py | s216348603.py | py | 462 | python | en | code | 0 | github-code | 90 |
44204549251 | import numpy as np
from astropy.io import fits
def construct_response(fits_file_dir, fits_arf_dir = None, min_val = 1.e-6):
'''
Returns
-------
cin_min, cin_max, cout_min, cout_max, det_res
'''
in_header = 1
out_header = 2
with fits.open(fits_file_dir) as rmf:
# Calculate... | joshwfoster/3p5 | ChandraReduction/response_matrix.py | response_matrix.py | py | 1,697 | python | en | code | 0 | github-code | 90 |
18536224929 | s = input()
k = int(input())
dct = []
for i in range(len(s)):
for j in range(k+1):
word = s[i:i+j]
if word not in dct:
dct.append(word)
dct.sort()
print(dct[k]) | Aasthaengg/IBMdataset | Python_codes/p03353/s898331418.py | s898331418.py | py | 194 | python | en | code | 0 | github-code | 90 |
17050648140 | #! /usr/bin/env python
#
# Author: Dave Grumm (based on work by Tomas Dahlen and Eddie Bergeron)
# Program: makemedmask.py
# Purpose: routine to create median mask for 'Finesky'
# History: 03/04/08 - first version
# 02/23/16 - Use SciPy
from __future__ import absolute_import, division, print_function # confid... | spacetelescope/nictools | nictools/makemedmask.py | makemedmask.py | py | 8,120 | python | en | code | 0 | github-code | 90 |
1633927265 | from sklearn.model_selection import train_test_split
import numpy as np
def read_values(filename):
"""
Reading ARPS (from Nora) .txt files
Input:
path file
Output:
1. Data description as described in the files (entête)
2. Data (2D matrix)
"""
# opening the f... | louisletoumelin/wind_downscaling_cnn | pre_process/utils_preprocess.py | utils_preprocess.py | py | 2,948 | python | en | code | 1 | github-code | 90 |
15527914386 | from uret.core.explorers.graph_explorer import GraphExplorer
from uret.core.rankers import Random
import simanneal
import warnings
import copy
import random
import numpy as np
class SimulatedAnnealingSearchGraphExplorer(GraphExplorer, simanneal.Annealer):
"""
This class implement simulated annealing (random ... | IBM/URET | uret/core/explorers/simmulated_annealing.py | simmulated_annealing.py | py | 13,432 | python | en | code | 22 | github-code | 90 |
6750595099 | import random
shuff=['Rock','Paper','Scissors']
def shuffle():
op=random.choice(shuff)
print(op)
while True:
a=input('Do you want to Play Y/y ?? : ')
if(a=='Y' or 'n'):
shuffle()
else:
break
| MrBinayakB/Python | RockSciStone.py | RockSciStone.py | py | 238 | python | en | code | 2 | github-code | 90 |
2203916832 | class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ''
maxlen=min(list(map(len,strs)))
if maxlen==0:
return ''
for i in range(maxlen):
flag=True
... | zpyao1996/leetcode | longest common prefix.py | longest common prefix.py | py | 616 | python | en | code | 0 | github-code | 90 |
20072225534 | from sklearn.cluster import KMeans
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from itertools import compress
import pickle
from pre_processing import Preprocesser
class Custom_KMeans():
""""
Custom KMeans model. It looks for an optimum K value automatically
... | sotnaSD/WNTAN | backend/clusterization/clustering.py | clustering.py | py | 2,665 | python | en | code | 0 | github-code | 90 |
9376589315 | import SinglyLinkedList
def link_reversal(node):
marker = node
next_marker = None
prev_marker = None
while marker:
next_marker = marker.nextnode
marker.nextnode = prev_marker
prev_marker = marker
marker = next_marker
return prev_marker
a = Si... | amaechichisom/python-datastructure | LinkedList/LinkedListReversal.py | LinkedListReversal.py | py | 474 | python | en | code | 0 | github-code | 90 |
34870004300 | """
Common type operations.
"""
from __future__ import annotations
from typing import (
TYPE_CHECKING,
Any,
Callable,
)
import warnings
import numpy as np
from pandas._libs import (
Interval,
Period,
algos,
lib,
)
from pandas._libs.tslibs import conversion
from pandas.util._exceptions imp... | pandas-dev/pandas | pandas/core/dtypes/common.py | common.py | py | 46,987 | python | en | code | 40,398 | github-code | 90 |
18306515069 | import sys
import itertools
# import numpy as np
import time
import math
sys.setrecursionlimit(10 ** 7)
from collections import defaultdict
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
n = int(input())
A = list(map(int, input().split()))
MOD = 10 ** 9 + 7... | Aasthaengg/IBMdataset | Python_codes/p02838/s213462968.py | s213462968.py | py | 553 | python | en | code | 0 | github-code | 90 |
42706910577 | import json
import http.client as httplib
import spotipy
import spotipy.util as util
def createmix(event, context):
data = json.loads(event['body'])
kwargs = {}
token = data['accesstoken']
genre = data['genres']
kwargs['target_tempo'] = data['bpm']
sp = spotipy.Spotify(auth=token)
... | CraigMcAulay1101/running-app-api | handlers/mix.py | mix.py | py | 799 | python | en | code | 0 | github-code | 90 |
38758913091 | """ NYU-SPS-Summer-2017-Section-2-
Homework assignments for Python class
inout.py
Homework for the first week of our Python class
"""
import sys
while True:
try:
age = input("How old are you: ")
# if EOF or Ctrl-C exit the program...
except EOFError:
sys.exit(0)
except KeyboardInterrupt:
prin... | PeterKoppelman/Python-INFO1-CE9990 | homeowrk week 1.py | homeowrk week 1.py | py | 881 | python | en | code | 0 | github-code | 90 |
18318383349 | from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator impor... | Aasthaengg/IBMdataset | Python_codes/p02855/s906139343.py | s906139343.py | py | 1,508 | python | en | code | 0 | github-code | 90 |
18391007969 | import numpy as np
H, W = map(int, input().split())
S = np.zeros((H,W))
for i in range(H):
Si = np.array([int(s == '.') for s in input()])
S[i] = Si
top = S.copy()
bottom = S.copy()
left = S.copy()
right = S.copy()
for i in range(1, H):
top[i] = (top[i-1] + 1) * S[i]
bottom[-i-1] = (bottom[-i] + 1... | Aasthaengg/IBMdataset | Python_codes/p03014/s917047413.py | s917047413.py | py | 512 | python | en | code | 0 | github-code | 90 |
32316433106 | #!/usr/bin/env python3
import xml.etree.ElementTree as ET
import os
import argparse
import zipfile
response_template_success = '''<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<ns2:response xmlns:ns2="http://umms.fms.gov.ru/hotel/hotel-response" xmlns="http://www.w3.org/2000/09/xmldsig#" schemaVersion="1.0"... | scalar438/mvd_test_scripts | check_consistency.py | check_consistency.py | py | 3,587 | python | en | code | 0 | github-code | 90 |
19847470724 | # -*- coding: utf-8 -*-
"""Console script for pyidea."""
import click
from pyidea.pyidea import create_idea, save_idea, list_ideas
from pyidea.pyidea import complete_idea
from pyidea.pyidea import idea_callback
@click.command()
@click.option("--show", "-s", is_flag=True, help="List all saved ideas.")
@click.option("... | madelyneriksen/PyIdea | pyidea/cli.py | cli.py | py | 1,461 | python | en | code | 0 | github-code | 90 |
17217419995 | import ctypes
import re
from ctypes import *
from ctypes import wintypes
from ctypes.wintypes import HWND, CHAR, LPSTR
def convert_wildcard_to_regex(wildcard):
"""
Converts wildcard to regex.
:param str wildcard: wildcard.
:rtype: str
:return: regex pattern.
"""
regex = re.escape(wildcar... | letmeNo1/Makima | makima/windows/utils/common.py | common.py | py | 3,968 | python | en | code | 14 | github-code | 90 |
6934981152 | import sqlite3
from sqlite3 import Error
from utility.tools import Resources
import os
import logging
from collections import namedtuple
logger = logging.getLogger('warband_builder.db_loader')
class DatabaseAPI():
database = Resources().resource_path(r"resources\Burrows&Badgers.db")
def __init__(self):
self.table... | flanagan-niall/warband-builder-interface | db_api.py | db_api.py | py | 2,314 | python | en | code | 0 | github-code | 90 |
6199817602 | from Customer import Customer
from Account import Account
class DataSource:
customers = []
def datasource_conn(self):
f = open("BankApplication/Data.txt")
true = True
string = "Connection successfull"
name = f.name
tuple = (true, string, name)
f.close()
... | Levophobia/Assignments | Python BankApplication/DataSource.py | DataSource.py | py | 4,394 | python | en | code | 0 | github-code | 90 |
17997388339 | from sys import stdin
a,b,c = [int(x) for x in stdin.readline().strip().split()]
l = 0
mem = []
while(True):
if sum([a%2, b%2, c%2]) > 0:
break
elif [a,b,c] in mem:
l = -1
break
else:
l += 1
mem.append([a,b,c])
a_tmp = b/2 + c/2
b_tmp = a/2 + c/2
c_tmp = a/2 + b/2
a,b,c = a_t... | Aasthaengg/IBMdataset | Python_codes/p03723/s295328327.py | s295328327.py | py | 348 | python | en | code | 0 | github-code | 90 |
12998440205 | """
/**
* @author agond
* @package main.slidingWindow.medium
* @Date 24/09/2023
* @Project PracticeDSA
* <p>
* 1052. Grumpy Bookstore Owner
* Hint
* There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store.
* You are given an integer array customers... | akashgond3112/PracticeDsaPython | src/slidingWindow/medium/GrumpyBookstoreOwner.py | GrumpyBookstoreOwner.py | py | 2,986 | python | en | code | 1 | github-code | 90 |
21464359870 | import speech_recognition as sr
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language='pl-PL')
pri... | MichalkapDeveloper/T.R.Y.B.I.K. | recognizer.py | recognizer.py | py | 485 | python | en | code | 0 | github-code | 90 |
74035786218 | # Imports
import math
import json
from pathfinding.finder.finder import Finder
from pathfinding.core.grid import Grid
from pathfinding.finder.a_star import AStarFinder
from pathfinding.core.diagonal_movement import DiagonalMovement
# Initializations
def calc_cost(self, node_a, node_b):
"""
Get the cost (absol... | LuigiLegion/deimosy-backend | utils.py | utils.py | py | 2,896 | python | en | code | 0 | github-code | 90 |
18756702550 | import os, sys, inspect
# Mpi cant be started in subdirectory, or to be more specific, can't import custom module
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
print(sys.path)
from loguru import logger
from ... | simonhauck/MPI_NEAT | code/src/mpi_tutorial/mpi_example_communication.py | mpi_example_communication.py | py | 2,803 | python | en | code | 3 | github-code | 90 |
40026564836 | class Solution:
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
for i in range(len(board)):
for j in range(len(board[0])):
if self.dfs(i,j,board,word):
return True
... | lanpartis/LeetCodePractice | 79.py | 79.py | py | 807 | python | en | code | 0 | github-code | 90 |
1902483340 | import cv2 as cv
import math
## Blue color filter
lowBlue = (85, 60, 45);
upBlue = (130, 255, 255);
## Yellow spots
lowYellow = (25, 75, 91);
upYellow = (35, 255, 255);
## Using a video as input
file = "../testInput/bordA/20210531_170354.mp4"
capture = cv.VideoCapture(cv.samples.findFileOrKeep(file))
if not capture.... | riturajsingh2015/ws2020-infm2300-teamprojekt-darts-tracker | dartstracker/src/test/resources/scripts/blue_dart_tracking.py | blue_dart_tracking.py | py | 2,715 | python | en | code | 0 | github-code | 90 |
20052236216 | # -*- coding:utf-8 -*-
#输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
#把一个整数减去1,再和原整数做与运算,会把该整数最右边的1变成0.
#判断是不是2的整数次方。若是,只有有一个1,其余皆为0.所以只要判断经过一次减一再与自己的与远算之后是不是为0.
#判断两数不同的位数,只需要先异或,不同的则为真“1”,再统计1的个数。
class Solution:
def NumberOf1(self, n):
# write code here
count=0
if n<0:
n=n& 0xff... | shirleychangyuanyuan/SwordToOfferByPython | 15(2)-两数不同的位数.py | 15(2)-两数不同的位数.py | py | 932 | python | zh | code | 0 | github-code | 90 |
30948113577 | import tensorflow as tf
from working_memory_model import WorkingMemoryModel
import random
from tensorflow.keras import activations, losses
def make_flashing_mod_game(num_flashes, mod, period = 4):
flashes = []
labels = []
# averaging period
# flashes += [[0.0, random.random(), random.random(), random... | BCheng-KH/working_memory_experiment | model_test_functions.py | model_test_functions.py | py | 3,256 | python | en | code | 1 | github-code | 90 |
10620337563 | import pandas as pd #the pandas libary is one we use when building dataframes
#--------------this is our dictionary of four receivers from the 2021 draft-----------------
receiverclassof2021 = {
"Team": ["Cincinnati Bengals", "Philadelphia Eagles", "Miami Dolphins", "New York Jets"],
"Player": ["Jamar Chase",... | Jhorton0899/Python-Basics | 2021draft.py | 2021draft.py | py | 2,993 | python | en | code | 0 | github-code | 90 |
22238270182 | import pandas
def unify_registed_client_end(s):
if s is None:
return 0
s = s.strip().lower()
if s == 'ios':
return 3
elif s == 'android':
return 2
elif s == 'h5':
return 1
else:
return 0
def unify_phone_brand(s):
if s is None:
return 'OTH'
... | forestyaser/Risk_Control | src/main/utils/helpers.py | helpers.py | py | 5,790 | python | en | code | 0 | github-code | 90 |
70175371177 | def insertion_sort(arr):
def sortedList(l, x):
newList = []
inserted = False
for z in l:
if not inserted:
if x<z:
newList.append(x)
inserted = True
newList.append(z)
if not inserted:
newList.a... | dineshkumarsarangapani/leetcode-solutions | python/source/iitm/computation_thinking/insertionSort_onSpace.py | insertionSort_onSpace.py | py | 539 | python | en | code | 1 | github-code | 90 |
14757729882 | import logging
from linotp.lib.util import getParam
import datetime
optional = True
required = False
from linotp.lib.tokenclass import TokenClass
from linotp.lib.dpwOTP import dpwOtp
from linotp.lib.config import getFromConfig
from linotp.lib.error import TokenAdminError
log = logging.getLogger(__name__)
... | rb12345/Elm | linotpd/src/linotp/lib/tokens/tagespassworttoken.py | tagespassworttoken.py | py | 5,839 | python | en | code | 0 | github-code | 90 |
28486989534 | import requests
import json
import configparser
from datetime import datetime
from web3.auto import w3
from eth_account.messages import defunct_hash_message
print("Automate piedpipercoin (PPI-ETH)")
print("-----------------------------------")
# Read configuration (ETH Address and PrivateKey)
print("-----------------... | sanjaychandak/DDEX_PPI | src/DDEXCreateOrder.py | DDEXCreateOrder.py | py | 3,264 | python | en | code | 3 | github-code | 90 |
25300617206 | #
# @lc app=leetcode.cn id=566 lang=python3
#
# [566] 重塑矩阵
#
# @lc code=start
class Solution:
# 本题的思路很简单,遍历所有元素,c个元素为一组截取即可。
# 注:在本题的解题过程中,遇到了python内存机制相关的问题,
# 由于每次sub_list都需要加入到new_mat中去,而受python引用
# 机制的影响,new_mat中加入的其实是sub_list所指向对象的引用,
# 当时用sub_list.clear()时会将sub_list所引用对象清空,导致
... | HughTang/Leetcode-Python | Array and Matrix/566.重塑矩阵.py | 566.重塑矩阵.py | py | 1,652 | python | zh | code | 0 | github-code | 90 |
74729189735 | """
Utilities for testing
Some adapted from https://serge-m.github.io/testing-json-responses-in-Flask-REST-apps-with-pytest.html
"""
import json
from os import environ
import jwt
from bs4 import BeautifulSoup
def create_jwt(user_id):
""" Create JSON Web Token and decode to string """
token = jwt.enco... | gilmoreg/legocollector | server/tests/testutils.py | testutils.py | py | 3,434 | python | en | code | 0 | github-code | 90 |
32810306347 | import os
patches_num = 40000
from Tools import shuffle_array
import shutil
def selected_patches(source_dir, target_dir, num_limited):
names = os.listdir(source_dir)
names = shuffle_array(names)
names = names[:num_limited]
paths = [os.path.join(source_dir, name) for name in names]
for path in paths... | UpCoder/ICPR2018 | LeaningBased/BoVW_DualDict/selected_patches.py | selected_patches.py | py | 1,055 | python | en | code | 2 | github-code | 90 |
8564236066 | # -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
#from scrapy.utils.response import open_in_browser
class BestMoviesSpider(CrawlSpider):
name = 'best_movies'
allowed_domains = ['imdb.com']
start_urls = ['https://www.imdb.com/... | ritik-attri/Web-scraping-using-Scrapy | spiders/best_movies.py | best_movies.py | py | 991 | python | en | code | 0 | github-code | 90 |
24564622530 | from lzstring import LZString
from AzurLaneToolLib.data import data_AZR_Lan as data_AZR_Lan
comp_teur_comp = LZString.compressToEncodedURIComponent
dic_ship_data = data_AZR_Lan.dic_ksen_data
def fun_maks_code():
list_ksdt = []
stri_lskd = str(list_ksdt)
kasn_code = comp_teur_comp(stri_lskd)
return ... | thedayofthedoctor/altl | AzurLaneToolLib/mode/mode_FLE_Tol.py | mode_FLE_Tol.py | py | 330 | python | en | code | 2 | github-code | 90 |
19583630071 | import os
import sys
import socket
import smtplib
import logging
import unittest
import importlib.util
from configparser import ConfigParser
from functools import wraps
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from selenium im... | sylgdxsgx/IsliTest | base/function.py | function.py | py | 11,224 | python | en | code | 0 | github-code | 90 |
71509255977 | import time
from datetime import datetime, timedelta
from info import constants, db
from info.models import User, News, Category
from info.modules.admin import admin_blu
from flask import request
from flask import render_template, current_app, session, redirect, url_for, g, jsonify, abort
# 新闻后台用户登陆功能实现
from info.ut... | liudiyilalala/Xinjing-information-network | info/modules/admin/views.py | views.py | py | 15,267 | python | en | code | 0 | github-code | 90 |
38004655927 | class Banco(object):
def __init__(self, total, taxa_reserva, reserva_exigida):
self.__total = total
self.taxa_reserva = taxa_reserva
self.__reserva_exigida = reserva_exigida
def __calcular_reserva(self):
reserva = self.__total * self.taxa_reserva
return reserva
def podeFazerEmprestimo(self, ... | mariomendonca/Solving-problems-python | orientação_a_objetos/exe02.py | exe02.py | py | 493 | python | pt | code | 1 | github-code | 90 |
17437402810 | """
A pangram is a sentence that contains every single letter of
the alphabet at least once. For example, the sentence
"The quick brown fox jumps over the lazy dog" is a pangram,
because it uses the letters A-Z at least once (case is irrelevant).
Given a string, detect whether or not it is a pangram. Return True
if it... | Ristani/Codewars-Katas | kyu-06/detect-pangram.py | detect-pangram.py | py | 809 | python | en | code | 0 | github-code | 90 |
38108551867 | # -*- coding:utf-8 -*-
# Copyright (C) 2021- BOUFFALO LAB (NANJING) CO., LTD.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the ... | llamaonaskateboard/bflb-mcu-tool | bflb_mcu_tool/libs/bflb_efuse_boothd_create.py | bflb_efuse_boothd_create.py | py | 12,690 | python | en | code | 4 | github-code | 90 |
19500358435 | import connection
@connection.connection_handler
def get_question_for_index(cursor):
cursor.execute("""
SELECT id, submission_time, view_number, title, message FROM question
ORDER BY submission_time DESC;
""")
question_data = cursor.fetchall()
... | CodecoolBP20173/wswp-ask-mate-dork-side-of-the-moon | data_manager.py | data_manager.py | py | 9,943 | python | en | code | 0 | github-code | 90 |
34336413210 | #!/usr/bin/env python3
"""Real time plot of potato loads"""
import collections
import datetime
import matplotlib
import matplotlib.dates as dates
import matplotlib.pyplot as plt
import re
import seaborn
import subprocess
import time
def get_loads():
"""Gets the loads of the potatoes as a list"""
cmd = ['pssh... | byu-aml-lab/window | plot_load.py | plot_load.py | py | 1,891 | python | en | code | 0 | github-code | 90 |
71574952297 | from django.urls import path
from auth.views import LoginAPIVIEW, LogoutAPIView, AuthStatusAPIView
urlpatterns = [
path("login", LoginAPIVIEW.as_view(), name="login"),
path("logout", LogoutAPIView.as_view(), name="logout"),
path("status", AuthStatusAPIView.as_view(), name="auth-status"),
]
| jumakiwaka/msgraph | BEE/auth/urls.py | urls.py | py | 306 | python | en | code | 0 | github-code | 90 |
18533715159 | N = int(input())
X = [int(input()) for _ in range(N)]
if X[0]:
print(-1)
exit()
ans = 0
for i in range(1, N):
if X[i] == X[i-1] + 1:
ans += 1
elif X[i] > X[i-1] + 1:
print(-1)
exit()
else:
ans += X[i]
print(ans) | Aasthaengg/IBMdataset | Python_codes/p03347/s814977106.py | s814977106.py | py | 264 | python | en | code | 0 | github-code | 90 |
73821320617 | from ast import Import
from turtle import Turtle, position
ALIGNMENT = "center"
FONT = ("Arial", 24, 'normal')
class ScoreBoard(Turtle):
def __init__(self):
self.score = 0
self.high_score = 0
# with open("data.txt") as file:
# print(file.read())
# self.high_score = i... | Harryalways317/100-days-of-python | 14-SnakeGame/scoreboard.py | scoreboard.py | py | 1,267 | python | en | code | 0 | github-code | 90 |
2941283407 | """
Max Consecutive Ones
Given a binary array nums, return the maximum number of consecutive 1's in the array.
Example 1:
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Example 2:
Input: nums = [1,0,1,1,... | shilleroleg/LeetCode | src/arrays/max_consecutive_ones.py | max_consecutive_ones.py | py | 1,237 | python | en | code | 0 | github-code | 90 |
18011454349 | def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
divisors.sort()
return divisors
x=int(input())
ans=float('inf')
for i in make_divisors(x):
a,b=i,x//i
a,b=... | Aasthaengg/IBMdataset | Python_codes/p03775/s712358590.py | s712358590.py | py | 382 | python | en | code | 0 | github-code | 90 |
18589317459 | n = int(input())
a = list(map(int,input().split()))
ans = 0
flag = False
while flag == False:
for i in range(n):
if a[i]%2 == 0:
a[i] /= 2
else:
flag = True
break
else:
ans += 1
print(ans) | Aasthaengg/IBMdataset | Python_codes/p03494/s663726545.py | s663726545.py | py | 258 | python | en | code | 0 | github-code | 90 |
27097340838 | from spack import *
class Uberftp(AutotoolsPackage):
"""UberFTP is an interactive (text-based) client for GridFTP"""
homepage = "http://toolkit.globus.org/grid_software/data/uberftp.php"
url = "https://github.com/JasonAlt/UberFTP/archive/Version_2_8.tar.gz"
version('2_8', 'bc7a159955a9c4b9f5f42... | matzke1/spack | var/spack/repos/builtin/packages/uberftp/package.py | package.py | py | 478 | python | en | code | 2 | github-code | 90 |
381799514 | # Source: https://medium.com/@abhishek.bn93/using-keras-reinforcement-learning-api-with-openai-gym-6c2a35036c83
import os
from tensorflow import uint32
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.models import Sequential
from tensorflow.python.keras import Input
import gym_snake
from rl.ag... | MaZeeT/MultiAgentRL | CustomSnake_SARSA/SARSA_model.py | SARSA_model.py | py | 1,862 | python | en | code | 0 | github-code | 90 |
11530838075 | import discord
import html
from discord.channel import VoiceChannel
from discord.player import FFmpegPCMAudio
from google.cloud import texttospeech
import re
from submodule import token
Discord_TOKEN = token.Discord_TOKEN
client = discord.Client()
voiceChannel: VoiceChannel
messageChannel = None
@client.event
async... | owandog/DiscordBotTTS | DiscordBotTTS.py | DiscordBotTTS.py | py | 3,520 | python | en | code | 1 | github-code | 90 |
36013305566 | userfirstline = input()
usersplit = userfirstline.split()
orders = int(usersplit[0])
watertank = int(usersplit[1])
orders_fufiled = 1
waterRefilCounter = 0
waterRefil = watertank
while int(orders_fufiled) <= int(orders):
orders_fufiled += 1
userOrder = input("")
userOrder += " "
waterUsed = 0
if userOrder[1] ... | sushiboytr/KattisSolutions | espresso.py | espresso.py | py | 566 | python | en | code | 0 | github-code | 90 |
20706398489 | from collections import Counter
''' Here my first solution. It is not as efficient as it could be '''
def number_needed2(a, b):
"""
Given two strings, consisting of lowercase English alphabetic letters, determine the minimum number of character deletions required to make them anagrams. Any characters can be d... | fantauzzi/Cracking_the_Coding_Interview | strings_making_anagrams.py | strings_making_anagrams.py | py | 1,894 | python | en | code | 0 | github-code | 90 |
18401671129 | N, M = map(int, input().split())
A = list(map(int, input().split()))
A = sorted(A, reverse = True)
bc = [0] * M
for i in range(M):
bc[i] = list(map(int, input().split()))
bc = sorted(bc, key = lambda x:x[1], reverse = True)
#めぐる式二分探索
#indexが条件を満たすか判定
def isOK(index, key, A):
if A[index] < key:
return True
e... | Aasthaengg/IBMdataset | Python_codes/p03038/s116800821.py | s116800821.py | py | 1,126 | python | en | code | 0 | github-code | 90 |
1442248632 | def isMatch(word, pattern, d, i=0, j=0):
if not word or not pattern:
return False
n = len(word)
m = len(pattern)
if n < m:
return False
if i == n and j == m:
return True
if i == n or j == m:
return False
curr = pattern[j]
if curr in d:
s = ... | aggagah/tubes-SA | backtrack.py | backtrack.py | py | 919 | python | en | code | 1 | github-code | 90 |
18052301999 | import math
N = int(input())
t,a = [],[]
for _ in range(N):
t_tmp, a_tmp = map(int, input().split())
t.append(t_tmp)
a.append(a_tmp)
T,A=1,1
for i in range(N):
n = max(-(-A//a[i]), -(-T//t[i]))
A = a[i] * n
T = t[i] * n
print(A+T) | Aasthaengg/IBMdataset | Python_codes/p03964/s332475279.py | s332475279.py | py | 240 | python | en | code | 0 | github-code | 90 |
16410417307 | # image_segmentation.py
"""Volume 1A: Image Segmentation.
Alexandra Hurst
Math 345
11/4/16
"""
from matplotlib import pyplot as plt
import numpy as np
from scipy import linalg as la
from scipy import sparse
from scipy.sparse import csgraph
from scipy.sparse import spdiags
from scipy.sparse.linalg import eigsh
# Probl... | alexandrarhurst/code_sample | python_scripts/image_segmentation.py | image_segmentation.py | py | 7,020 | python | en | code | 0 | github-code | 90 |
28748538161 | fin=open("photo.in")
fout=open("photo.out","w")
n=int(fin.readline().strip())
ref=[i for i in range(1,n+1)]
arr=list(map(int,fin.readline().strip().split()))
test=arr[0]
for i in range(1,test):
if test%2==0 and i==test//2:
continue
check=[i]
curr=i
for j in arr:
check.append(... | SriramV739/CP | USACO/Contest/Bronze/2020January/photo.py | photo.py | py | 570 | python | en | code | 0 | github-code | 90 |
7993003958 | import torch
import torch.nn as nn
import torch.nn.functional as F
class EncoderRNN(nn.Module):
def __init__(self, input_size: int, hidden_size: int):
super(EncoderRNN, self).__init__()
self.hidden_size = hidden_size
self.embedding = nn.Embedding(input_size, hidden_size)
self.gru ... | DunZhang/NLPGeneration | 01RNN_Seq2Seq_Translation/EncoderDecoder.py | EncoderDecoder.py | py | 2,676 | python | en | code | 2 | github-code | 90 |
1849242936 | import sys
input = sys.stdin.readline
INF = sys.maxsize
# float('inf')는 음수를 더해도 갱신되지 않음
N, M = map(int, input().split())
costs = []
dist = [INF] * (N+1)
for _ in range(M):
A, B, C = map(int, input().split())
costs.append((A,B,C))
def bellman(start):
dist[start] = 0
for i in range(N):
fo... | GANGESHOTTEOK/yaman-algorithm | 09_Bellman-Ford/AN/BOJ11657.py | BOJ11657.py | py | 677 | python | en | code | 2 | github-code | 90 |
18303647529 | n,u,v=map(int,input().split())
u-=1
v-=1
e=[[]for _ in range(n)]
for i in range(n-1):
a,b=map(int,input().split())
a-=1
b-=1
e[a].append(b)
e[b].append(a)
cho=[u]
cho_dis=[10**7]*n
cho_dis[u]=0
cho_visited={u}
countt=1
while cho:
CHO=[]
for i in cho:
for j in e[i]:
if j in cho_visited:continue
... | Aasthaengg/IBMdataset | Python_codes/p02834/s662268715.py | s662268715.py | py | 743 | python | en | code | 0 | github-code | 90 |
23267902493 | from fastapi import HTTPException
from sqlalchemy.orm import Session
from app.core.product import select_product_by_id, insert_product, select_product_by_sku, update_product
from app.models.entities.product import Product
from app.schemas.product_schema import ProductSchema
def get_product_id(db: Session, id: int):
... | pak3r5/ia-test | src/app/services/product_service.py | product_service.py | py | 1,601 | python | en | code | 0 | github-code | 90 |
18184655379 | mod=10**9+7
num,k=map(int,input().rstrip().split())
mai=list(map(int, input().rstrip().split()))
main=sorted(mai,key=abs,reverse=True)
result=1
def findplus_plus(x):
for i in range(x,len(main)):
if main[i]>=0:
return main[i]
return ''
def findplus_minus(x):
for i in range(x,len(main)):
... | Aasthaengg/IBMdataset | Python_codes/p02616/s160752910.py | s160752910.py | py | 2,022 | python | en | code | 0 | github-code | 90 |
22717259491 | class Queue:
def __init__(self, capacity):
self.queue = [None for i in range(capacity)]
self.rear = 0
self.length = 0
self.front = 0
self.capacity = capacity
def reverseQueue(self):
stack = Stack(self.length)
while (not self.isEmpty()):
stack.... | Himanshu-Singh-Chauhan/DSA-Programs | Queue.py | Queue.py | py | 855 | python | en | code | 0 | github-code | 90 |
18056436446 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021/1/23 2:10 PM
# @Author: zhangzhihui.wisdom
# @File:stringConvetToInt.py
import re
def stringConvertToInt(s):
strings = s.strip()
if len(strings) > 0:
firstChar = strings[0]
if firstChar == '+' or firstChar == '-':
leftSt... | wisdom2018/stringConvertInteger-python | stringConvetToInt.py | stringConvetToInt.py | py | 1,272 | python | en | code | 0 | github-code | 90 |
3108345784 | #multiple client scripts can be run on the same script on the same machine that the server script is on
import pygame
from network import Network
from player import player
width = 500
height = 500
win = pygame.display.set_mode((width,height))
pygame.display.set_caption("Client")
clientNumber = 0
def read_pos(str):... | soniprajna/exploding-kittens | client.py | client.py | py | 1,314 | python | en | code | 0 | github-code | 90 |
18050287189 | import sys
sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7
def input():
return sys.stdin.readline().strip()
def main():
N = int(input())
T = list(map(int, input().split()))
A = list(map(int, input().split()))
if T[-1] != A[0]:
print(0)
return
# 左からみていく
... | Aasthaengg/IBMdataset | Python_codes/p03959/s875658740.py | s875658740.py | py | 902 | python | en | code | 0 | github-code | 90 |
6621090424 |
def zeroes(height, width):
""" Creates a matrix of zeroes. """
g = [[0.0 for _ in range(width)] for __ in range(height)]
return Matrix(g)
class Matrix(object):
# Initializes a matrix from a 2D grid of values
# Assumes and initializes a grid-specified number of rows and columns
def __ini... | udacity/CVND_Localization_Exercises | 4_5_State_and_Motion/matrix.py | matrix.py | py | 2,136 | python | en | code | 123 | github-code | 90 |
39103633901 | import cv2 as cv
import numpy as np
import pywt as pw
import matplotlib.pyplot as plt
img = 0
img1 = cv.imread('Ruido Periodico 1.jpg', cv.IMREAD_GRAYSCALE)
img2 = cv.imread('Valle de la luna.jpg', cv.IMREAD_GRAYSCALE)
def Wavelet(image, wavelet_name, sigma):
new_coeffs = []
wavelet = pw.Wavelet(wavelet_name)... | XknopiX117/Vision-por-computadora | Transformada Wavelets/EliminarRuido.py | EliminarRuido.py | py | 1,863 | python | en | code | 0 | github-code | 90 |
18756116291 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
sys.path.append('./')
import json
from io import BytesIO
import zipfile
import re
from datetime import datetime
import importlib
import sqlite3
import rrc_evaluation_funcs
from config.config import *
try:
from bottle import route, run, request, st... | clovaai/TedEval | web.py | web.py | py | 19,181 | python | en | code | 171 | github-code | 90 |
15801662305 | # -*- coding: utf-8 -*-
"""
1299. Replace Elements with Greatest Element on Right Side
Given an array arr, replace every element in that array with the greatest element among the elements to its right,
and replace the last element with -1.
After doing so, return the array.
Constraints:
1 <= arr.length <= 10^4
1 <= ... | tjyiiuan/LeetCode | solutions/python3/problem1299.py | problem1299.py | py | 581 | python | en | code | 0 | github-code | 90 |
23475785768 | import time
import myclass2 as mc
#проверяем, граф связный или нет
def isConnected(gr):
marker=[1]*len(gr)
hasNext=True
marker[0]=2
while hasNext:
hasNext=False
for i in range(len(gr)):
if marker[i]==2:
marker[i]=3
hasNext=True
... | genwarhunter/python | lab3/tree_Prim.py | tree_Prim.py | py | 2,289 | python | en | code | 0 | github-code | 90 |
19420336313 | from config import *
from collections import OrderedDict, defaultdict
class Model(nn.Module):
def __init__(self, modelname_or_path, config):
super(Model, self).__init__()
self.config = config
config.update({
"hidden_dropout_prob": 0.0,
"layer_norm_eps": 1e-7,
... | inabakaiso/chaii-comp | chaii_NLP/lstm_transformer_src/cnn_roberta.py | cnn_roberta.py | py | 1,987 | python | en | code | 0 | github-code | 90 |
26174466396 |
# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# This file is licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License. A copy of the
# License is located at
#
# http://aws.amazon.com/apache2.0/
#
# This... | sagarwal10/helloAWS | projects/Babeflow/babeflow-python/src/main/helloTranslate.py | helloTranslate.py | py | 952 | python | en | code | 0 | github-code | 90 |
2042153597 | import subprocess
direccion_ip = "8.8.8.8" # Dirección IP de Google
comando_ping = ["ping", "-n", "4", direccion_ip]
resultado = subprocess.Popen(comando_ping, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
salida_stdout, salida_stderr = resultado.communicate()
# Decodificar la salida en bytes a formato ... | iAmSan76/Ping_tool | exaple_nslookup.py | exaple_nslookup.py | py | 711 | python | es | code | 0 | github-code | 90 |
73939959017 | from fastapi import APIRouter, Depends, Response
from typing import List
from ..database import crud, schemas
from ..dependencies import get_db
from ..utils import auth
router = APIRouter(prefix="/options", tags=["Options"])
@router.get("/", response_model=List[schemas.Option],
summary="Read all option... | Mirea-Ikbo-17-18/anticafe-backend | app/routers/options.py | options.py | py | 704 | python | en | code | 0 | github-code | 90 |
72142232938 | from typing import Dict
import plotly.graph_objs as go
from dao_analyzer.web.apps.common.presentation.charts.layout.figure.figure import Figure
import dao_analyzer.web.apps.common.resources.colors as Color
class BarFigure(Figure):
def __init__(self) -> None:
super().__init__()
super().configurati... | Grasia/dao-analyzer | dao_analyzer/web/apps/common/presentation/charts/layout/figure/bar_figure.py | bar_figure.py | py | 2,167 | python | en | code | 33 | github-code | 90 |
45369338079 | import pandas as pd
import numpy as np
import os
import time
import glob
from keras.utils import np_utils
from tqdm import tqdm
import math
import cv2
import random
class Data:
def __init__(self) -> None:
self.normalization = None
self.img_rows, self.img_cols = None, None
random_state = 51
... | elcio-bardeli/pucpr | modules/data.py | data.py | py | 10,065 | python | en | code | 0 | github-code | 90 |
5448390307 | ####################################
# DIGITS
####################################
DIGITS = '0123456789'
####################################
# ERRORS
####################################
class Error:
def __init__(self, positionStarts, positionEnds, errorName, details):
self.positionStarts = positionSta... | mohit-dubey66/Hindian | interpreter.py | interpreter.py | py | 6,524 | python | en | code | 0 | github-code | 90 |
2179542661 | class Solution:
def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
s_list = list(s)
print(s_list)
track = {}
for l, r in pairs:
if l not in track:
track[l] = set()
track[l].add(l)
track[l].add... | wlyu1208/Leet-Code | 1202-Smallest_String_With_Swaps/code.py | code.py | py | 695 | python | en | code | 1 | github-code | 90 |
27367696682 | # # -*- coding: utf-8 -*-
"""
Provide table manipulation queries:
- create tables
- create index
- delete tables
"""
import asyncio
# user defined formula
from db_management import sql_executing_queries
def catch_error(error, idle: int = None) -> list:
""" """
from utilities import system_tools
system_... | venoajie/MyApp | src/create_db_and_tables_sqlite.py | create_db_and_tables_sqlite.py | py | 1,604 | python | en | code | 2 | github-code | 90 |
34871852330 | import numpy as np
import pytest
import pandas as pd
from pandas import MultiIndex
import pandas._testing as tm
def test_fillna(idx):
# GH 11343
msg = "isna is not defined for MultiIndex"
with pytest.raises(NotImplementedError, match=msg):
idx.fillna(idx[0])
def test_dropna():
# GH 6194
... | pandas-dev/pandas | pandas/tests/indexes/multi/test_missing.py | test_missing.py | py | 3,348 | python | en | code | 40,398 | github-code | 90 |
12578891670 | """Guidebox API calls and functions."""
import os
import requests
from model import connect_to_db, db, User, Show, StreamingService, Favorite, CableListing, Streaming, Network
GUIDEBOX_BASE_URL = "http://api-public.guidebox.com/v1.43/US/"
GUIDEBOX_API_KEY = os.environ.get('GUIDEBOX_API_KEY')
# {Base API URL} /shows... | lindsaynchan/hb_fellowship_final_project | guidebox.py | guidebox.py | py | 3,393 | python | en | code | 0 | github-code | 90 |
12319793560 | import sqlite3
con = sqlite3.connect('exercise_3.db')
cur = con.cursor()
# Create database if not exsits
cur.execute('CREATE TABLE IF NOT EXISTS Numbers (Val INTEGER)')
# Empty database in case it exists
cur.execute('DELETE FROM Numbers')
cur.execute('INSERT INTO Numbers VALUES(1)')
cur.execute('INSERT INTO Numbers... | brianvanburken/playground | python/python/book-practical-programming/ch17/exercise_3.py | exercise_3.py | py | 630 | python | en | code | 3 | github-code | 90 |
18250043899 | def column_check(grp, grp_count, choco, h, j, k):
""" 0:成功(更新も反映) 1:失敗(区切った結果を返す) 2:不可能 """
# この行のグループ毎のカウント
curr_count = [0] * len(grp_count)
# 数える
for i in range(h):
if choco[i][j] == '0':
continue
curr_count[grp[i]] += 1
# この行だけでk越えてたら現在の横の切り方では不可能
for cc in c... | Aasthaengg/IBMdataset | Python_codes/p02733/s229846672.py | s229846672.py | py | 1,547 | python | ja | code | 0 | github-code | 90 |
14724104795 | import json
from unittest import TestCase
from urlparse import parse_qs, urlparse
import responses
from nose.tools import eq_, raises
from marketpulse.base.mozillians import (BadStatusCode, MozilliansClient, ResourceDoesNotExist,
MultipleResourcesReturned)
class TestMozill... | Cloudxtreme/marketpulse | marketpulse/base/tests/test_mozillians.py | test_mozillians.py | py | 5,706 | python | en | code | null | github-code | 90 |
17944155929 | class UnionFind:
def __init__(self, n):
self.parent = [i for i in range(n)]
self.height = [0 for i in range(n)]
def get_root(self, i):
if self.parent[i] == i:
return i
else:
self.parent[i] = self.get_root(self.parent[i])
return self.parent[i]
def unite(self,... | Aasthaengg/IBMdataset | Python_codes/p03575/s342579430.py | s342579430.py | py | 1,168 | python | en | code | 0 | github-code | 90 |
21894937412 | """ Advent of Code, 2015: Day 08, a """
import re
with open(__file__[:-5] + "_input") as f:
inputs = [line.strip() for line in f]
def run():
""" Find the length difference between the strings and their values """
total = 0
for string in inputs:
s = string[1:-1]
s = re.sub(r"\\\\", "s... | nickspoons/adventofcode | python/2015/aoc_08_a.py | aoc_08_a.py | py | 500 | python | en | code | 0 | github-code | 90 |
9212367358 | import yaml
from os import path
def load_config_file(config_filepath, params_class, logger=None):
"""Loads the config file and prepares necessary paths.
Parameters
----------
config_filepath : str
local path to the config file containing all the parameters for training
params_class : objec... | bigmb/mb_tensorflow | mb_tensorflow/params/load_config_file.py | load_config_file.py | py | 2,360 | python | en | code | 0 | github-code | 90 |
17260903914 | import cv2
import numpy as np
import os
ImageFile = os.path.join(os.path.dirname(__file__), 'Resources/Photos/cat.jpg')
assert os.path.exists(ImageFile)
image=cv2.imread(ImageFile)
cv2.imshow('Cat',image)
blank=np.zeros((500,500,3),dtype='uint8') # (heigt,width,color_channel)
cv2.imshow('Blank',blank)
#... | SadettinKayali/OpenCV_EN | EN_opencv1/Part1_Basics_DrawingShapes.py | Part1_Basics_DrawingShapes.py | py | 2,444 | python | tr | code | 0 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.