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
43216482905
#Ejercicio 9 ''' d={} d["clave1"] = "valor1" d["clave2"] = "valor2" print(d["clave1"]) for clave in d.keys(): print("{}:{}".format(clave, d[clave])) ''' d = {} continuar = True while continuar: print("Introduce la palabra clave o '1' para salir.") clave = input() if clave == "1": continuar = ...
gasparpd/SGEM-python
EjerciciosIniciales/src/ejercicio9.py
ejercicio9.py
py
728
python
es
code
0
github-code
1
34902152990
"""DjangoBBSForum URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Clas...
solost23/DjangoBBSForum
bbs/urls.py
urls.py
py
1,196
python
en
code
10
github-code
1
36448157773
import cProfile from logger import lg, initLogger from numpy import ndarray from analisis.loader.img_analizer import * from analisis.loader.mask_loader import * from analisis.loader.islands import build_islands_from_fragmets, fragment_calculate from drawing.draw import * from drawing.show import * from constant.paths...
alekseyIsakin/py
src/main.py
main.py
py
1,904
python
en
code
0
github-code
1
26612191778
import random import sys class BatchGenerator: """ Splits list of items into batches of batch_size length. If item_length_batching is set to True batch length is determined by the sum of item lengths, otherwise by the count of items. """ def __init__(self, items, batch_size, item_length_bat...
zacateras/yansp
utils/generators.py
generators.py
py
3,169
python
en
code
0
github-code
1
29490050611
import collections import numpy as np # type: ignore import random from typing import List, Tuple, Union class SkipGramBatcher: """Encapsulate functionality for getting the next batch for SkipGram from a single list of ints (e.g. from a single text with no sentences). Use SkipGramListBatcher for Node2Vec....
LeoPompidou/embiggen
embiggen/w2v/skip_gram_batcher.py
skip_gram_batcher.py
py
4,263
python
en
code
null
github-code
1
32226270024
""" Line/read counting functions """ import os import subprocess from .filetypes import * from .inspection import * __author__ = "Vince Reuter" __email__ = "vreuter@virginia.edu" __credits = ["Nathan Sheffield", "Andre Rendeiro", "Vince Reuter"] __all__ = ["count_fail_reads", "count_flag_reads", "count_lines", ...
pepkit/ngstk
ngstk/counts.py
counts.py
py
4,351
python
en
code
1
github-code
1
74952017313
""" Module plotpages Utilities for taking a set of plot files and creating a set of html and/or latex/pdf pages displaying the plots. """ from __future__ import absolute_import from __future__ import print_function import os, time, string, glob import sys from functools import wraps # increase resolution for images ...
clawpack/visclaw
src/python/visclaw/plotpages.py
plotpages.py
py
112,744
python
en
code
29
github-code
1
4246703255
import pandas as pd import numpy as np import umap import json from loguru import logger def convert_str_emb_to_float(emb_list): float_emb = [] for str_emb in emb_list: emb = json.loads(str_emb) float_emb.append(np.array(emb)) return float_emb def reduce_embedding_dimension( data, ...
pass-culture/data-gcp
jobs/ml_jobs/embeddings/tools/dimension_reduction.py
dimension_reduction.py
py
717
python
en
code
2
github-code
1
20693742543
from vehicles.models import VehicleManufacturer, VehicleModel, Vehicle import random _manufacturer = 0 _vehicle_model = 0 _vehicle = 0 def create_manufacturer(): global _manufacturer name = 'manufac' + str(_manufacturer) + 'v' manufacturer_dict = { 'name': name } _manufacturer += 1 ma...
mfilipelino/django_angular_simple_project
utils/fakedata.py
fakedata.py
py
1,233
python
en
code
0
github-code
1
4467571006
import database import databasebuilder import idlparser import logging.config import os.path import sys _logger = logging.getLogger('fremontcutbuilder') FEATURE_DISABLED = [ 'ENABLE_BATTERY_STATUS', 'ENABLE_CSS3_CONDITIONAL_RULES', 'ENABLE_CSS_DEVICE_ADAPTATION', 'ENABLE_CUSTOM_SCHEME_HANDLER', 'E...
MarkBennett/dart
tools/dom/scripts/fremontcutbuilder.py
fremontcutbuilder.py
py
4,498
python
en
code
6
github-code
1
15869504617
#!/usr/bin/python # coding:utf-8 """ @author: yyhaker @contact: 572176750@qq.com @file: 19.报数.py @time: 2019/8/4 16:02 """ """ leetcode38:报数(Count and Say) """ class Solution: def countAndSay(self, n: int) -> str: # 思路:统计字符串个数,然后拼接到一起 res = "1" for i in range(n-1): prev = res[0]...
Stella2019/unique-fenlei
字符串/19.报数.py
19.报数.py
py
2,604
python
zh
code
1
github-code
1
41283212288
from hypothesis import given from hypothesis.strategies import lists, builds from cim.collection_validator import validate_collection_unordered from cim.iec61968.common.test_document import document_kwargs, verify_document_constructor_default, verify_document_constructor_kwargs, \ verify_document_constructor_args,...
zepben/evolve-sdk-python
test/cim/iec61968/operations/test_operational_restriction.py
test_operational_restriction.py
py
1,975
python
en
code
3
github-code
1
11819620665
import cv2 fps = 24 size = (274,512) videowriter = cv2.VideoWriter("result.avi",cv2.cv.FOURCC('M','J','P','G'),fps,size) for i in range(1,150): img = cv2.imread('../results/result%d.png' % i) if i!=70: videowriter.write(img)
Hajiren/Parametric-human-shape-reshaping-for-video
code/videoMake/videoMake.py
videoMake.py
py
243
python
en
code
1
github-code
1
74945370273
# dndtester.py import pygtk pygtk.require("2.0") import gtk import gtk.glade class DNDTester(object): def __init__(self): filename = 'dnd.glade' windowname = 'DNDTester' self.wTree = gtk.glade.XML(filename, windowname) self.log_buffer = gtk.TextBuffer() self.setupWidgets()...
georgyberdyshev/ascend
pygtk/drag-drop-example/dnd.py
dnd.py
py
900
python
en
code
5
github-code
1
11547807027
def uniquePaths(array_matrix): #Запускаем цикл, который идет по двумерному массиву for i in range(1, len(array_matrix)): #Запускаем цикл, который идет по элементам массива for j in range(1, len(array_matrix[i])):#Записываем в ячейку массива минимальное значение из соседних ячеек array_matrix[...
AlexanderPodprugin/algorithms_DZ_1_2_3
DZ2/Task1.py
Task1.py
py
788
python
ru
code
0
github-code
1
12855297661
from __future__ import annotations from typing import Callable, Type, TypeVar T = TypeVar("T") Instance = TypeVar("Instance") MapValidateSub = TypeVar("MapValidateSub", bound = "MapValidate") class MapValidate: """ A data descriptor that will apply the provided mapper functions to its data to transform it a...
Divy1211/BinaryFileParser
src/binary_file_parser/retrievers/MapValidate.py
MapValidate.py
py
2,582
python
en
code
4
github-code
1
72514206114
import torch import torch.nn as nn import torch.nn.functional as F #TODO: focal loss index over error class FocalLoss(nn.Module): def __init__(self, gamma=0, alpha=None, size_average=True): super(FocalLoss, self).__init__() self.gamma = gamma self.alpha = alpha if isinstance(alpha,(...
alswlsghd320/u2net_pytorch
loss.py
loss.py
py
4,463
python
en
code
0
github-code
1
34886502654
import time from pika import BlockingConnection, ConnectionParameters from pika.adapters.blocking_connection import BlockingChannel QUEUE_NAME = "basic_channel" def send_message(channel: BlockingChannel, body: str): """ Send a basic message to the given channel :param channel: The channel to send to...
gnir-work/dockerized-rabbitmq
distributer/distributer/distributer.py
distributer.py
py
1,161
python
en
code
0
github-code
1
3134834714
casenum = int(input()) case = [int(input()) for i in range(casenum)] def Factorial(n) : if n == 0 : return 1 elif n == 1 : return 1 return n * Factorial(n-1) for i in range(casenum) : print(f'#{i+1}') for j in range(0, case[i]) : for k in range(j+1) : print(Fact...
DSCodeLearning/SeoYeon
[220102]SWExpertAcademy_2005.py
[220102]SWExpertAcademy_2005.py
py
389
python
en
code
0
github-code
1
5416694372
import math import torch import torch.nn as nn import torch.nn.functional as F class Downblock(nn.Module): def __init__(self, channels, kernel_size=3): super(Downblock, self).__init__() self.dwconv = nn.Conv2d(channels, channels, groups=channels, stride=2, kernel_siz...
cuihu1998/GENet-Res50
pytorch-GENet/models/blocks.py
blocks.py
py
2,353
python
en
code
15
github-code
1
33721261902
import os, sys, time if __name__ == '__main__': print("Je suis %d" % os.getpid()) p = os.fork() if p == 0: # Fils print("fils %d de %d" % (os.getpid(), os.getppid())) time.sleep(5) sys.exit(12) # Suite du père print("père %d de %d" % (os.getpid(), p)) pid, status = os.w...
gando537/L2-Systeme-Python
TD/TD2/src_corr/Q2.2.py
Q2.2.py
py
507
python
fr
code
0
github-code
1
74541383072
# Local imports import json import os # Paths JLAB_ROOT = os.getcwd() PACKAGE_JSON = os.path.join(JLAB_ROOT, "dev_mode", "package.json") EXTERNAL_DEPENDENCIES = { "@jupyterlab-benchmarks/table-render": "0.1.1" } def main(): with open(PACKAGE_JSON, "r") as fh: data = json.loads(fh.read()) jlab_da...
jupyterlab/benchmarks
docker/add_table_render.py
add_table_render.py
py
835
python
en
code
12
github-code
1
33999259780
''' Created on Feb 27, 2014 @author: anshulchawla ''' import re # . (dot ) matches any character except new line one characher per dot. # does left to right so takes the first one from the left match = re.search('...n','Its a cool world anshulanshul') if match: print(match.group()) # /w word char a-z 0-9 etc bu...
anshulankush/PythonWorkspace
Numbers/NumberPackage/Regex.py
Regex.py
py
1,283
python
en
code
0
github-code
1
72094195874
# # # ##------------------------MAIN SELECTION INTRO------------------------------ from operator import itemgetter import os.path def main(): global storelist global incomelist storelist = ['store1', 'store2', 'store3', 'store4', 'store5'] incomelist = [0.0, 0.0, 0.0, 0.0, 0.0] usr_sel = 0 whi...
ekavyd/oldPyCodeRepo
ic_shop3.py
ic_shop3.py
py
6,064
python
en
code
0
github-code
1
16150940400
# Name: John Kelly # ID: C00176932 from flask import Flask, render_template, request, session from operator import itemgetter from collections import Counter import pickle import random import time import os.path import parse_words app = Flask(__name__) @app.route('/') def start_app(): if os.path.isfile('pickl...
ItsJohn/Word-Game
webapp.py
webapp.py
py
4,798
python
en
code
0
github-code
1
2071335048
import json import logging import os import re import sys import time import requests def get_logger(name): log_file = os.getenv('DISKU_LOG_FILE') if log_file: log_handler = logging.FileHandler(log_file) else: log_handler = logging.StreamHandler(sys.stdout) log_handler.setFormatter(lo...
Inndy/disku
disku.py
disku.py
py
8,386
python
en
code
0
github-code
1
38989922806
import argparse import time import absim.world as world from absim.bayesian_agent import BayesianAgent from absim.prob_agent import ProbAgent from absim.prox_agent import ProxAgent from absim.prob_prox_agent import ProbProxAgent from absim.salesman_agent import SalesmanAgent agent_lookup = { "prob" : ProbAgent, ...
utexas-bwi/scavenger_hunt
bwi_scavenger/scripts/absim/hunt.py
hunt.py
py
5,517
python
en
code
3
github-code
1
30169864726
from app.control import modes as robotControl from app.test.fake.bot import motorPairFake class TestControlBasic: def test_initialization(self): wheels = motorPairFake.MotorPair() self.control = robotControl.RobotControl(wheels) assert(self.control is not None)
hoani/pendulumBot
app/test/test_robotControl.py
test_robotControl.py
py
293
python
en
code
0
github-code
1
7814140733
import cv2 import matplotlib.pyplot as plt import os from glob import glob import numpy as np import argparse parser = argparse.ArgumentParser() parser.add_argument( "--root", type=str, default="./atten_bear_visualization/", help="down or middle or up" ) parser.add_argument( "--num_sample", type=int, default=3,...
sunwoo76/CrossAttentionControl-stablediffusion
visualize_comp.py
visualize_comp.py
py
3,773
python
en
code
73
github-code
1
43438190115
import numpy as np import mediapipe as mp import matplotlib.pyplot as plt from utils import ( poseDetector, poseUtils ) def main(): fileName = 'data/Question 19 - 8AE44065-F2F5-4D85-9A96-F69471837F7A.jpeg' image = poseUtils.getImage(fileName) pDetector = poseDetector.Pose...
sankhaMukherjee/legalUserImage
main.py
main.py
py
713
python
en
code
0
github-code
1
5103298786
totalentrevistado = cont_maior_18 = cont_M = cont_mulher_20 = 0 while True: idade = int(input('Idade: ')) sexo = ' ' while sexo not in 'MF': sexo = str(input('Sexo: [M/F] ')).upper() totalentrevistado += 1 if idade > 18: cont_maior_18 += 1 if sexo == 'M': cont_M += 1 ...
RaphaelHenriqueOS/Exercicios_Guanabara
Desafio069.py
Desafio069.py
py
720
python
pt
code
0
github-code
1
35700198066
from struct import pack, unpack import logging from handleclient import common from handleclient import utils from handleclient import message from handleclient import handlevalue from handleclient.handlevalue import HandleValue from handleclient.message import Message, Envelope, Header, Body, Credential logger = ...
pullp/HandleClient
handleclient/response.py
response.py
py
1,554
python
en
code
0
github-code
1
71015513315
# Title: 우수 마을 # Link: https://www.acmicpc.net/problem/1949 import sys from collections import defaultdict sys.setrecursionlimit(10 ** 6) read_single_int = lambda: int(sys.stdin.readline().strip()) read_list_int = lambda: list(map(int, sys.stdin.readline().strip().split(' '))) def get_max(vil: int,...
yskang/AlgorithmPractice
baekjoon/python/best_vilage_1949.py
best_vilage_1949.py
py
1,357
python
en
code
1
github-code
1
12282411056
import ply.lex as lex from ply.lex import TOKEN class Lexer: tokens = ( "WORD", "APOSTROPH", "NEWLINE", "OTHERS", ) large_alpha = "[ΑἈἌᾌἊᾊἎᾎᾈἉἍᾍἋᾋᾋἏᾉΆᾺᾼ]" large_epsilon = "[ΕἘἜἚἙἝἛΈῈ]" large_eta = "[ΗἨἬᾜἪᾚἮᾞᾘἩἭᾝἫᾛᾛἯᾙΉῊῌ]" large_iota = "[ΙἸἼἺἾἹἽἻἿΊῚΪ]" la...
ohmin839/pyplgr
pyplgr/plgrcoll/lexer.py
lexer.py
py
2,770
python
en
code
0
github-code
1
41408095532
# 1293. Shortest Path in a Grid with Obstacles Elimination # https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/ # https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/451787/Python-O(m*n*k)-BFS-Solution-with-Explanation class Solution: def short...
aszx4510/LeetCode
python/1293-shortest_path_in_a_grid_with_obstacles_elimination.py
1293-shortest_path_in_a_grid_with_obstacles_elimination.py
py
2,195
python
en
code
0
github-code
1
12834853666
import json from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) age = Column(Integer) inc...
nicholascgilpin/lifeman
database.py
database.py
py
2,710
python
en
code
0
github-code
1
72116071075
""" Utilities for testing """ from collections import namedtuple import numpy as np from .callbacks import ConvergenceCallback from .cpd import GaussianCPD from .irt import BayesNetLearner from .node import Node EPSILON = 1e-3 NUM_TRIALS = 3 NUM_ITEMS = 50 NUM_INSTR_ITEMS = 0 NUM_LATENT = 1 NUM_CHOICES = 2 NUM_RESP...
Knewton/edm2016
rnn_prof/irt/testing_utils.py
testing_utils.py
py
6,559
python
en
code
58
github-code
1
8691148159
from typing import List # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children if children is not None else [] class Solution: def findRoot(self, tree: List['Node']) -> 'Node': if len(tree) == 0: return No...
songkuixi/LeetCode
Python/Find Root of N-Ary Tree.py
Find Root of N-Ary Tree.py
py
631
python
en
code
1
github-code
1
74863567394
import time import gql from gql.transport.aiohttp import AIOHTTPTransport from gql.transport.exceptions import TransportError class MidosHouse: def __init__(self): self.client = gql.Client(transport=AIOHTTPTransport(url='https://midos.house/api/v1/graphql')) self.cache = None self.cache_e...
deains/ootr-randobot
randobot/midos_house.py
midos_house.py
py
1,113
python
en
code
2
github-code
1
75256450273
class Solution: def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ nums_len = len(nums) nums[:] = nums[nums_len - k:] + nums[: nums_len - k] print (nums) if...
HawkinYap/Leetcode
leetcode189.py
leetcode189.py
py
442
python
en
code
0
github-code
1
14841507583
#!/usr/bin/env python import argparse from termcolor import colored from app import App from constants import ERROR_COLOR, KEY_COLOR, INFO_COLOR from utils import did_you_mean def run(): parser = argparse.ArgumentParser(description='Command line key-value store.', add_help=Fal...
vinu76jsr/kaboom
kaboom/kaboom.py
kaboom.py
py
1,158
python
en
code
0
github-code
1
6788180106
def is_lucky_ticket(ticket_number): ticket_str = str(ticket_number) # Проверяем, что номер билета состоит из шести цифр if len(ticket_str) != 6: return False # Вычисляем сумму первых трех цифр и последних трех цифр sum_first_half = sum(int(digit) for digit in ticket_str[:3]) su...
fireboard777/pythonseminars
task6.py
task6.py
py
923
python
ru
code
0
github-code
1
42896773895
import torch import torch.nn as nn import torch.nn.functional as F from transformers import * from transformers.modeling_roberta import RobertaLMHead from transformers.modeling_bert import BertOnlyMLMHead class BertMLM(BertPreTrainedModel): """BERT model with the masked language modeling head. """ def __i...
alexa/ramen
code/src/models.py
models.py
py
5,251
python
en
code
17
github-code
1
27576774668
import numpy as np import cv2 as cv img = cv.imread("Resources/test.png") gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY) cv.imshow("Gray", gray) lap = cv.Laplacian(gray,cv.CV_64F) lap = np.uint8(np.absolute(lap)) cv.imshow("Laplacian", lap) cv.waitKey(0)
SafirIqbal/Demo-repo
Laplacian.py
Laplacian.py
py
261
python
en
code
0
github-code
1
43679542198
def shift_symbols(): temp = word[shift:len(word)] + word[0:shift] return temp def caesar(): encrypted_message = [alfabet[alfabet.index(letter) - len(alfabet) + 51] if letter in alfabet else letter for letter in my_word] return encrypted_message word = 'vujgvmCfb tj ufscfu oui...
Dober616/work
18/18.5/caesar.py
caesar.py
py
624
python
en
code
0
github-code
1
41283629238
from zepben.evolve import ConductingEquipmentStepTracker, ConductingEquipmentStep, Junction def test_visited_step_is_reported_as_visited(): # noinspection PyArgumentList step = ConductingEquipmentStep(Junction()) tracker = ConductingEquipmentStepTracker() # pylint: disable=protected-access print(...
zepben/evolve-sdk-python
test/services/network/tracing/connectivity/test_conducting_equipment_step_tracker.py
test_conducting_equipment_step_tracker.py
py
3,456
python
en
code
3
github-code
1
12752768218
""" These modules are responsible for scheduling model transfers while adhering to bandwidth limitations of both the sending and receiving party. """ import logging import random from asyncio import Future, get_event_loop, InvalidStateError from typing import List, Dict from ipv8.taskmanager import TaskManager class...
devos50/decentralized-learning
simulations/bandwidth_scheduler.py
bandwidth_scheduler.py
py
14,192
python
en
code
2
github-code
1
19063572783
from __future__ import annotations import dataclasses import enum import grpc from tensorflow_serving.apis.model_pb2 import ModelSpec from tensorflow_serving.apis.model_service_pb2_grpc import ModelServiceStub from tensorflow_serving.apis.prediction_service_pb2_grpc import PredictionServiceStub from tensorflow_serving...
nanaya-tachibana/sknlp-server
sknlp_serving/tfserving.py
tfserving.py
py
6,178
python
en
code
0
github-code
1
18187068649
"""Control navigation of FOREST data""" import copy import datetime as dt import numpy as np import pandas as pd import bokeh.models import bokeh.layouts from collections import namedtuple from forest import data from forest.observe import Observable from forest.util import to_datetime as _to_datetime from forest.expor...
MetOffice/forest
forest/db/control.py
control.py
py
21,707
python
en
code
38
github-code
1
12179042424
from itertools import dropwhile from io_utils import read_file, write_file def clear_missed_rides(rides, max_time, ctime): time_left = max_time - ctime if rides and rides[0].score > time_left: rides = list(dropwhile(lambda x: x.score > time_left, rides)) return rides def run_example(input_file,...
bonheml/hashcode_2018
main.py
main.py
py
792
python
en
code
0
github-code
1
13885704764
from time import perf_counter_ns # Calcul temps d'exécution import matplotlib.pyplot as plt # Graphes def InsertSort(l): """ entree : -------- l : liste d’entier ou réel liste à trier Sortie : -------- l : liste triée Attention la liste initiale est modifiée. ""...
Ilade-s/Sorting-Algorithms
TriInsertions.py
TriInsertions.py
py
3,080
python
en
code
0
github-code
1
26559685585
from tkinter import W, Button from tkinter.ttk import Treeview from tkinter import Toplevel class SimilarityTable: def createAndShow(self, arr, filenames, window): table_window = Toplevel(window) columns = ('File #1', 'File #2', 'Similarity') tree = Treeview(table_window, columns=columns...
jaskier07/DocumentComparator
SimilarityTable.py
SimilarityTable.py
py
1,253
python
en
code
3
github-code
1
30079937946
#! /usr/bin/env python3 import xml.etree.ElementTree as ET import requests import sys from datetime import datetime import subprocess def get_m3u8(targetarea='tokyo', station='fm'): hls = station + "hls" ...
mnod/docker-radiru
rec_radio.py
rec_radio.py
py
1,880
python
en
code
0
github-code
1
29121079371
from selenium import webdriver import time from selenium.common.exceptions import NoSuchElementException import random class amdAutomation(): def __init__(self): self.driver = None def setWebsiteLocation(self, link): self.driver = webdriver.Chrome('/Users/chiraag/chromedriver') self.d...
crekhari/Graphics-Card-Auto-Checkout-Bot
src/amd.py
amd.py
py
1,348
python
en
code
0
github-code
1
72276045475
import pygame class Sprite(pygame.sprite.Sprite): def __init__(self, groups=[]): super().__init__(groups) # The state for the sprite self.state = "released" self.mouse_state = "released" # This makes sure that the rect actually exists # self.rect = sel...
LeoTheMighty/ApocalypseLater
ui/Sprite.py
Sprite.py
py
1,761
python
en
code
0
github-code
1
39156355623
#+--------------------------------------------------------------------- #+ Python Script that creates CMAQ_ADJ v4.5 forcing files #+ Check the 'CHANGE' comments to define your directories for the run #+ Author: Camilo Moreno #+ Email = cama9709@gmail.com #+--------------------------------------------------------------...
kamitoteles/Forcingfile_generator_CMAQ_adj_v4.5
cmaqadj_forcefile.py
cmaqadj_forcefile.py
py
8,146
python
en
code
0
github-code
1
19654910100
import keras import os, shutil from keras import layers from keras import models from keras import optimizers from keras.preprocessing.image import ImageDataGenerator import matplotlib.pyplot as plt model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(...
BoomFan/dogs_vs_cats
Chapter5/chapter5_2_2.py
chapter5_2_2.py
py
3,262
python
en
code
0
github-code
1
23160219600
#! /usr/bin/env python3 def marker_index(transmission: str, num_identical_chars: int) -> int: """Find index after specified number of identical characters.""" for idx in range(len(transmission)): if len(set(transmission[idx:idx+num_identical_chars])) == num_identical_chars: return idx+num...
donovan-h-parks/advent-of-code
2022/python/day-06/day-06.py
day-06.py
py
1,015
python
en
code
0
github-code
1
33447489847
def input_num(): while True: try: x = int(input('Enter num')) if x < 255 and x > 0: return x else: print('Num is incorrect') except ValueError: print('Wrong number') def to_16x(): num = input_num() l_1 = list() ...
Vac1k/python_labs_km13_onyshchenko
p7_onyshchenko/p7_onyshchenko.py
p7_onyshchenko.py
py
908
python
en
code
0
github-code
1
6819650595
from flask import render_template, Blueprint from app.model import Article, User, Category, Tag blueprint = Blueprint('front', __name__, template_folder='templates') @blueprint.route("/") def index(): result = Article.query.getall() categorys = Category.query.all() #tags = Tag.query.all() temp = Arti...
romasport/coolflask
app/view/front.py
front.py
py
1,022
python
en
code
0
github-code
1
73836192993
# python script for OptionCalculator_v1_1_0.xlsm file # excel link : https://blog.naver.com/montrix/221378282753 # python link : https://blog.naver.com/montrix/*********** import mxdevtool as mx # vanilla option def test(): print('option pricing test...') s0 = 255 strike = 254 r = 0.02 div = 0.0...
actuarial-tools/mxdevtool-python
excel/pricing/OptionCalculator_v1_2_0.py
OptionCalculator_v1_2_0.py
py
1,497
python
en
code
0
github-code
1
12844050855
import numpy as np import cv2 def get_matrix_2D(center, rot, trans, scale): ca = np.cos(rot) sa = np.sin(rot) sc = scale cx = center[0] cy = center[1] tx = trans[0] ty = trans[1] t = np.array([[ca * sc, -sa * sc, sc * (ca * (-tx - cx) + sa * ( cy + ty)) + cx], [sa * s...
mqne/GraphLSTM
region_ensemble/transformations.py
transformations.py
py
1,583
python
en
code
8
github-code
1
35367988265
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import json import yaml import datetime import argparse from collections import defaultdict from dateutil.parser import parse from dateutil.rrule import rrule, DAILY from dateutil.relativedelta import relativedelta from utils import get_season, get_team_from_g...
leaffan/del_stats
backend/get_del_games.py
get_del_games.py
py
20,247
python
en
code
14
github-code
1
28816552446
def showbook(url, kind): html = requests.get(url).text soup = BeautifulSoup(html, 'html.parser') try: pages = int(soup.select('.cnt_page span')[0].text) # 该分类共有多少页 print("共有", pages, "页") for page in range(1, pages + 1): pageurl = url + '&page=' + str(page).strip() ...
c7934597/Python_Internet_NewBook_Boards
books_xlsx.py
books_xlsx.py
py
2,801
python
zh
code
0
github-code
1
74345211234
# # @lc app=leetcode.cn id=122 lang=python3 # # [122] 买卖股票的最佳时机 II # from typing import List # @lc code=start class Solution: def maxProfit(self, prices: List[int]) -> int: #---------------------------------------------------------------# # 贪心算法 # 计算相隔两天的利润 # 利润为正就sum++ ...
Zigars/Leetcode
贪心算法/122.买卖股票的最佳时机-ii.py
122.买卖股票的最佳时机-ii.py
py
701
python
en
code
0
github-code
1
72005765155
import requests import requests as rq from util import jieba # 使用scikit-learn進行向量轉換 # 忽略在文章中佔了90%的文字(即去除高頻率字彙) # 文字至少出現在2篇文章中才進行向量轉換 from bs4 import BeautifulSoup from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer, TfidfVectorizer # import pandas ...
Chunshan-Theta/GlobePocket
util/ins_explore.py
ins_explore.py
py
6,623
python
en
code
0
github-code
1
70320371554
''' ''' """ """ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: # 自下向上递归 def isSymmetric_BTT(self, root: TreeNode) -> bool: pass #...
HVP1998/python_learning
advanced/BinaryTree/06.对称二叉树.py
06.对称二叉树.py
py
1,556
python
en
code
0
github-code
1
11737218073
"""apks table Revision ID: e10608056996 Revises: dd4e694b3acf Create Date: 2018-08-20 15:22:37.862657 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e10608056996' down_revision = 'dd4e694b3acf' branch_labels = None depends_on = None def upgrade(): # ###...
johndoe-dev/Ecodroid
migrations/versions/e10608056996_apks_table.py
e10608056996_apks_table.py
py
1,158
python
en
code
0
github-code
1
39879428
import datetime class Logic: localTime = datetime.datetime.now() carLeft = carRight = carFront = carBack = False def __init__(self, GPSData): self.GPS = GPSData def shouldWindowsBeTinted(self): if 60 < self.GPS.elevationAngle < 120: print("GPS Elevation angle shows no t...
swachm/AutoCarWindowVisor
Model/Logic.py
Logic.py
py
1,007
python
en
code
0
github-code
1
23568303273
from os import error from time import sleep import serial import psutil import serial.tools.list_ports import GPUtil import json from hotkey import activate_gpu, activate_mem ports = serial.tools.list_ports.comports() handShakePort = None prevMode = 0 mode = 0 memoryActivate = False maxMem = 0 memKey = '' gpuKey = '' g...
brutalzinn/arduino-python-computer-monitor
main.py
main.py
py
3,817
python
en
code
0
github-code
1
40071012285
"""empty message Revision ID: 075ef7b7f465 Revises: c8df1e64ac3f Create Date: 2020-01-14 00:46:47.381666 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '075ef7b7f465' down_revision = 'c8df1e64ac3f' branch_labels = None depends_on = None def upgrade(): # ...
paduck210/flask_practice
resources/migrations/versions/075ef7b7f465_.py
075ef7b7f465_.py
py
780
python
en
code
1
github-code
1
840878035
#Asking for the file size in kilobytes kilo_size = float(input("Enter a file size in kilobytes (KB): ")) print() print(kilo_size,"KB ...") print() #Calculations for converting into other size values bytes_size = kilo_size * 1024 bits_size = bytes_size * 8 mega_size = float(kilo_size / 1024) giga_size = flo...
smileone22/18Fall_IntroToProgramming
Input_output_processing/Kim_Heewon_Output.py.py
Kim_Heewon_Output.py.py
py
1,609
python
en
code
0
github-code
1
18338733624
class Data: def __init__(self, path='Data/new 1.json'): self.data_path = path """ This is just a method to check for inconsistency in Post-Edits, as someone has done some mischievious things while translating(Post-editing), Sentences have been repeated upto 4 times, words with long unw...
srbhr/Test-Edits
Data.py
Data.py
py
1,989
python
en
code
3
github-code
1
35533894023
import json import logging try: from http import client as httplib except ImportError: # Python 2.6/2.7 import httplib import urllib from pretenders.common.exceptions import ( ConfigurationError, ResourceNotFound, UnexpectedResponseStatus, ) from pretenders.common.pretender import PretenderMo...
pretenders/pretenders
pretenders/client/__init__.py
__init__.py
py
5,630
python
en
code
108
github-code
1
1585776599
from typing import Optional, List from validator_collection import validators, checkers from highcharts_core.metaclasses import HighchartsMeta from highcharts_core.decorators import class_sensitive, validate_types from highcharts_core.options.sonification.track_configurations import (InstrumentTrackConfiguration, ...
highcharts-for-python/highcharts-core
highcharts_core/options/plot_options/sonification.py
sonification.py
py
7,074
python
en
code
40
github-code
1
30922015541
"""Misc. utilities.""" def endless_range(start=0, step=1): i = start while True: yield i i += step try: from setproctitle import setproctitle except ImportError: setproctitle = lambda t: NotImplemented def mixined(cls, *mixin_clses): return type(cls.__name__ + "+Mixins", mixin_cls...
yostudios/ams
ams/utils.py
utils.py
py
2,390
python
en
code
2
github-code
1
10668569761
from django.forms import ModelForm from core.erp.models import * from django.forms import * class ListForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for form in self.visible_fields(): form.field.widget.attrs['class']='form-control' fo...
AxelAlvarenga/Proyecto2022
Eldeportista/app/core/login/forms.py
forms.py
py
439
python
en
code
0
github-code
1
11424506
#기초 import numpy as np import cv2 print(cv2.__version__) img = cv2.imread("./image/food.jpg") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow("food", img) cv2.imshow("food - gray", gray) cv2.waitKey(0) cv2.destroyWindow() #보간법으로 픽셀 변경 resized = cv2.resize(img, None, fx = 0.2, fy = 0.2, interpolation=cv2.IN...
GitOfVitol/openCVProj
openCV기초.py
openCV기초.py
py
397
python
en
code
0
github-code
1
3841312108
#!/usr/bin/env python # -*- coding: utf-8 -*- # import dependency library import numpy as np import pandas as pd from static import config from scipy import ndimage from collections import Counter import csv import os # import user defined library import utils.general_func as general_f def get_cell_name_affin...
chiellini/CellFeatureEnhancementModel
utils/cell_func.py
cell_func.py
py
3,769
python
en
code
0
github-code
1
15127957692
# O(n) time | O(n) space, where n is the length of the input string class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s output = [] for i in range(numRows): output.append([]) idx = 0 ...
mmichalak-swe/Algo_Expert_Python
LeetCode/6_ZigZag_Conversion/attempt_1.py
attempt_1.py
py
692
python
en
code
3
github-code
1
5890621434
import torch from torch.autograd import Variable as Var import torch.nn as nn def ifcond(cond, x_1, x_2): # ensure boolean cond = cond.byte().float() # check is it Tensor or Variable if not hasattr(cond, "backward"): cond = Var(cond, requires_grad=False) return (cond * x_1) + ((1-cond) * x...
ds4an/CoDas4CG
CodeOfApproaches/tree2tree/model/utils.py
utils.py
py
3,470
python
en
code
13
github-code
1
35264151669
import numpy as np from ranker import Ranker class BM25(Ranker): def __init__(self, k=1.2, b=0.75, is_ranker=True): self.k = k self.b = b self.is_ranker = is_ranker def get_scores(self, query, df): """returns bm25 of doc""" if self.is_ranker: docs = df["bod...
Yannjoel/mse_project_team05
src/python/RankingAlgorithms/bmtf.py
bmtf.py
py
1,852
python
en
code
0
github-code
1
16408548253
# lab03.py for Tyler Pennebaker # CS20, Spring 2016, Instructor: Phill Conrad # Draw some initials using turtle graphics import turtle def drawT(t,w,h): #draws a letter 'T' w/ width, w, and height, h using turtle, t #Find start point x0 = t.xcor() y0 = t.ycor() #Draw letter using multiple points ...
ZryletTC/CMPTGCS-20
labs/lab03/lab03.py
lab03.py
py
1,217
python
en
code
0
github-code
1
31944333985
from qgis.utils import iface from qgis import gui, core import math from Ferramentas_Producao.modules.qgis.mapFunctions.mapFunction import MapFunction class CloseLine(MapFunction): def __init__(self): super(CloseLine, self).__init__() def isValidParameters(self, layer): if not layer: ...
dsgoficial/Ferramentas_Producao
modules/qgis/mapFunctions/closeLine.py
closeLine.py
py
2,008
python
en
code
2
github-code
1
22752641641
from django.urls.conf import path from . import views app_name = 'events' urlpatterns = [ path('create-event/', views.CreateEventView.as_view(), name="create_event"), path('edit-event/<uuid:event_id>/', views.EditEventView.as_view(), name='edit_event'), path('get-events/', views.RetrieveEventView.as_view(...
rashiddaha/django_meet
events/urls.py
urls.py
py
449
python
en
code
1
github-code
1
15760438393
#!/usr/bin/python from flask import Flask, render_template from constant import constants import random import urllib3 import json __author__ = "Daniel Fernando Santos Bustos" __license__ = "MIT" __version__ = "1.0" __maintainer__ = "Daniel Santos" __email__ = "dfsantosbu@unal.edu.co" __status__ = "Development" app=...
xdanielsb/blog-flask
app.py
app.py
py
985
python
en
code
1
github-code
1
22290717535
import sys input = sys.stdin.readline import os os.chdir(os.path.dirname(os.path.abspath(__file__))) with open('yodel.in', 'r') as f: read = f.read().strip().split('\n') dataiter = iter(read) def input(): return next(dataiter) ppl, rounds = map(int, input().strip().split()) scores = [0] * ppl ...
dhrumilp15/Puzzles
CCC04/yodel.py
yodel.py
py
505
python
en
code
0
github-code
1
19323442922
def solution(skill, skill_trees): answer = 0 for tree in skill_trees: skill_arr = [] for t in tree: if t in skill: skill_arr.append(t) new_skill = "".join(skill_arr) if new_skill == skill[:len(new_skill)]: answer += 1 return answer pr...
hanameee/Algorithm
Programmers/Summer:Winter Coding/src/스킬트리.py
스킬트리.py
py
376
python
en
code
2
github-code
1
73602744993
from typing import Any import gym from gym import spaces import numpy as np import pybullet as p from robot_utils import RegisterScenes from robot_utils import Robot, rayTest, checkCollision from robot_utils.log import * from robot_utils.utils import control_miniBox import pybullet_data class MsnDiscrete(gym.Env): ...
LSTM-Kirigaya/MsnEnvironment
env/MsnDiscrete.py
MsnDiscrete.py
py
8,863
python
en
code
0
github-code
1
12466619564
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('urly_app', '0004_auto_20161026_1723'), ] operations = [ migrations.AddField( model_name='link', name...
spe-bfountain/short
urly_app/migrations/0005_link_requires_login.py
0005_link_requires_login.py
py
401
python
en
code
0
github-code
1
22474100212
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ tbl, stack = {')':'(', ']': '[', '}': '{' }, [] for c in s: if c in [ '(', '[', '{' ]: stack.append(c) else: if not stack or stack.p...
Brady31027/leetcode
20_Valid_Parentheses/valid_parentheses.py
valid_parentheses.py
py
419
python
en
code
1
github-code
1
27948021566
class User: def __init__(self, username, user_id): self.username = username self.user_id = user_id self.followers = 0 self.following = 0 def follow(self, user): user.followers += 1 self.following += 1 user_1 = User("Fidelis", 200) user_2 = User("Angela", 201) u...
Fidelis-7/100-days-of-coding-in-python
100-Days/Day_17/Class.py
Class.py
py
438
python
en
code
2
github-code
1
26395961422
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC #escolhe o chrome #endereco para o chrome driver PATH = "/home/amanda/Docum...
AmandaApolinario/SpiritFanficFavoritador
coisadelu.py
coisadelu.py
py
1,474
python
en
code
2
github-code
1
42615469832
"""Constants and enumerations""" from enum import Enum, Flag class RinnaiSystemMode(Enum): """Define system modes.""" HEATING = 1 EVAP = 2 COOLING = 3 RC = 4 NONE = 5 class RinnaiOperatingMode(Enum): """Define unit operating modes.""" NONE = 0 MANUAL = 1 AUTO = 2 class RinnaiC...
funtastix/pyrinnaitouch
pyrinnaitouch/const.py
const.py
py
2,104
python
en
code
4
github-code
1
10068296172
import pandas as pd import numpy as np import hydra import os import json import yaml import pickle import time from flask import Flask, request, jsonify import mysql.connector import prediction #26.6.2021 #1. Change the db into production db #2. Deploy into AWS EC2 #3. Deploy the model into AWS EKS app = Flask(__na...
hoe94/Water_Quality
src/app.py
app.py
py
1,846
python
en
code
0
github-code
1
19369503791
from django.http import HttpResponse from django.utils.html import strip_tags from models import Listener import activity_checker import corrector import formatter cor = corrector.Corrector() fmt = formatter.Formatter() def check(request, listener_id, line_id, line): good_one, len_lines, level = Listener.get_go...
deccico/capego
listener/views.py
views.py
py
1,134
python
en
code
0
github-code
1
25087220013
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: q = [root] k = 0 while q...
sanial2001/tree
binary tree/even odd tree.py
even odd tree.py
py
1,054
python
en
code
0
github-code
1
70094000673
# Look for #IMPLEMENT tags in this file. These tags indicate what has # to be implemented to complete the warehouse domain. # You may add only standard python imports---i.e., ones that are automatically # available on TEACH.CS # You may not remove any imports. # You may not import or otherwise source any ...
lhelium/csc384
assignment1/solution.py
solution.py
py
14,826
python
en
code
0
github-code
1
24939243032
import time import random import matplotlib.pyplot as plt def quicksort(arr): if len(arr) <= 1: return arr else: pivot = random.choice(arr) lesser = [x for x in arr if x < pivot] equal = [x for x in arr if x == pivot] greater = [x for x in arr if x > pivot] ...
Lixipluv/Code-Cool-Things
TrabAnalise/Questão 1/letrad.py
letrad.py
py
436
python
en
code
0
github-code
1
15253443423
from sys import stdin def solve(n,d,arr): for i in range(n): g = next(x for x, j in enumerate(arr) if j-arr[i]>=d) print(g) n, d = list(map(int, stdin.readline().rstrip().split())) arr = list(map(int, stdin.readline().rstrip().split())) solve(n,d,arr)
manav2511/codeforces-solutions
Python/251A.py
251A.py
py
275
python
en
code
0
github-code
1