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
13058059804
from string import printable from keras.models import Model, load_model from keras import regularizers from keras.layers.core import Dense, Dropout, Lambda from keras.layers import Input, ELU, Embedding, \ BatchNormalization, Convolution1D,concatenate from keras.preprocessing import sequence from keras.optimizers im...
larranaga/phishing-url-detection
CNNC.py
CNNC.py
py
3,833
python
en
code
5
github-code
36
75075870824
from __future__ import unicode_literals import frappe from frappe.utils.make_random import add_random_children, get_random, how_many, can_make from frappe.utils import cstr from erpnext.setup.utils import get_exchange_rate from erpnext.accounts.party import get_party_account_currency def run_sales(current_date): if ...
frappe/erpnext_demo
erpnext_demo/selling.py
selling.py
py
2,758
python
en
code
2
github-code
36
2744395369
# 第一列不能有 4 import pandas as pd import numpy as np TRUTH_PATH = "/Users/luminshen/Documents/代码/PycharmProjects/Research/-GAN-/Table-GAN/tableGAN/data/Adult/Adult.csv" SAVE_PATH = "./data_with_rule_single_rule.csv" def single_cell_rule(): file = pd.read_csv(TRUTH_PATH, sep=',') file = list(np.array(file)) ...
lums199656/Research
rules/去除违反 rules 的数据.py
去除违反 rules 的数据.py
py
2,786
python
en
code
1
github-code
36
25822228264
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def ui_input() -> str: """This function takes player's cards""" return input('Enter all your cards (with spaces): ') def blackjack(cards: str) -> int: """This function counts points""" cards_values = { '2': 2, '3': 3, '4': 4, '5': 5, ...
LiudaShevliuk/python
lab9_1.py
lab9_1.py
py
1,178
python
en
code
0
github-code
36
31062929205
from ..utils import Object class ChatStatisticsMessageSenderInfo(Object): """ Contains statistics about messages sent by a user Attributes: ID (:obj:`str`): ``ChatStatisticsMessageSenderInfo`` Args: user_id (:obj:`int`): User identifier sent_message_count (:obj:...
iTeam-co/pytglib
pytglib/api/types/chat_statistics_message_sender_info.py
chat_statistics_message_sender_info.py
py
1,244
python
en
code
20
github-code
36
471364125
# Adapted from https://github.com/mimoralea/gdrl from helpers.utils.action_selection import GreedyStrategy, NormalNoiseStrategy from helpers.utils.priority_replay import Memory from helpers.nn.network import FCQV, FCDP from itertools import count import torch.optim as optim import numpy as np import torch import time i...
Oreoluwa-Se/Continuous-Control
helpers/agent.py
agent.py
py
16,852
python
en
code
0
github-code
36
6245629363
# -*- coding: utf-8 -*- from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand class PyTest(TestCommand): ptest_args = [] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def run(self): import p...
magichan-lab/PyIEProxy
setup.py
setup.py
py
1,119
python
en
code
0
github-code
36
33675586325
#!/usr/bin/env python # coding: utf-8 # In[44]: import re import pickle from sklearn_crfsuite import CRF from sklearn_crfsuite import metrics from sklearn_crfsuite import scorers # In[45]: def parse(input_): tags = [] lexicons = [] lemma = [] pos= [] sentences = input_.split("\n\n") for s...
hellomasaya/linguistics-data
assgn4/annCorraCRFModel.py
annCorraCRFModel.py
py
3,577
python
en
code
0
github-code
36
28801077672
# -*- coding: utf-8 -*- """ Created on Thu Feb 1 09:03:59 2018 @author: a001985 """ import logging import pathlib #========================================================================== def add_log(log_id=None, log_directory=None, log_level='DEBUG', on_screen=True, prefix='log_ekostat'): """ log...
ekostat/ekostat_calculator
core/logger.py
logger.py
py
3,803
python
en
code
1
github-code
36
72573548584
import torch import torchaudio import glob from torch.utils.data import Dataset from utils.signal_processing import get_rnd_audio,extract_label_bat from pandas import read_csv from os import path class raw_audio_dataset(Dataset): def __init__(self,wav_dir, annotation_file, input_size, transform=None, target_t...
ArthurZucker/PAMAI
datasets/raw_audio_dataset.py
raw_audio_dataset.py
py
1,409
python
en
code
5
github-code
36
36121229353
import os from typing import Any, Iterator, Dict, Set from forte.data.data_pack import DataPack from forte.data.data_utils_io import dataset_path_iterator from forte.data.base_reader import PackReader from ft.onto.base_ontology import Document __all__ = [ "PlainTextReader", ] class PlainTextReader(PackReader): ...
asyml/forte
forte/data/readers/plaintext_reader.py
plaintext_reader.py
py
1,931
python
en
code
230
github-code
36
7045186193
#!/usr/bin/python3 import argparse import orbslam2 import os import cv2 from time import sleep def build_parser(): parser = argparse.ArgumentParser() parser.add_argument('--vocab', type=str, required=True) parser.add_argument('--config', type=str, required=True) parser.add_argument('--seq', type=str...
cds-mipt/iprofihack
baselines/orbslam2/scripts/run_orbslam2_stereo.py
run_orbslam2_stereo.py
py
2,114
python
en
code
3
github-code
36
541220899
# Реализация класса class People: # Инициализируем человека def __init__(self, name="", surname="", age=0, gender="male"): self.name = name self.surname = surname self.age = age self.gender = gender def print_info(self): # Прописываем информацию о человеке p...
FRFGreyFox/artificial_intelligence
Lectors/OOP.py
OOP.py
py
2,807
python
en
code
1
github-code
36
11316424779
import json import re from pprint import pprint with open('yc_feed.json') as data_file: data = json.load(data_file) i = 0 c = 0 for hundredmessages in data: hm_plain_text = json.dumps(hundredmessages) match = re.search(r'hackathon', hm_plain_text) if match: for msg in hundredmessages['data']: msg_...
adamhipster/hackathon_website
python_fb_group_crawls/parse_fb_feed_data.py
parse_fb_feed_data.py
py
530
python
en
code
0
github-code
36
38895942898
from sys import argv, exit from pygmail.types import Account, Label if __name__ == "__main__": account = Account.from_environment(load_labels=True) label_file = argv[1] if not label_file: print("Usage: remove_labels.py <input_file>") exit(1) label_names = None with open(argv[1]) ...
sk3l/pygmail
examples/remove_labels.py
remove_labels.py
py
881
python
en
code
0
github-code
36
27769169402
import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule class XyjjSpider(CrawlSpider): name = 'xyjj' # allowed_domains = ['www.ccc.com'] start_urls = ['https://www.xyshjj.cn/list-1487-1489-0.html'] # page链接与其他链接相似度过高 rules不起作用,放弃。 rules = ( ...
kshsky/PycharmProjects
dataFile/scrapy/ace/xxjjCrawl/xxjjCrawl/spiders/xyjj.py
xyjj.py
py
992
python
en
code
0
github-code
36
28068050082
# 보물섬 # https://www.acmicpc.net/problem/2589 from collections import deque import copy def bfs(treasure_map, x, y, n, m) : copy_map = copy.deepcopy(treasure_map) dx = [-1, 1, 0, 0] dy = [0, 0, -1, 1] # 시작 지점과 탐색해나가는 지점과의 거리 저장 변수 count = 0 queue = deque([[x, y, count]]) copy_map[x][y] = ...
hwanginbeom/algorithm_study
1.algorithm_question/6.BFS/131.BFS_wooseok.py
131.BFS_wooseok.py
py
1,279
python
ko
code
3
github-code
36
74627444265
def solution(array): print(array[-1]) if array == []: return 1 else: if len(array) < 3: return array[0] - 1 else: array.sort() for i in range(0, len(array) - 1): if array[0] > 1: return 1 elif array[-1] != len(array) + 1: return len(array) + 1 ...
diegosadrinas/Code-Tests
Codility/PermMissingElem/PermMissingElem.py
PermMissingElem.py
py
407
python
en
code
1
github-code
36
14247830669
""" Author: Todd Zenger, Brandeis University The purpose of this program is to show some basics of functions. """ """ First, we can put something in, and get a value out NOTICE: you are responsible to figure out what data type you are passing into the function and what type you are spitting out """ def f(x): y = ...
ToddZenger/PHYS19a
tutorial/lesson01/functions.py
functions.py
py
2,132
python
en
code
1
github-code
36
34848625388
from __future__ import absolute_import from __future__ import unicode_literals __version__ = '0.5.0' from markdown import Extension from markdown.treeprocessors import Treeprocessor class MDXReplaceImageSrcTreeprocessor(Treeprocessor): def __init__(self, md, config): super(MDXReplaceImageSrcTreeprocesso...
twardoch/markdown-steroids
mdx_steroids/replimgsrc.py
replimgsrc.py
py
1,313
python
en
code
3
github-code
36
40272343197
from __future__ import absolute_import, division, print_function import base64 import json import os import time import requests import urllib.request from urllib.request import Request, urlopen from uuid import UUID from beets import config import beets.library from beets.plugins import BeetsPlugin from pathlib imp...
peace899/beets2kodi
beetsplug/kodinfo.py
kodinfo.py
py
18,692
python
en
code
1
github-code
36
72582014823
import spotipy import openai import json import argparse import datetime from dotenv import load_dotenv import os load_dotenv() openai.api_key = os.environ.get("OPENAI_API_KEY") parser = argparse.ArgumentParser(description="Enkelt commandline verktøy") parser.add_argument("-p", type=str, default="AI genert liste",he...
donadelicc/MySpotify
utils/local_app.py
local_app.py
py
3,072
python
en
code
0
github-code
36
40129073796
from openpydss.opendss.model.dssobject import DSSObject class Transformer(DSSObject): def __init__( self, phases="3", windings="2", wdg="1", bus="transformer_1", conn="wye ", kV="12.47", kVA="1000", tap="1"...
munizrodrigo/openpydss
openpydss/opendss/model/transformer.py
transformer.py
py
3,379
python
en
code
0
github-code
36
9104252011
##annealing.py # this python script bruteforces swaps until N iterations are reached. best is saved and shown from classes.bucket import Bucket from classes.target import Target from classes.generate import Generate from similarity import Similarity, Delta from random import random from math import exp def Annealing...
porcherface/mosaic-bot
code/annealing.py
annealing.py
py
2,675
python
en
code
0
github-code
36
40558916970
#!/usr/bin/python3 def roman_to_int(roman_string): if roman_string is None or isinstance(roman_string, str) is not True: return 0 dicta = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} tot = 0 prev = 0 for let in roman_string: if let not in dicta:...
kofikorang12/alx-higher_level_programming
0x04-python-more_data_structures/12-roman_to_int.py
12-roman_to_int.py
py
574
python
tr
code
0
github-code
36
29647730897
import os import sys import subprocess BASE_PATH = os.getcwd() #python folder def drugbank_search(query): content = [] os.chdir("./../java_lucene_index") #process = subprocess.Popen(['ls'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) process = subprocess.Popen("./launch.sh drugbank "+query, sh...
Hamza-ABDOULHOUSSEN/gmd2k22
python/drugbank/drugbank_index_query.py
drugbank_index_query.py
py
1,259
python
en
code
0
github-code
36
42215123133
import json import os import datetime import scipy.optimize import sklearn.metrics import aop import aop.api class DailyIndexPrediction: def __init__(self): # read the config.json in the current directory with open(os.path.dirname(__file__) + '/config.json', 'r') as file_obj: self....
Silence-2020/mt-prediction
daily_index_prediction.py
daily_index_prediction.py
py
9,807
python
en
code
0
github-code
36
30910231452
import sys from PyQt5 import uic from PyQt5.QtGui import QPainter, QColor from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QMainWindow from random import randint class MyWidget(QMainWindow): def __init__(self): super().__init__() uic.loadUi('Ui.ui', self) self.do_paint = Fa...
Dathator/Git-
main.py
main.py
py
870
python
en
code
0
github-code
36
14247809149
""" Author: Todd Zenger, Brandeis University The purpose of this code is to figure out how to bring the mean of two values of a large range down """ import numpy as np # Method 1: simply use variables to continuously check # Our two values x1 = 3 x2 = 555 # The number of times we add 2 n = 0 # We want this loop to...
ToddZenger/PHYS19a
challenge/challenge-00-02.py
challenge-00-02.py
py
1,043
python
en
code
1
github-code
36
39276214746
import numpy as np import tensorflow as tf class TFModel(object): # Define and initialize the TensorFlow model, its weights, initialize session and saver def __init__(self, shape, learning_rate, alpha, regularization_rate, implicit, loss, log_weights, fit_intercepts, optimizer, ...
twolodzko/tfmf
tfmf/tf_model.py
tf_model.py
py
7,146
python
en
code
9
github-code
36
74469828583
#! /usr/bin/env python3 import logging import os import tempfile log = logging.getLogger(__name__) def download_to_disk(config, object_ref): log.debug('Moving file from {} to temporary file'.format(object_ref)) fd, path = tempfile.mkstemp(os.path.splitext(object_ref)[-1]) os.write(fd, open(object_ref, '...
mabruras/sqapi
src/sqapi/query/content/disk.py
disk.py
py
367
python
en
code
2
github-code
36
8786926229
from .abstract import Aggregator from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui i...
t-bucchi/accagg
accagg/bank/sbinetbank.py
sbinetbank.py
py
10,622
python
en
code
0
github-code
36
21821135553
# F*ck implementation problems # Ab to kaam hoja bsdk # Adding comments so it might be helpful to someone ## Moral: Don't watch IPL during contest from collections import Counter for _ in range(int(input())): n = int(input()) lis = list(map(int, input().split())) ## Check for NO condition counter = Counter...
sainad2222/my_cp_codes
codeforces/1433/D.py
D.py
py
1,155
python
en
code
0
github-code
36
44638762028
# **************************************************************************** # # # # ::: :::::::: # # stockholm.py :+: :+: :+: ...
Mankestark/Proyectos-terminados-bootcamp-ciberseguridad
stockholm/stockholm.py
stockholm.py
py
7,398
python
uk
code
0
github-code
36
22192834373
def convert_to_binary(tmp): flag = False s = '' while not flag: if tmp < 2: s += str(tmp) flag = True else: s += str(tmp % 2) tmp = int(tmp / 2) print(f'Овтет: {s[::-1]}') def start_task(): print('\nЗадача 4: Перевод в двоичную\n' + ...
Minions-Wave/GB-Minions-Wave
The Big Brain Solutions/Personal Zone/NighTramp Solutions/Blok 2/Python/HomeWork/Seminar003/task_4.py
task_4.py
py
611
python
ru
code
2
github-code
36
26281206663
#!/usr/bin/env python3 # coding:utf-8 import os,hashlib import shutil import subprocess from datetime import datetime import nacos import yaml from apscheduler.schedulers.blocking import BlockingScheduler from dotenv import load_dotenv, find_dotenv # load .env file load_dotenv(find_dotenv(), override=True) SERVER_A...
GounGG/nacos-client-py
nacos-get-config.py
nacos-get-config.py
py
2,424
python
en
code
1
github-code
36
2708690996
from src.GameLogic.GenericGameLogic import GenericGameLogic class FightCycle(GenericGameLogic): def __init__(self, printMethod, data): super().__init__(printMethod,data) self.turn_order = None self.current_character = None self.index = 0 async def getMessage(self, message, act...
dndiscord/dndiscord
src/GameLogic/FightCycle.py
FightCycle.py
py
1,751
python
en
code
0
github-code
36
22359845771
def set_cover(universe, subsets): """Find a family of subsets that covers the universal set""" elements = set(e for s in subsets for e in s) # Check the subsets cover the universe if elements != universe: return None covered = set() cover = [] # Greedily add the subsets with the most...
LokeshNaidu8/MSc_Practicals
Practicals/Algorithm/setCover.py
setCover.py
py
941
python
en
code
1
github-code
36
38054510986
import accept import logging from aiohttp import web, web_exceptions from aiohttp_swagger import setup_swagger from model import ClientModel, ItemNotFoundException from protocol import * from prometheus_client import REGISTRY, exposition from urllib.parse import parse_qs from voluptuous import MultipleInvalid class ...
weierstrass54/sb_rest
api.py
api.py
py
12,166
python
en
code
0
github-code
36
72447544744
#!/usr/bin/python -tt # -*- coding: utf-8 -*- # Examen LAGRS, diciembre 2018 # NOMBRE: Jorge Luzon Lopez # LOGIN: jluzon import telepot import telepot.namedtuple import time import subprocess,sys import os from telepot.loop import MessageLoop from optparse import OptionParser PUERTOS_TCP = [6666 , 443 , 7899] def r...
jluzonlopez/Largs
extralagrs/vigila_puertos.py
vigila_puertos.py
py
1,538
python
en
code
0
github-code
36
31608746342
import torch from torch import nn from torch.autograd import Variable class topk_crossEntrophy(nn.Module): def __init__(self, top_k=0.7): super(topk_crossEntrophy, self).__init__() self.loss = nn.NLLLoss() self.top_k = top_k self.softmax = nn.LogSoftmax() return ...
Forrest0503/VAT-ABAW
ohem_loss.py
ohem_loss.py
py
987
python
en
code
0
github-code
36
5106024377
import re import json import base64 import pandas as pd import networkx as nx from textblob import TextBlob from collections import defaultdict from arabic_reshaper import reshape from bidi.algorithm import get_display from requests_toolbelt.multipart import decoder def generate_hashtag_data(file_path): # Read th...
kashif-ghafoor/twitter-scrap-infa
src/hashtagAnalysis/index.py
index.py
py
6,609
python
en
code
0
github-code
36
13070129833
import math def roundPrice(A): # attention: in python3, round(1.5) = 1 !!! def round(x): fac = x - math.floor(x) return math.ceil(x) if fac >= 0.5 else math.floor(x) if not A: return A roundSum = sum(map(round, A)) sumRound = round(sum(A)) print(roundSum) print(sumRo...
Jason003/Interview_Code_Python
Airbnb/roundPrice.py
roundPrice.py
py
1,203
python
en
code
3
github-code
36
22577716879
''' Created on May 29, 2017 @author: hfrieden Export ASC DEM files ''' import struct import bpy import bmesh import os.path as path import ArmaToolbox from math import sqrt def vertIdx(x,y,ncols, nrows): return y*ncols + x def exportASC(context, fileName): filePtr = open(fileName, "wt") obj = context.o...
AlwarrenSidh/ArmAToolbox
ArmaToolbox/ASCExporter.py
ASCExporter.py
py
1,167
python
en
code
70
github-code
36
29757178996
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isUnivalTree(self, root): """ :type root: TreeNode :rtype: bool """ unival = ...
hrithikguy/leetcode
965_univalued_binary_tree.py
965_univalued_binary_tree.py
py
632
python
en
code
0
github-code
36
34530261292
from __future__ import absolute_import import hashlib import json import os import re import socket from mercurial.i18n import _ from mercurial import ( error, pathutil, url as urlmod, util, vfs as vfsmod, worker, ) from ..largefiles import lfutil # 64 bytes for SHA256 _lfsre = re.compile(r...
bruno-oliveira/twilioHackathon-whats-around-me
env/lib/python2.7/site-packages/hgext/lfs/blobstore.py
blobstore.py
py
17,091
python
en
code
0
github-code
36
12080392849
chemin = "C:/python/prenom.txt" chemin_clean = "C:/python/prenom_clean_correction.txt" with open(chemin, "r") as f: lines = f.read().splitlines() prenoms = [] for line in lines: prenoms.extend(line.split()) prenoms_final = [prenom.strip(",. ") for prenom in prenoms] with open(chemin_clean, "w") as f: f....
yunus-gdk/python_beginner
trier_liste_noms_correction.py
trier_liste_noms_correction.py
py
360
python
en
code
0
github-code
36
40751695822
import pandas as pd import glob import numpy as np import os col_names = ['date','shop','item', 'unit', 'value'] month ='02' files = [] list_of_files = glob.glob(r'\\lhrnetapp03cifs.enterprisenet.org\rfeprodapp05\InputBackupFiles\CH\Import_M\Monthly-2019-M' r'M-0{month}\*'.format(month=mon...
owojtek18/CH_retailers
Import_ch.py
Import_ch.py
py
1,193
python
en
code
0
github-code
36
39687720281
import networkx as nx, matplotlib.pyplot as plt, numpy as np, copy import MarkovChain as SMC from Randomized import * from time import time Pps = 0.4 # float(input('Ingrese la probabilidad de que un dispositivo protegido pase a ser susceptible: ')) Psp = 0.3 # float(input('Ingrese la probabilidad de que un dispositi...
Zharet-Bautista-Montes/Markov_Inspector
venv/core/MultipleMC.py
MultipleMC.py
py
9,302
python
en
code
0
github-code
36
18935365420
# pylint: disable=too-many-locals, duplicate-code """Management command that loads locale .po files into database.""" from __future__ import unicode_literals import json from os.path import join, isdir from django.conf import settings from django.core.management.base import BaseCommand as LoadCommand, CommandError fr...
IATI/IATI-Standard-Website
modeltranslation_sync/management/commands/load_trans_nav.py
load_trans_nav.py
py
3,582
python
en
code
5
github-code
36
11622358382
def factorial(n: int) -> int: """Return the factorial of n, an exact integer >= 0. Args: n (int): n! Returns: int. The factorial value:: >>> factorial(5) 120 >>> factorial(0) 1 >>> factorial(-1) Traceback (most recent call last): ... ValueError: Only no...
UiO-IN3110/UiO-IN3110.github.io
lectures/python/factorial_doctest_exceptions.py
factorial_doctest_exceptions.py
py
678
python
en
code
21
github-code
36
25971972492
number=5 if type(number) == int: print("resultado: ",number*2) else: print("El dato no es numerico") def mensaje (men): print(men) mensaje("Mi primer Programa") mensaje("Miu segundo Programa")
PovedaJose/EjerciciosDePython
Practicas#1/Ejercicio#1.py
Ejercicio#1.py
py
216
python
es
code
1
github-code
36
17169329371
import os import telebot from dotenv import load_dotenv import client load_dotenv() bot_token = os.getenv('BOT_TOKEN') admin = os.getenv('TG_ADMIN_ID') bot = telebot.TeleBot(bot_token) states_list = ["ADDRESS", "AMOUNT", "CONFIRM"] states_of_users = {} @bot.message_handler(commands=['start']) def start_message(...
Lexxar91/bitcoin_api_bot
tg_bot/bot.py
bot.py
py
12,039
python
ru
code
0
github-code
36
40568587585
from datetime import datetime from typing import Optional from dcs.mission import Mission from game.weather.atmosphericconditions import AtmosphericConditions from game.weather.clouds import Clouds from game.weather.conditions import Conditions from game.weather.fog import Fog from game.weather.wind import WindCondit...
dcs-liberation/dcs_liberation
game/missiongenerator/environmentgenerator.py
environmentgenerator.py
py
2,028
python
en
code
647
github-code
36
35378767894
#!/usr/bin/env python3 """SERVICE YET TO BE IMPLEMENTED. THIS FILE IS JUST A PLACEHOLDER.""" print("Sorry! This service has not yet been implemented\n(will you be the one to take care of it?\n --- RIGHT NOW THIS FILE IS JUST AN HANDY PLACEHOLDER ---") exit(0) #!/usr/bin/env python3 from sys import stderr, stdout, e...
romeorizzi/TALight
TAL_utils/problem_maker/templates/service_server_placeholder.py
service_server_placeholder.py
py
909
python
en
code
11
github-code
36
27435754821
import os import pathlib import numpy as np import matplotlib.pyplot as plt from matplotlib.image import imsave, imread def add_noise(noise_type, image): if noise_type == "gauss": shp = image.shape mean = 0 var = 0.01 sigma = var ** 0.5 gauss = np.random.normal(mean, sigma...
206081/psio
Lab2/zad1.py
zad1.py
py
2,703
python
en
code
0
github-code
36
29138207241
from random import randint as rand import pygame import time row_max =16 column_max =16 mine_count = 50 square_list = [] square_size = 30 BLACK = (0,0,0) WHITE = (255,255,255) BLUE = (0,0,255) RED = (255,0,0) pygame.init() stage = "setup" check_list = [] screen = pygame.display.set_mode((square...
OOCam1/Minesweeper
Minesweeper.py
Minesweeper.py
py
19,511
python
en
code
0
github-code
36
8111739008
import pygame, sys from pygame.locals import * class Particle(object): #Initalizes the paritcle object (called when it is first created) def __init__(self,X,Y,size,deltaX,deltaY,color, displaySurface): #surface to display the particle on self.displaySurface = displaySurface ...
arnavdani/Python-2015-Summer
MyClasses/Particle.py
Particle.py
py
1,136
python
en
code
0
github-code
36
18672969440
import pandas as pd import argparse import yaml import os import io import json def retrieve_params(config): with open(config) as yaml_file: params= yaml.safe_load(yaml_file) return params def generate_metadata_csv(params): excel_file_path = params["data"]["standard_excel_file"] df = pd.read...
sagar-harry/Youtube_Trending_data
generate_meta_data_file_2.py
generate_meta_data_file_2.py
py
1,708
python
en
code
0
github-code
36
24340406630
""" Variables! """ length = 20 breadth = 10 area = length * breadth print(area) # legal variables Area = 10 _area = 10 _Area = 10 area_1 = 10 area1 = 10 # python should use snake-case naming first_name = 'Akhila' print(first_name) #python basic: programming challenge: Money left in the bank after subracting all ...
AkhilaSirikonda/Python-Project
PythonBasics/variables.py
variables.py
py
489
python
en
code
0
github-code
36
25978420324
from enum import Enum class ProxyResponseType(Enum): proxy = 'proxy' file = 'file' json = 'json' def get_dict(self): return self.value class ProxyResponse(object): def __init__(self, request, response, type: ProxyResponseType, ...
sayler8182/MockServer
app/models/models/proxy_response.py
proxy_response.py
py
793
python
en
code
2
github-code
36
29317958483
from keras.utils.data_utils import get_file import os import numpy as np from os import listdir from os.path import isfile, join, isdir import cv2 from random import shuffle import math from keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint, ReduceLROnPlateau, LearningRateScheduler from keras.models im...
LifengFan/Shared-Attention
src/gazemap.py
gazemap.py
py
23,892
python
en
code
4
github-code
36
69941827626
import pickle import os import numpy as np import torch from sklearn.datasets import make_blobs from torch.utils.data import Dataset from torch.utils.data.dataset import T_co def prepare_blob_dataset(city_num: int = 50, feature_dim: int = 2, sample_num: int = 100000...
ma-shangao/rl_waypoint_mrta
dataset_preparation.py
dataset_preparation.py
py
3,367
python
en
code
2
github-code
36
22107437691
from blackfox import BlackFox, KerasOptimizationConfig import csv blackfox_url = 'http://localhost:50476/' bf = BlackFox(blackfox_url) input_columns = 9 input_set = [] output_set = [] with open('data/cancer_training_set.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 fo...
vodena/BlackFoxPython
examples/test_optimize_sync_onnx.py
test_optimize_sync_onnx.py
py
1,040
python
en
code
1
github-code
36
2360976211
""" 【问题描述】 编写一函数insert(string, c),用于在一个已排好序(ASCII值从小到大)的字符串string(少于50个字符)中适当位置插入字符c,要求插入后串的序不变(从小到大),允许字符重复,函数返回插入后的字符串。 测试该函数:从键盘分别输入有序字符串和单个字符,然后调用insert函数,并向屏幕输出插入后的字符串。 【输入形式】 从键盘分行输入有序字符串和单个字符 【输出形式】 向屏幕输出插入后的字符串 【输入样例】 abdef c 【输出样例】 abcdef 【样例说明】 从键盘输入少于50个字符的有序字符串abdef和字符c,将字符c插入字符串abdef,并以ASCII值从小到大排序输出 ...
xzl995/Python
CourseGrading/7.1.11插入字符.py
7.1.11插入字符.py
py
995
python
zh
code
3
github-code
36
43540671742
""" """ import numpy as np from scipy.signal import find_peaks_cwt from scipy.ndimage import gaussian_filter1d def peak_finder( curve:np.ndarray, smoothing_factor:float=21.0, )->np.ndarray: """ """ min_width = int(curve.size/20) max_width = int(curve.size/5) resolution = int((max_width...
chriswilly/design_patterns
data_science/misc.py
misc.py
py
528
python
en
code
1
github-code
36
11249142498
import torch import copy import numpy as np from torch.nn import Dropout from torch.nn import Linear from torch.nn import LayerNorm from torch.nn import functional as F from RprMultiheadAttention import MultiheadAttention def _get_activation_fn(activation): if activation == "relu": return F.relu elif activation =...
perathambkk/lipreading
short1.27fast_nlls_xl_2mem_lattransconv_p_OSL_500_cosine/RprTransformerEncoderLayer.py
RprTransformerEncoderLayer.py
py
3,370
python
en
code
3
github-code
36
37412068955
############################################################################## # # File format versions: # # 1: initial version # # 2: now contains reciprocal planck opacity and rosseland opacity # previous rosseland opacity was actually reciprocal planck opacity # ###############################################...
hyperion-rt/hyperion
hyperion/dust/dust_type.py
dust_type.py
py
31,342
python
en
code
51
github-code
36
71592645224
matrix_A = [ [2,0], [3,0]] matrix_B = [ [1,0], [1,2]] rows_A = len(matrix_A) columns_A = len(matrix_A[0]) rows_B = len (matrix_B) columns_B = len(matrix_B[0]) print(f' m: {rows_A}') print(f' n: {columns_A}') print(f' r: {columns_B}') matrix_C = [[0 for row in range(rows_A)] for columns in range(columns_B)] print(m...
Gabospa/Matrix
multiplication.py
multiplication.py
py
688
python
en
code
1
github-code
36
42985186741
import psycopg2 def create_table(connection): # il cursore è utillizato esequire comandi e accedere alla risposta cursor = connection.cursor() try: # prepara il comando create_table_query = '''CREATE TABLE students (ID SERIAL PRIMARY KEY , NAME TEX...
Torla/postgres_ex
main.py
main.py
py
5,031
python
en
code
0
github-code
36
1947598630
import util primes = [2, 3] d_sum = [0] def init(n): i = primes[-1] while i < n: i += 2 for num in primes: if num * num > i: primes.append(i) break if i % num == 0: break def decompose(n): init(n) fac = {} i = 0 while n > 1: if n % primes[i] == 0: n = int(n / primes[i]) if prime...
liligeng111/Euler_Python
prime.py
prime.py
py
629
python
en
code
1
github-code
36
35701573370
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(899, 563) MainWindow.setMinimumSize(QtCore.QSize(700, 480)) MainWindow.setStyleSheet("*{\n" "background:#18162A;\n" "borde...
MyLongCode/project1
ui_interface.py
ui_interface.py
py
19,084
python
en
code
0
github-code
36
15381149189
import requests from weather_message import WeatherStation LINE_URL = 'https://notify-api.line.me/api/notify' def send_message(token, msg): headers = {'Authorization': 'Bearer ' + token} payload = {'message': msg} response = requests.post(LINE_URL, headers=headers, params=payload) return re...
shamiOuO/weather_report
Line_notify.py
Line_notify.py
py
544
python
en
code
0
github-code
36
21123419493
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, Text, TIMESTAMP from sqlalchemy import func Base = declarative_base() class TestData(Base): __tablename__ = 'test' id = Column(Integer, primary_key = True) data = Column(Text) created_at = Column(TIMESTAMP...
tosiaki/windyfall_bot
testdata.py
testdata.py
py
423
python
en
code
0
github-code
36
34341824103
# -*- coding: utf-8 -*- from telegram.ext import Updater from telegram.ext import CommandHandler from telegram.ext import MessageHandler, Filters from telegram.ext.dispatcher import run_async from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, KeyboardButton import telegram from emoji import emojize, demojiz...
c4software/laurence-bot
telegram_start.py
telegram_start.py
py
5,247
python
en
code
1
github-code
36
25175834547
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 2 17:19:48 2023 @author: acomeau """ import matplotlib.pyplot as plt import time import numpy as np import math x=np.zeros((1,100)) x1=np.zeros((1,100)) x2=np.zeros((1,100)) for timeSetepNdx in range(1,100): x[0,timeSetepNdx]=timeS...
adriencomeau/Telescopium
untitled1.py
untitled1.py
py
749
python
en
code
0
github-code
36
9742849940
import random , math, time from threading import Barrier, Thread # A barrier for 5 thraeds barrier = Barrier(5) start_time = math.floor(time.perf_counter()) # person_in_mall is target of threads created to represent persons def person_in_mall(name, arrival, visit): # sleep for 'arri...
nilanjana123/Programming_lab
lab4/Q4.py
Q4.py
py
2,038
python
en
code
1
github-code
36
70506020904
#importing libraries import pandas as pd from selenium import webdriver # for webdriver from selenium.common.exceptions import NoSuchElementException # for exception handling import time # for delay # setting platform for selenium path = r'C:\Users\haqab\Desktop\DS\chromedriver.exe' driver = webdriver.Chrome(path) ...
Abdulhaq005/Web-Scraping-scrapy-and-selenium-
cars/spiders/selenium_script.py
selenium_script.py
py
3,645
python
en
code
0
github-code
36
72177063783
import json import traceback from flask import Blueprint, jsonify from bson.json_util import dumps from models.users import User get_users_blueprint = Blueprint("get_users_blueprint", __name__) @get_users_blueprint.route("/get-users") def get_users(): try: users = User.find(User.record_status=="ALIVE").a...
emacliam/REDIS-HACKERTHON---CRM
CRM BACKEND/controllers/users/get_users.py
get_users.py
py
947
python
en
code
0
github-code
36
12532422975
"""empty message Revision ID: 8f71e60633a3 Revises: 2e7679aa003d Create Date: 2023-01-24 23:57:44.856118 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '8f71e60633a3' down_revision = '2e7679aa003d' branch_labels = None depe...
lusferror/SugestionCties
src/migrations/versions/8f71e60633a3_.py
8f71e60633a3_.py
py
1,087
python
en
code
0
github-code
36
17393417065
import sqlite3 import constants #from constants import insert_base_user DB_NAME = "vehicle_management.db" db = sqlite3.connect(DB_NAME) db.row_factory = sqlite3.Row c = db.cursor() # # insert_base_user = """ # INSERT INTO BASE_USER (user_name, email, phone_number, address) # VALUES (:user_name, :email,...
bonevb/HackBulgaria-Programming101-Python-2018
week10/01-Vehicle-Repair-Manager/mechanic.py
mechanic.py
py
1,904
python
en
code
0
github-code
36
69953437863
#!/usr/bin/env python #-*- encoding: gbk -*- import time def time_now(time_id): feedback = None T=int(time.time()) if time_id==2 or time_id==3: T+=86400 elif time_id==4 or time_id==5: T+=172800 elif time_id==6 or time_id==7: T+=259200 elif time_id==8 or time_id==9: ...
Jackeriss/Companions
the_time.py
the_time.py
py
3,041
python
en
code
16
github-code
36
7573894871
from tkinter import * import math # ---------------------------- CONSTANTS ------------------------------- # PINK = "#e2979c" RED = "#e7305b" GREEN = "#9bdeac" YELLOW = "#f7f5dd" FONT_NAME = "Courier" WORK_MIN = 25 SHORT_BREAK_MIN = 5 LONG_BREAK_MIN = 20 reps=0 timer=None # ---------------------------- TIMER RESET ----...
EwezuNgim/The_Shadow_Monarch
Pomodoro_main.py
Pomodoro_main.py
py
2,527
python
en
code
0
github-code
36
29028425647
import json import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch from torchvision import transforms from src.constants import ( DICT_CLASS, EMB_ARRAY, EMBEDDINGS, METADATA, NUM_CLOSEST_PLOT, NUMBER_RANDOM_IMAGES, PREDICTION, SKETCHY, TUBERL...
VisiumCH/AMLD-2021-Sketchy
src/models/inference/inference.py
inference.py
py
9,160
python
en
code
0
github-code
36
31987030282
# !/usr/bin/env python # -*- coding: utf-8 -*- import contextlib import os import zipfile import os.path import yaml import json applets_index = [] @contextlib.contextmanager def change_dir(path): old_path = os.getcwd() os.chdir(path) yield os.chdir(old_path) def read_applet_config(applet_path) -> ...
jumpserver/applets
build.py
build.py
py
2,560
python
en
code
9
github-code
36
29261172588
import xml.etree.ElementTree as ET def xml_parse(file_byte): def get_recursive(parent): res = {} if not parent.getchildren(): res[parent.tag] = '' return res res[parent.tag] = [] for child in parent: if child.getchildren(): res[p...
oktavianustjoea/ap-app
xml_converter/utils.py
utils.py
py
529
python
en
code
0
github-code
36
35291375172
""" Created on Tue Apr 26 20:17:37 2022 @author: celiaberon """ import os import numpy as np import pandas as pd import scipy from nta.features.select_trials import match_trial_ids from nta.preprocessing.signal_processing import snr_photo_signal def QC_included_trials(ts: pd.DataFrame, tria...
celiaberon/neural-timeseries-analysis
nta/preprocessing/quality_control.py
quality_control.py
py
12,580
python
en
code
0
github-code
36
26626844923
import astropy.units as u from astropy.coordinates.sky_coordinate import SkyCoord from astropy.units import Quantity from astropy.io.votable import parse from astropy.table import Table from matplotlib.colors import LogNorm import matplotlib.pyplot as plt import numpy as np extra_data = np.genfromtxt("Data/Mean_extinc...
spacer730/Gaia_research
Queries-CM-Diagrams/CM-Diagram-corrected_mean_AG-EBminR .py
CM-Diagram-corrected_mean_AG-EBminR .py
py
2,142
python
en
code
0
github-code
36
31850440252
import matplotlib.pyplot as plt import numpy as np # x axis u = np.arange(0.0,2.74,0.01,dtype=np.cdouble) v = np.arange(2.74,5.0,0.01,dtype=np.cdouble) x = np.arange(0.0,5.0,0.01,dtype=np.cdouble) y = np.arange(0.0,3.83,0.01, dtype=np.cdouble) z = np.arange(3.83,5.0,0.01, dtype=np.cdouble) # y axis def f(t, option =...
cesaregarza/QMResearch
plotter.py
plotter.py
py
1,812
python
en
code
0
github-code
36
27663638173
from typing import List class Solution: def isPalindrome(self, s: str) -> bool: s1 = ''.join(ch for ch in s if ch.isalnum()).lower() s2 = s1[::-1] return s1 == s2 def isPalindrome(self, s: str) -> bool: s1 = ''.join(ch for ch in s if ch.isalnum()).lower() s2 = s1[::-1] ...
robertCho/LeetCode
Multiple Points/E125 Valid Palindrome.py
E125 Valid Palindrome.py
py
583
python
en
code
0
github-code
36
72215373865
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console # DANGER! This is insecure. See http://twil.io/secure account_sid = 'AC3f72ddfebffe2adae5b4efe0c6d9c9b6' auth_token = 'd45d3fcfab5be3e08985b77a3fd13103'...
leemengwei/tasty_shrimp_skype
phone_with_twilio.py
phone_with_twilio.py
py
1,069
python
en
code
1
github-code
36
40861542036
import numpy as np from typing import List, Dict from math import ceil def _valleys(hist: Dict[int, int]) -> List[int]: """ Find the valleys of a histogram of gray levels Arguments: hist frequencies in the histogram of gray levels 0,1,...,L-1 (dictionary) Value: valleys returns ...
image-multithresholding/Image-multithresholding
src/image_multi_thresholding/thresholding_windows.py
thresholding_windows.py
py
2,140
python
en
code
1
github-code
36
15851928871
# python3 phbook = {} n = int(input()) for i in range(n): query = input().split() command = query[0] number = query[1] if command == "add": name = query[2] phbook[number] = name if command == "del": if number in phbook: phbook.pop(number) if...
DA-testa/phone-book-DenissBondars
main.py
main.py
py
461
python
en
code
0
github-code
36
1141324769
import re import base64 import math from glob import glob from getpass import getpass from pprint import pprint from marshals.interface import api import tns.sedm_auto_tns as tns fritz_base_url = 'https://fritz.science/api/' fritz_classification_url = fritz_base_url + 'classification' fritz_redshift_update_url = frit...
scizen9/sedmpy
fritz/fritz_commenter.py
fritz_commenter.py
py
14,311
python
en
code
5
github-code
36
625331659
import os import time from io import BytesIO import aiohttp import asyncio import requests from PIL import Image from lxml import etree # import pandas as pd class Spider(object): """ 下载路径在实例化时候指定,比如:r'd:\test\\',这个目录如果不存在,会出错。 如果想给文件名加前缀,只要在目录下加前缀就行,比如:r'd:\test\abc',那么生成的文件前面都有abc 默认路径为当前文件下的down...
chenxy2022/long
wow.py
wow.py
py
7,151
python
en
code
0
github-code
36
72547899303
from tools.build_utils import * import os, shutil import argparse def main(): # Command line parser options parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument( '--tf_version', type=str, help="TensorFlow tag/branch/SHA\n", ...
openvinotoolkit/openvino_tensorflow
build_tf.py
build_tf.py
py
4,841
python
en
code
176
github-code
36
1908225099
print("Enter the last digit of the serial number") serial = int(input()) serialeven = False if serial % 2 == 0: serialeven = True print("Enter the number of batteries on the bomb:") batteries = int(input()) print("Does the bomb have a parallel Port?(y/n)") hasParallel = False a = input() if a == "y": hasPara...
TimoLob/KTANE-Bot
complicatedcable.py
complicatedcable.py
py
671
python
en
code
0
github-code
36
28078901449
# coding: utf-8 # Your code here! n = int(input().rstrip()) class Node: __slots__ = ['key', 'left', 'right', 'parent'] def __init__(self, key): self.key = int(key) self.left = self.right = self.parent = None root = None def insert(node): global root y, x = None, root while ...
negiandleek/til
aoj/ALDS1_8_A_Binary_Search_Tree_III.py
ALDS1_8_A_Binary_Search_Tree_III.py
py
2,320
python
en
code
0
github-code
36
3026799734
# -*- coding: utf-8 -*- import arcpy,math import pandas as pd import numpy as np import uuid,json,datetime,sys,csv,os from scipy.spatial import distance_matrix arcpy.env.overwriteOutPut = True from Basic_Tools import * from Engine_class import Layer_Engine print_arcpy_message('# # # ...
medad-hoze/EM_3
Old/Engine_main.py
Engine_main.py
py
3,885
python
en
code
0
github-code
36
13019170409
import torch import math from torch import nn import torch.nn.functional as F # Objective: learn embedding vector for each "relative" position # Steps: (1) Identify matrix of possible relatives (sent_len, sent_len) "clamped values" # (2) Identify embedding vector with possible vocabs of relatives (vocab, emb) ...
hosnaa/bert-implement
src/relative_position.py
relative_position.py
py
10,928
python
en
code
0
github-code
36