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
28924497501
""" 프로그래머스 Lv2 -뉴스 클러스터링 """ # 아이디어가 맘에 들었음!@ """ 20 Minute :: flood fill """ from collections import Counter import math def make_window_size2(string): windows = [] for i in range(len(string)-1): if string[i].isalpha() and string[i+1].isalpha(): windows.append(string[i:i+2].lower()) ...
GuSangmo/BOJ_practice
programmers/level2/뉴스클러스터링.py
뉴스클러스터링.py
py
1,199
python
en
code
0
github-code
36
39479742836
# -*- coding: utf-8 -*- from django.urls import path, re_path, include from decks import views from decks.views import TournamentListView urlpatterns = [ re_path(r'^$', views.index, name='index'), re_path(r'^(?P<deck_id>[0-9]+)/$', views.deck, name='deck'), re_path(r'^cluster/(?P<cluster_id>[0-9]+)/$', v...
jcrickmer/mtgdbpy
decks/urls.py
urls.py
py
1,036
python
en
code
0
github-code
36
14102761586
import platform import yaml import pkg_resources import re import logging log = logging.getLogger(__name__) def convert_conda_yaml_to_requirement(conda_array) : ''' Convert the conda.yaml syntax to requirements.txt syntax : for now : - select "dependencies" key - transform = into == ...
nasa/ML-airport-data-services
data_services/conda_environment_test.py
conda_environment_test.py
py
3,612
python
en
code
3
github-code
36
29158315057
# Imports from __future__ import print_function, division import tensorflow as tf import warnings from tensorflow.python.ops import control_flow_ops import numpy as np import pdb # DATA AUGMENTATION **************************************************************************************************** def random_rotati...
ChangqingHui/Semantic-Segmentation-with-Adversarial-Networks
utils.py
utils.py
py
15,349
python
en
code
1
github-code
36
72052572903
# Created by: Younes Elfeitori # Created on: Nov 2017 # Created for: ICS3U # This program selects 10 numbers from 1 to 10 and selects the biigest value from numpy import random def find_max_value(array): # finds largest number max_value = max(array) return max_value # input counter = 0 random_number...
Youneselfeitori/Unit5-02
array_max.py
array_max.py
py
610
python
en
code
0
github-code
36
25417748938
#!/usr/bin/env python import soundfile as sf import math class LoopableSample(): def __init__(self): self.data = [] def addBuffer(self, buffer): for d in buffer: self.data.append(d) def fromFile(self, file): print("loading %s" % file) (data, ignore) = ...
andrewbooker/samplescaper
capture/LoopableSample.py
LoopableSample.py
py
1,055
python
en
code
2
github-code
36
74352481703
# -*- coding: utf-8 -*- """ ------------------------------------------------------------------------------- GUFY - Copyright (c) 2019, Fabian Balzer Distributed under the terms of the GNU General Public License v3.0. The full license is in the file LICENSE.txt, distributed with this software. ----------------...
Fabian-Balzer/GUFY
GUFY/simgui_modules/threading.py
threading.py
py
12,049
python
en
code
0
github-code
36
28242426542
class Solution: def sumOfUnique(self, nums: List[int]) -> int: li = [] re = [] for i in nums: if i not in li: li.append(i) else: if i not in re: re.append(i) nums = [j for j in nums if j not in re] r...
coincidence-one/algorithm-test-prep
week6/1748번_문제/1748_김현진.py
1748_김현진.py
py
335
python
en
code
null
github-code
36
15521857644
''' 85. Maximal Rectangle Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. Example: Input: [ ["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"] ] Output: 6 ''' class Solution: # based on problem 8...
MarshalLeeeeee/myLeetCodes
85-maximalRectangle.py
85-maximalRectangle.py
py
4,569
python
en
code
0
github-code
36
16274525184
# Authors: Clyde Sumagang and Roy Morla # Date: 9/22/ 2019 # Course: CST 205 # Abstract: This program will count the rgb values in a matrix and store them into a dictionary # with 4 bins based on color and intensity import pickle file = open('image_matrix', 'rb') data = pickle.load(file) def task1(data): ...
rjmorla/helloworld
my_Workspace/cst205/hw/hw1/hw1_1.py
hw1_1.py
py
2,104
python
en
code
0
github-code
36
6699714805
def linear_search(data, item): index = 0 found = False while index < len(data): if data[index] == item: found = True else: index += 1 return found, index def binary_search(data, item): first = 0 last = len(data) - 1 found = False while fir...
h3nok/MLIntro
Algorithms/Sorting/search_algorithms.py
search_algorithms.py
py
1,185
python
en
code
0
github-code
36
41120685968
import os from default.liststc import splitter_to_array, add_list, length, convert_arr_to_type, el_in_array delimiter = ';' def write(header, arr, folder_name, file_name, url_file=None): url = url_file url_none = True if not url else False folder_found = False url = '' if url is None: f...
zidane-itb/tubes-daspro
file/csv.py
csv.py
py
4,733
python
id
code
0
github-code
36
9816456408
__title__ = 'pyfcm' __summary__ = 'Python client for FCM - Firebase Cloud Messaging (Android, iOS and Web)' __url__ = 'https://github.com/olucurious/pyfcm' __version__ = '1.5.2' __author__ = 'Emmanuel Adegbite' __email__ = 'olucurious@gmail.com' __license__ = 'MIT License'
olucurious/PyFCM
pyfcm/__meta__.py
__meta__.py
py
277
python
en
code
790
github-code
36
17498728037
import os.path import pandas import numpy as np def opt_report(reportPath, snrTh=0.9, debug=False, plotError=True): df = pandas.read_csv(reportPath) totalNbLoop = list(df["nbLoop"])[-1] # print(totalNbLoop) loopList = [] rmseList = [] avgErrorList = [] for loop_ in range(totalNbLoop + 1):...
SaifAati/Geospatial-COSICorr3D
geoCosiCorr3D/geoTiePoints/misc.py
misc.py
py
4,538
python
en
code
37
github-code
36
4374357755
"""You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?""" """Example 1: Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps""" # goal is two climb to ...
sharmaineb/tech-interview
climbingstairs.py
climbingstairs.py
py
1,722
python
en
code
0
github-code
36
26613373403
from sklearn.linear_model import LogisticRegression import pandas as pd import numpy as np from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix, classification_report import seaborn as sn import matplotlib.pyplot as plt data = pd.read_csv('./Data/wine.csv') data = data.sample(frac=1,...
larocaroja/Advanced-Programming
Logistic Regression.py
Logistic Regression.py
py
2,652
python
en
code
0
github-code
36
26175621630
from distutils.core import setup, Extension from Cython.Build import cythonize include_dirs_list = [ "../include", "../Thirdparty/libccd/src", #libccd "../Thirdparty/libccd/build/src", #libccd "../Thirdparty/yaml-cpp/include", # yaml-cpp...
hfutcgncas/mpl_cpp
cython/setup.py
setup.py
py
1,152
python
en
code
1
github-code
36
23296850783
from pathlib import Path import pandas as pd from . import integration from model import advanced_controls as ac from model import aez from model import dd from model import vma from model import world_land from solution import factory standard_land_allocation_types = list(world_land.AEZ_ALLOCATION_MAP.keys()) + ["Ad...
ProjectDrawdown/solutions
integrations/aez_land_integration.py
aez_land_integration.py
py
3,975
python
en
code
203
github-code
36
28870151431
class Node: def __init__(self, data=None): self.data = data self.next = None self.previous = None class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def prepend(self, data): new_node = Node(data) if self.head is None: ...
almamuncsit/Data-Structures-and-Algorithms
Data-Structure/13-doubly-linked-list.py
13-doubly-linked-list.py
py
2,766
python
en
code
5
github-code
36
36332628382
import csv import pandas as pd import numpy as np data = pd.read_csv("insurance.csv") ages = [] sexes = [] bmis = [] num_children = [] smoker_statuses = [] regions = [] insurance_charges = [] def load_list_to_data(lst, csv_file, column_name): # open csv file with open(csv_file) as csv_info: ...
Sorunlu00/Project-US-Insurance-Cost
Medical_Insurance_cost.py
Medical_Insurance_cost.py
py
8,296
python
en
code
0
github-code
36
72027268583
cookbook = {'sandwich' : {'ingredients' : ['ham', 'bread', 'cheese', \ 'tomatoes'] , 'meal' : 'lunch', 'prep_time' : 10}, \ 'cake' : {'ingredients' : ['flour', 'sugar', 'eggs'] , 'meal' : 'dessert', \ 'prep_time' : 60}, \ 'salad' : {'ingredients' : ['avocado', 'arugula', 'tomatoes', 'spinach'] , \ 'meal' : 'lunch', 'p...
GabPillow/python_bootcamp
day00/ex06/recipe.py
recipe.py
py
3,347
python
en
code
0
github-code
36
4414438763
s = input() n = len(s) k ="keyence" flg = 1 # はじめて違う文字を見つけたら、マイナスインデックスで後ろからも同時に見ていく(かしこい…) for i in range(7): if s[i] != k[i]: if s[-7+i] != k[-7+i]: flg = 0 break print('YES' if flg else 'NO') # -- ダメだったコード -- # OKなパターンは3つ # 1.keyencexxx # 2.xxxkeyence # 3.keyxxxence など、頭とお尻に分かれてるパターン # 分かれてるパタ...
burioden/atcoder
submissions/keyence2019/b.py
b.py
py
937
python
ja
code
4
github-code
36
26740758351
#!/usr/bin/env python import glob, os, sys, subprocess, shutil, string, argparse parser = argparse.ArgumentParser(description="Wrapper script for MakePlots_HTopMultilep.py. This gets called on the PBS worker node via the PBS script generated by submit-PBS-ARRAY-MakePlots_HTopMultilep.py. The variable to be plotted ge...
mmilesi/HTopMultilepAnalysis
PlotUtils/Scripts/wrapper-MakePlots_HTopMultilep-PBS.py
wrapper-MakePlots_HTopMultilep-PBS.py
py
2,258
python
en
code
0
github-code
36
18316576813
import functools import inspect import types from typing import Dict, List, Optional, Type, Union import pytest import servo.utilities.inspect class OneClass: def one(self) -> None: ... def two(self) -> None: ... def three(self) -> None: ... class TwoClass(OneClass): def ...
opsani/servox
tests/utilities/inspect_test.py
inspect_test.py
py
9,377
python
en
code
6
github-code
36
3382979841
class Solution: def findMin(self, nums: List[int]) -> int: start , end = 0 ,len(nums) - 1 curr_min = float("inf") while start < end : mid = (start + end ) // 2 curr_min = min(curr_min,nums[mid]) # right has the min if ...
neetcode-gh/leetcode
python/0153-find-minimum-in-rotated-sorted-array.py
0153-find-minimum-in-rotated-sorted-array.py
py
532
python
en
code
4,208
github-code
36
10495557667
from dateutil import rrule import datetime # 算两个时间的月数 def months_calculte(begin,end): begin += '-01' end += '-01' d1 = datetime.datetime.strptime(begin,'%Y-%m-%d') d2 = datetime.datetime.strptime(end,'%Y-%m-%d') # d2 = datetime.date(2017, 4) months = rrule.rrule(rrule.MONTHLY, dtstart=d1, until=...
rantengfei/python-utility
compute_time.py
compute_time.py
py
3,098
python
en
code
0
github-code
36
4109086257
import sys n, m = [int(x) for x in input().split()] one, two = 0, 0 for i in range(1, m + 1): a, b, c, d = [int(x) for x in input().split()] one += a * b two += c * d if one >= n and two >= n: print(f"It's a tie at round {i}!") sys.exit() if one >= n: print(f"Team 1 wins at r...
AAZZAZRON/DMOJ-Solutions
ucrpc21c.py
ucrpc21c.py
py
447
python
en
code
1
github-code
36
19573707796
import os def getVariantspath(modelPath,reportfname): """list dirs in modelPath in order to get variant names and its folder path""" vnames = [name for name in os.listdir(modelPath) if os.path.isdir(os.path.join(modelPath,name))] vpath = [os.path.join(modelPath,name) for name in os.listdir(modelPath) ...
vhoangTS/LizardParallelPlot
reportWriter.py
reportWriter.py
py
3,626
python
en
code
0
github-code
36
38817077412
import requests import random from dotenv import load_dotenv from PIL import ImageTk, Image from io import BytesIO import tkinter as tk import os class FetchAPI(): query: str quantity: int img_width: int img_height: int load_dotenv() api_key = os.getenv('PEX...
yethuhlaing/Car-Rental
src/fetchAPI.py
fetchAPI.py
py
2,071
python
en
code
0
github-code
36
8385928022
from django.db.models import Model, Q, OuterRef, Max, Count from django.conf import settings from django.core import mail from django.http import HttpResponse from django.template import Context, Template, loader from django.utils.translation import gettext_lazy as _ from django.contrib import admin import os, glob fro...
johncronan/formative
formative/utils.py
utils.py
py
9,508
python
en
code
4
github-code
36
70068023143
import random def randomquote(quotes): last = len(quotes) -1 rnd = random.randint(0,last) print("Random Quote: ",quotes[rnd]) f = open("quotes.txt") quotes = f.readlines() f.close() selection = "A" while True: selection = input("(D)isplay a quote\n(A)dd a quote\nChoose your selection by typing in the lette...
EricJB77/python-random-quote
get-quote.py
get-quote.py
py
705
python
en
code
0
github-code
36
9766193824
import sys import librosa import numpy as np #import soundfile as sf import functools import torch #from torch.nn.functional import cosine_similarity #import essentia.standard as es def logme(f): @functools.wraps(f) def wrapped(*args, **kwargs): print('\n-----------------\n') print(' MODEL: ...
andrebola/contrastive-mir-learning
utils.py
utils.py
py
7,635
python
en
code
13
github-code
36
27479201010
def read(): with open("input/02.txt") as f: return [x.split() for x in f.read().split('\n')[:-1]] def part1(m): r = [0, 0] for x, y in m: if x == 'forward': r[0] += int(y) elif x == 'up': r[1] -= int(y) elif x == 'down': r[1] += int(y) ...
MergunFrimen/advent-of-code
2021/02/02.py
02.py
py
653
python
en
code
0
github-code
36
43767535683
# -*- coding: utf-8 -*- # @Time : 2020/8/19 11:17 # @Author : WuatAnt # @File : ext_gcd.py # @Project : Python数据结构与算法分析 def ext_gcd(x,y): if y == 0: return (x,1,0) else: (d,a,b) = ext_gcd(y,x%y) return (d,b,a-(x//y)*b) print(ext_gcd(25,9))
WustAnt/Python-Algorithm
Chapter8/8.3/8.3.3/ext_gcd.py
ext_gcd.py
py
297
python
en
code
9
github-code
36
6951210977
import argparse from algorithms.utils import timedcall @timedcall def count_inversions(array): _, inversions = _count_inversions(array) return inversions def _count_inversions(array): if len(array) < 2: return array, 0 mid = len(array) // 2 left, left_inversions = _count_inversions(arra...
dfridman1/algorithms-coursera
algorithms/divide_and_conquer/week2/inversions.py
inversions.py
py
1,642
python
en
code
0
github-code
36
17567691479
from inpladesys.datatypes import Segment, Segmentation from typing import List import numpy as np from inpladesys.datatypes.dataset import Dataset from collections import Counter from sklearn.model_selection import train_test_split import time import scipy.stats as st def generate_segmentation(preprocessed_documents: ...
Coolcumber/inpladesys
software/inpladesys/models/misc/misc.py
misc.py
py
5,944
python
en
code
3
github-code
36
5043460289
"""Methods for playing the game from the value iteration agent.""" from DeepQLearningAgent import * from QLearningAgent import * from DoubleQLearningAgent import * episodes = 100 def play_q(env: JoypadSpace, args, actions): """Play the game using the Q-learning agent.""" agent: QLearningAgent = QLearningAgen...
astelmach01/Mario-Q_Learning
play.py
play.py
py
1,955
python
en
code
1
github-code
36
74160099303
#!/bin/python3 import os import sys # # Complete the getMoneySpent function below. # def getMoneySpent(keyboards, drives, b): keyboards = sorted([each_keyboards for each_keyboards in keyboards if each_keyboards < b], reverse = True) drives = sorted([each_drives for each_drives in drives if each_drives < b], r...
CodingProgrammer/HackerRank_Python
(Implementation)Electronics_Shop.py
(Implementation)Electronics_Shop.py
py
1,134
python
en
code
0
github-code
36
42910133147
from pymongo import MongoClient import time client = MongoClient('localhost', 27017) db = client['sahamyab'] series_collection = db['tweets'] start_time = time.time() series_collection.update_many( {'hashtags':{'$in': ['فولاد', 'شستا', 'شبندر'] }}, {'$set':{'gov': True }}) end_time = tim...
masoudrahimi39/Big-Data-Hands-On-Projects
NoSQL Databases (Cassandra, MongoDB, Neo4j, Elasticsearch)/MongoDB/1000 twiits/game3_2.py
game3_2.py
py
397
python
en
code
0
github-code
36
70891763304
# -*- coding: utf-8 -*- from __future__ import division from __future__ import print_function import ojfdb #import ojfresult #import ojfpostproc import towercal import yawcal import bladecal import ojf_freeyaw def rebuild_symlink_database(): # first, rebuild the symlink list: all files in one folder # this ...
davidovitch/freeyaw-ojf-wt-tests
rebuild.py
rebuild.py
py
1,755
python
en
code
2
github-code
36
14248952393
from collections import deque #올바른 괄호열인지 판단 하는 함수 def isCorrect(p): lst = [] #문자열의 문자를 하나하나 담을 lst for i in range(len(p)): if p[i] == '(': # 만약 열린 괄호이면 리스트에 넣는다. lst.append(p[i]) elif p[i] == ')': # 만약 닫힌 괄호라면 if len(lst) == 0: # 닫힌 괄호인데 lst가 빈 상태라면 retur...
vmfaldwntjd/Algorithm
Programmers/DFS,BFS/괄호 변환/Programmers.py
Programmers.py
py
2,869
python
ko
code
0
github-code
36
38558826717
import tkinter as tk import random import time class Ball: def __init__(self, _x, _y, _r, vx, vy, a_x=0, a_y=0, color='black'): self.x_acceleration = a_x self.y_acceleration = a_y self.v_x = vx self.v_y = vy self.x = _x self.y = _y self.r = _r ...
MitiaKorotkov/infa_2019_korotkov
laba4_2.py
laba4_2.py
py
6,091
python
en
code
0
github-code
36
32058377252
from heapq import heappop, heappush, heapify def solution(scoville, K): answer = 0 heapify(scoville) while scoville[0] < K and len(scoville) >= 2: first = heappop(scoville) second = heappop(scoville) heappush(scoville, first+(second*2)) answer += 1 if scoville[0]...
back1ash/solving_problem
coding_test/programmers/더 맵게.py
더 맵게.py
py
367
python
en
code
0
github-code
36
947147182
pkgname = "rxvt-unicode" pkgver = "9.31" pkgrel = 1 build_style = "gnu_configure" configure_args = [ "--with-terminfo=/usr/share/terminfo", "--with-term=rxvt-unicode-256color", "--enable-256-color", "--enable-font-styles", "--enable-keepscrolling", "--enable-startup-notification", "--enable-...
chimera-linux/cports
contrib/rxvt-unicode/template.py
template.py
py
1,956
python
en
code
119
github-code
36
28798514201
def main(): print("This program will calculate your BMI and tell whether it's above, below, or within the healthy range.") weight = int(input("What is your weight in pounds?")) height = int(input("What is your height?")) finalheight = height ** 2 bmi = (weight * 720) / finalheight finalbmi = str...
Eric-Wonbin-Sang/CS110Manager
2020F_hw6_submissions/mehtaom/OmCH7P1.py
OmCH7P1.py
py
539
python
en
code
0
github-code
36
36750215907
from flask import (g, abort, get_flashed_messages, request, flash, redirect, url_for) from sqlalchemy.sql import functions from buddyup.app import app from buddyup.database import (Course, Visit, User, BuddyInvitation, Location, Major, Event, Language, db) from buddyup...
thangatran/Buddy-Up
buddyup/pages/admin.py
admin.py
py
5,477
python
en
code
0
github-code
36
27511260267
# -*- coding: utf-8 -*- """ Created on Mo 12 Sept 2 13:15:51 2022 @author: FKAM """ import pandas as pd import streamlit as st import plotly.express as px import plotly.graph_objs as go #import altair as alt #from bokeh.plotting import figure def list_ext(uploads, radio3): list_ = [] header_default = ["date...
KempiG/Master
PVD_funcs.py
PVD_funcs.py
py
11,030
python
en
code
0
github-code
36
20510556949
from __future__ import print_function import numpy as np import ad3.factor_graph as fg import time def test_random_instance(n): costs = np.random.rand(n) budget = np.sum(costs) * np.random.rand() scores = np.random.randn(n) tic = time.clock() x = solve_lp_knapsack_ad3(scores, costs, budget) t...
andre-martins/AD3
examples/python/example_knapsack.py
example_knapsack.py
py
2,835
python
en
code
68
github-code
36
34222159351
from django.shortcuts import render, redirect from .models import Aricle from .forms import ArticleForm def new(request): if request.method == 'POST': article_form = ArticleForm(request.POST) if article_form.is_valid(): article = article_form.save() return redirect('blog:de...
kimhyunso/exampleCode
django/MTV/blog/new_views.py
new_views.py
py
542
python
en
code
0
github-code
36
31553967278
from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import PorterStemmer import json import string import re ps = PorterStemmer() punctuation = list(string.punctuation) stop = stopwords.words('english') + punctuation + ['rt', '#rt', '#follow', 'via', 'donald', 'trump', '…', "trump...
henrydambanemuya/socialsensing
ConflictSensingApp/TextNormalizer.py
TextNormalizer.py
py
1,705
python
en
code
0
github-code
36
2847150673
# Qus: https://leetcode.com/problems/maximal-network-rank/ # time complexity O(N**2) class Solution(object): def maximalNetworkRank(self, n, roads): """ :type n: int :type roads: List[List[int]] :rtype: int """ graph = {} for i in range(n): graph...
mohitsinghnegi1/CodingQuestions
Leetcode Everyday challenge/Maximal Network Rank.py
Maximal Network Rank.py
py
825
python
en
code
2
github-code
36
20436716291
# pxy7896@foxmail.com # 2020/8/1 __doc__ = """ 获取中公教育每日一练内容;获取国务院政府工作报告。 """ import requests from bs4 import BeautifulSoup import os # 服务器反爬虫机制会判断客户端请求头中的User-Agent是否来源于真实浏览器,所以,我们使用Requests经常会指定UA伪装成浏览器发起请求 headers = {'user-agent': 'Mozilla/5.0'} # 写文件 def writedoc(raw_ss, i, ii): # 打开文件 ...
pxy7896/PlayWithPython3
获取某网站每日一练.py
获取某网站每日一练.py
py
4,447
python
zh
code
0
github-code
36
23856814731
from collections import deque GENERATOR = 0 MICROCHIP = 1 floors = [[] for _ in range(4)] elev = 0 elems = dict() def is_safe(arrangement): floors, _ = arrangement for floor in floors: chips = set() hasg = False for e in floor: if e & 1 == MICROCHIP: chips....
mahiuchun/adventofcode-2016
day11/part2.py
part2.py
py
3,739
python
en
code
0
github-code
36
19041324588
# Author: Trevor Sherrard # Since: Feb. 21, 2022 # Purpose: This file contains functionallity needed to run inference on a single image import cv2 import numpy as np import tensorflow as tf import keras # declare file paths model_file_loc = "../../models/saved_unet_model.h5" test_image_loc = "../../dataset/semantic_d...
Post-Obstruction-Assessment-Capstone/Drone-Road-Segmentation
utils/deep_learning/single_image_inference.py
single_image_inference.py
py
1,599
python
en
code
0
github-code
36
8444405928
import cupy import cupyx.scipy.fft from cupy import _core from cupy._core import _routines_math as _math from cupy._core import fusion from cupy.lib import stride_tricks import numpy _dot_kernel = _core.ReductionKernel( 'T x1, T x2', 'T y', 'x1 * x2', 'a + b', 'y = a', '0', 'dot_product'...
cupy/cupy
cupy/_math/misc.py
misc.py
py
16,182
python
en
code
7,341
github-code
36
29052565706
import cryptoFunc choice = input('Please type 1 for encrypt or 2 for decrypt: ') file = input('Please give me a file name: ') if choice == '1': cryptoFunc.encrypt_file(file) elif choice == '2': cryptoFunc.decrypt_file(file) print('Successfull')
Akeon201/FED
main.py
main.py
py
265
python
en
code
0
github-code
36
12814302696
# 곱하기 혹은 더하기 / p312 input = input() result = 0 for i in input: if i == '0': continue if i == '1': result += 1 continue if result == 0: result += int(i) else: result *= int(i) print(result)
Girin7716/PythonCoding
pythonBook/Problem Solving/Q2.py
Q2.py
py
268
python
ko
code
1
github-code
36
37459633466
#Clases y funciones #classes = [] #for i in range(10): # class Dummy: # def init(self, _name): # self._name = 'Dummy {}'.format(i) # # classes.append(Dummy) #for item in classes: # dummy = item() # print(dummy.name) #print("Hello World") class Student: univ...
DiegoPaez2/POO-2963
Workshop/First partial/Workshop05/classes and functions.py
classes and functions.py
py
1,255
python
en
code
0
github-code
36
32933105911
import numpy as np from PIL import Image rainbow = np.zeros((521,512,3),'uint8') for i in range(0,256): rainbow[:,i,0] = 255-i rainbow[:,i,1] = 0+i for i in range(256,512): rainbow[:,i,1] = 255-i rainbow[:,i,2] = 0+i image = Image.fromarray(rainbow) image.save('rainbow.jpg')
hieumewmew/MultimediaCommunicationExam
bai5/rainbow.py
rainbow.py
py
299
python
en
code
0
github-code
36
28482960968
import pandas as pd import numpy as np import os, sys import warnings import matplotlib.pyplot as plt import gmplot from sklearn.cluster import DBSCAN import random import json def remove_invalid_coord(df): #[-90; 90] #return df.query('lat >= -90 & lat <= 90').query('lon >= -90 & lat <= 90') return df.query('lat !=...
lucaslzl/ponche
timewindow/lookdata.py
lookdata.py
py
5,789
python
en
code
0
github-code
36
23702793306
# This is just a sample program to show you how to do # basic image operations using python and the Pillow library. # # By Eriya Terada, based on earlier code by Stefan Lee, # lightly modified by David Crandall, 2020 # Import the Image and ImageFilter classes from PIL (Pillow) from PIL import Image, ImageFilter, I...
dhruvabhavsar/Optical-Music-Recognition
python-sample/omr.py
omr.py
py
13,907
python
en
code
0
github-code
36
23930369932
import sys import threading lastId = 0 #Ids used for object pointers class aObject: def __init__(self, name, value, type): global lastId self.name = name self.value = value self.aType = type self.id = lastId + 1 self.attributes = {} lastId += 1 class aString(aObject): def __init__(self, name, va...
Krobix/Ametscript
ametscript/classes.py
classes.py
py
1,956
python
en
code
1
github-code
36
38568510649
def dfs(graph, node, visited, stack): visited.add(node) for neighbor in graph[node]: if neighbor not in visited: dfs(graph, neighbor, visited, stack) stack.append(node) return stack def topological_order(edges, n): graph = dict() for i in range(1, n+1): graph[i] = ...
archanakalburgi/Algorithms
summer_prep/graphs/topological_dfs.py
topological_dfs.py
py
822
python
en
code
1
github-code
36
41703057518
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('portfolio', '0006_auto_20160109_0000'), ] operations = [ migrations.CreateModel( name='Blog', fields...
zachswift615/zachswift
portfolio/migrations/0007_blog.py
0007_blog.py
py
701
python
en
code
0
github-code
36
9390236732
n = int(input('Digite um número: ')) verificador = 1 if (n / 2).is_integer() == False and n != 1 and n != 0: verificador = 0 for c in range(2, n): n2 = n / c if n2.is_integer(): verificador = 1 if verificador == 0: print('Esse número é primo!') else: print('Esse número não é ...
github-felipe/ExerciciosEmPython-cursoemvideo
PythonExercicios/ex052.py
ex052.py
py
335
python
pt
code
0
github-code
36
16411706948
import os import shutil import numpy as np import cv2 import random import copy from keras.models import Sequential from keras.layers.core import Dense, Flatten, Dropout import tensorflow as tf def qpixmap_to_array(qtpixmap): # qpixmap转换成array img = qtpixmap.toImage() temp_shape = (img.height(), img.byte...
zhangxinzhou/game_explorer
game01_dino/new_test/game_utils.py
game_utils.py
py
5,865
python
en
code
0
github-code
36
10401144210
#!/usr/bin/env python """ Testtool om een lokale HTTP server te starten die verbinding maakt met dvs-daemon. Niet geschikt voor productie! Gebruik daar WSGI voor. """ import bottle import argparse import dvs_http_interface import logging # Initialiseer argparse parser = argparse.ArgumentParser(description='DVS HTTP ...
PaulWagener/rdt-infoplus-dvs
dvs-http.py
dvs-http.py
py
906
python
nl
code
null
github-code
36
43891173362
def fatorial(num=1, show=False): """ :param num: Número para ser fatorado :param show: Mostar o processo sa fatoração :return: Resultado da fatoração """ f = 1 for c in range(num, 0, -1): if show: print(c, end='') if c > 1: print(' x ', end='')...
Kaue-Romero/Python_Repository
Exercícios/exerc_102.py
exerc_102.py
py
484
python
pt
code
0
github-code
36
7111352063
import urllib import urllib2 from django import template from django.conf import settings from django.template.defaultfilters import truncatewords from django.utils.html import strip_tags from django.utils.safestring import mark_safe from utils.acm_auth import get_ip register = template.Library() def fix_trunc(te...
mnadifi/cie
source/apps/articles/templatetags.py
templatetags.py
py
2,209
python
en
code
0
github-code
36
17013425141
import datetime from lambda_function import handler from components import line_bot_api from utils import utils_database from linebot.models import ( JoinEvent, MemberJoinedEvent, MemberLeftEvent, TextSendMessage ) @handler.add(JoinEvent) def handle_join(event): group_id = event.source.group_id ...
jialiang8931/WRA06-Volunteer-LineBot
src/components/handler_event_group.py
handler_event_group.py
py
2,658
python
en
code
0
github-code
36
70562644584
import sys from bisect import bisect_left input = sys.stdin.readline N = int(input().rstrip()) nums = list(map(int, input().rstrip().split())) dp = [] def change(ary, num): ''' :param ary: dp 배열 :param num: 대치할 수 num보다 큰 수 중 최솟값과 대치 (이진탐색 이용) :return: None ''' low, high = 0, len(ary) ...
zsmalla/algorithm-jistudy-season1
src/chapter5/다이나믹프로그래밍(1)/임지수/12015_python_임지수.py
12015_python_임지수.py
py
791
python
ko
code
0
github-code
36
17236751533
# Дано натуральное число n (n ≥ 10). Напишите программу, которая определяет его максимальную и минимальную цифры. n = int(input()) max = 0 min = n % 10 while n != 0: last_digit = n % 10 if last_digit > max: max = last_digit if last_digit < min: min = last_digit n = n // 10 print('Макс...
i-kasparova/gloacademy_python
Lesson_8/task_4.py
task_4.py
py
517
python
ru
code
0
github-code
36
32538066028
# -*- coding: utf-8 -*- """ Created on Sat May 5 10:53:26 2018 @author: lenovo """ import numpy as np from scipy.optimize import leastsq def fun(p,x): """定义想要拟合的函数""" k,b = p return k*x+b def err(p,x,y): """定义误差函数""" return fun(p,x)-y x = [1,2,3,4] y = [6,5,7,10] p0 = ...
wilsonzyp/probability_statistics
Try_leastsq_with_scipy.py
Try_leastsq_with_scipy.py
py
446
python
en
code
1
github-code
36
22354796740
from django.shortcuts import render from remarcable_app.models import SearchHistory from remarcable_app.query_functions import ( delete_old_searches, pull_all_products, pull_all_tagged_products, pull_all_categories, pull_all_tags, products_to_array, search_products, tags_to_dictionary, ...
stephenv13/remarcableproject
remarcable_app/views.py
views.py
py
5,899
python
en
code
0
github-code
36
28841930639
import pygame, sys, time, random from pygame.locals import * pygame.init() mainClock = pygame.time.Clock() lives = 3 lives2 = 3 width = 800 height = 600 windowSurface = pygame.display.set_mode((width, height), 0, 32) pygame.display.set_caption('Star Wars!') movementSpeed = 10 projectileSpeed = 30 scrollSpeed = 6 ia...
Noah04322/Assignments
End of Year.py
End of Year.py
py
23,466
python
en
code
0
github-code
36
26703340293
import speech_recognition as sr import wave import sys import os import uuid pcmfn = sys.argv[1] wavefn = os.path.join(str(uuid.uuid4().hex)) with open(pcmfn, 'rb') as pcm: pcmdata = pcm.read() with wave.open(wavefn, 'wb') as wavfile: #convert pcm to wav wavfile.setparams((2, 2, 48000, 0, 'NONE', 'NONE')) ...
nfsmith/DiscordStenographer
transcribePCM.py
transcribePCM.py
py
586
python
en
code
0
github-code
36
23063800044
from src.pipeline.predict_pipeline import camera from src.utils import emotion_average import spotipy from spotipy.oauth2 import SpotifyClientCredentials from src.utils import normalize from src.utils import string from src.exception import CustomException import sys import pandas as pd def recommender(emotion,preferen...
AnshulDubey1/Music-Recommendation
src/pipeline/song_predictor.py
song_predictor.py
py
2,474
python
en
code
5
github-code
36
33830156345
import pandas as pd class Lista: def __init__(self): self.planilha_original = pd.read_excel("senhas.xlsx") self.df_original = pd.DataFrame(self.planilha_original) # CRIA O DATAFRAME ORIGINAL def busca_login(self, nome): self.reload() if nome in [i for i in self.planilha_origi...
riatoso/sistemaDeLoginExcel
login.py
login.py
py
1,934
python
pt
code
0
github-code
36
18082073278
#!/usr/bin/env python """ Neato control program to make a robot follow a line (like a roadway) and react to signs in its path. """ import rospy from geometry_msgs.msg import Twist, PoseWithCovariance, Pose, Point, Vector3 from sensor_msgs.msg import LaserScan, Image import math import numpy as np import cv2 from cv_...
lianilychee/project_caribou
scripts/caribou.py
caribou.py
py
6,666
python
en
code
1
github-code
36
40017524881
from scipy.stats import zscore from datetime import datetime as dt import numpy as np import pandas as pd RAW_DIR = "raw/" RAW_TRAIN_PATH = RAW_DIR + "raw_train_data.csv" RAW_PREDICT_PATH = RAW_DIR + "raw_predict_data.csv" CYCLE_AMOUNT_PATH = RAW_DIR + "cycle_amount.csv" INPUT_DIR = "input/" TRAIN_DATA_PATH = INPUT_D...
ytorii/park-amount
wdnn/raw_to_input_csv.py
raw_to_input_csv.py
py
5,411
python
en
code
0
github-code
36
16810461794
import json from django.contrib import messages from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from django.core import serializers from django.core.files.uploadhandler import FileUploadHandler from django.core.urlresolvers import reverse from django.http im...
SeanKapus/Fashion
outfit/views.py
views.py
py
3,292
python
en
code
0
github-code
36
16968857057
#-*- coding: utf-8 -*- from __future__ import unicode_literals from operator import __or__ as OR from functools import reduce import six from django.conf import settings try: from django.utils.encoding import force_unicode as force_text except ImportError: from django.utils.encoding import force_text from dj...
infolabs/django-edw
backend/edw/admin/base_actions/update_terms.py
update_terms.py
py
3,011
python
en
code
6
github-code
36
28523093007
# Opus/UrbanSim urban simulation software. # Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.logger import logger from urbansim.estimation.estimation_runner import EstimationRunner as UrbansimEstimationRunner from washtenaw...
psrc/urbansim
washtenaw/estimation/run_estimation.py
run_estimation.py
py
2,802
python
en
code
4
github-code
36
19608346992
# PROBLEM: # Given an array A of non-negative integers, return an array # consisting of all the even elements of A, followed by all # the odd elements of A. # You may return any answer array that satisfies this condition. # EXAMPLE: # Input: [3,1,2,4] # Output: [2,4,3,1] # The outputs [4,2,3,1], [2,4,1,3], and [4,...
angiereyes99/coding-interview-practice
easy-problems/SortArrayByParity.py
SortArrayByParity.py
py
1,364
python
en
code
0
github-code
36
27139316721
# References for fixed parameters: # https://therideshareguy.com/uber-statistics/ # wikipedia uber_drivers_worldwide = 3500000 uber_riders_worldwide = 93000000 initial_riders_ratio = uber_riders_worldwide / uber_drivers_worldwide toledo_population = 270000 saturation_riders = 0.2 * toledo_population saturation_drive...
lorenzobonomi/platformpricesmodel
parameters.py
parameters.py
py
368
python
en
code
0
github-code
36
31280891768
import boto3 import os import botocore import logging from agief_experiment import utils class Cloud: # EC2 instances will be launched into this subnet (in a vpc) subnet_id = 'subnet-0b1a206e' # For ECS, which cluster to use cluster = 'default' # When creating EC2 instances, the root ssh key t...
Cerenaut/run-framework
scripts/run-framework/agief_experiment/cloud.py
cloud.py
py
11,421
python
en
code
2
github-code
36
4005677116
# -*- coding: utf-8 -*- """ Created on Thu Jul 5 16:06:36 2018 @author: jose.molina """ # -*- coding: utf-8 -*- """ Created on Thu Jul 5 15:39:40 2018 @author: jose.molina """ from bs4 import BeautifulSoup from selenium import webdriver import requests from xml.etree import ElementTree from time...
josemolinag/scraping
cosas.py
cosas.py
py
3,820
python
en
code
0
github-code
36
4419617010
""" Simple BBS 簡単な掲示板 要件: 1. ページ上部に大きくSimple BBSと書かれている 2. Username と Messageを入力するフォームがある 3. 送信と書かれたスイッチがある 4. 入力された文字が掲示板に表示されていく(下段に追加されていく) 5. Username に何も入力されていない状態で送信された場合は名無しさんにする 6. Message に何も入力されていない状態で送信された場合は空欄にする """ import os from flask import Flask, render_template, request app = Flask(__name__) @ap...
tetsuya-yamamoto-ai-learn/practice01-F
WebAP.py
WebAP.py
py
2,101
python
ja
code
0
github-code
36
25462981448
import numpy as np import matplotlib.pyplot as plt from scipy.integrate import solve_ivp def system_of_odes(t, y): # Define the system of second-order ODEs # y is an array of shape (2n,), where n is the number of equations # Compute coefficients n = int(len(y) / 2) y1 = y[:n] # x,y y2 =...
mjanszen/Wind_turbine_aeroelasticity
src/dynamics_only_test.py
dynamics_only_test.py
py
1,287
python
en
code
0
github-code
36
74226664423
import pytest from functions import basic_functions def test_count_animal(spark): """ The simplest example is an assert statement This can be used for checking scalar values, e.g. a row count or a sum The function being tested counts the number of animals after first capi...
best-practice-and-impact/ons-spark
pytest-for-pyspark/tests/test_basic.py
test_basic.py
py
2,912
python
en
code
4
github-code
36
39303528940
#!usr/bin/env python # -*- coding:utf-8 -*- """ @author: admin @file: main.py @time: 2021/09/02 @desc: """ import time import torch from model import config from model.data_process import PrepareData from model.Transformer import make_model from model.LabelSmoothing import LabelSmoothing from model.opt import NoamOpt f...
coinyue/Transformer
main.py
main.py
py
1,629
python
en
code
0
github-code
36
6797262441
from utils.faker_factory import faker from ..mails import BaseMailView class OpportunityReminderCloseMailView(BaseMailView): """ """ template_name = 'mails/opportunity/opportunity_reminder_close.html' mandatory_mail_args = [ 'title', 'created_by_name', 'duedate_timedelta', ...
tomasgarzon/exo-services
service-exo-mail/mail/mailviews/opportunity_reminder_close.py
opportunity_reminder_close.py
py
850
python
en
code
0
github-code
36
36891664339
# functions for handling ABI checking of libraries import Options, Utils, os, Logs, samba_utils, sys, Task, fnmatch, re, Build from TaskGen import feature, before, after # these type maps cope with platform specific names for common types # please add new type mappings into the list below abi_type_maps = { '_Bool...
RMerl/asuswrt-merlin
release/src/router/samba-3.6.x/buildtools/wafsamba/samba_abi.py
samba_abi.py
py
7,987
python
en
code
6,715
github-code
36
9587927527
import os import shutil from plugin import plugin @plugin("file manage") class file_manage: """" Can manipulate files and folders by deleting, moving, or renaming. """ def __call__(self, jarvis, s): self.get_file_directory(jarvis) self.get_cmd(jarvis) if self.cmd == "delete"...
sukeesh/Jarvis
jarviscli/plugins/file_manager.py
file_manager.py
py
3,709
python
en
code
2,765
github-code
36
8424152758
#!/usr/bin/env python3 import pandas as pd def top_bands(): df1=pd.read_csv("src/bands.tsv",sep='\t') df2=pd.read_csv("src/UK-top40-1964-1-2.tsv",sep='\t') print(df1.head()) print(df2.head()) df1['Band']=df1['Band'].str.capitalize() df2['Artist']=df2['Artist'].str.capitalize() df_new=pd.me...
Manmohit10/data-analysis-with-python-summer-2021
part05-e03_top_bands/src/top_bands.py
top_bands.py
py
459
python
en
code
0
github-code
36
38810777586
''' CAS schema's for the roads ''' __name__ = "CASSchema.py" __author__ = "COUTAND Bastien" __date__ = "07.12.22" from datetime import datetime from pydantic import BaseModel, Field class CASBase(BaseModel): ''' CAS Schema ''' cas_ip: str = Field( description='ip for the CAS...
coutand-bastien/Student-project
ENSIBS-4/eduroom/server/app-container/api/schemas/CASSchema.py
CASSchema.py
py
838
python
en
code
0
github-code
36
39694098177
from app.issue_detector import IssueDetector from app.support_detector import SupportDetector import pandas as pd from pathlib import Path import sys from pydantic import BaseModel, Field class SupportScoreCalculator(BaseModel): timestamp: str = Field() issue_detector: IssueDetector = Field(default=IssueDetec...
blocks-web3/empower-link
contribution-analyzer/app/support_score_calculator.py
support_score_calculator.py
py
3,688
python
en
code
0
github-code
36
17359757102
from typing import Optional, List import torch import uuid from torch import nn from supertransformerlib import Core class DefaultParameterLayer(nn.Module): """ A NTM extension layer designed to contain within it the default state for some sort of parameter and to be manipulatable to create, interpol...
smithblack-0/torch-supertransformerlib
src/supertransformerlib/NTM/defaults.py
defaults.py
py
5,642
python
en
code
0
github-code
36
31415174040
from pydantic import BaseModel import json import requests import Console import config HTTP_PREFIX = "http://" HOST = config.server_address + "/internal" class DownloadFileFromAgentInputType(BaseModel): ip_address: str file_path: str class ListFilesFromAgentInputType(BaseModel): ip_address: str di...
Kuba12a/CybClient
Gateways/CybServerGateway.py
CybServerGateway.py
py
3,708
python
en
code
0
github-code
36
16732411603
from typing import List class Solution: def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str: for i, source, target in sorted(list(zip(indices, sources, targets)), reverse=True): l = len(source) if s[i:i + l] == source: ...
wLUOw/Leetcode
2023.08/833/Solution.py
Solution.py
py
372
python
en
code
0
github-code
36