text
string
size
int64
token_count
int64
"""Defines a rule for runsc test targets.""" load("@io_bazel_rules_go//go:def.bzl", _go_test = "go_test") # runtime_test is a macro that will create targets to run the given test target # with different runtime options. def runtime_test(**kwargs): """Runs the given test target with different runtime options.""" ...
690
237
# Copyright 2019-2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
918
342
from datetime import datetime import boto3 import json from .stage import Stage class SQS(object): """ class SQS is a collection of utils related to Foursight queues """ def __init__(self, foursight_prefix): self.stage = Stage(foursight_prefix) def invoke_check_runner(self, runner_input)...
5,254
1,422
#!/usr/bin/env python import os from setuptools import setup from setuptools.command.install import install LONG_DESCRIPTION = "" with open(os.path.join(os.path.dirname(__file__), 'README.md'), 'r') as f: LONG_DESCRIPTION = f.read() setup( name='shadho', version='0.4.3.post2', description='Hyperparam...
1,476
469
import difflib import glob import os import gmso import mbuild as mb import pytest from pkg_resources import resource_filename from foyer.exceptions import FoyerError from foyer.general_forcefield import Forcefield from foyer.tests.base_test import BaseTest from foyer.tests.utils import get_fn, register_mock_request ...
20,837
7,213
import requests from django.conf import settings from visualize.utils.api import Client class GetUserInfo(object): """ GetUserInfo : params : username response : { "login": "torvalds", "id": 1024025, "avatar_url": "https://avatars0.githubusercontent.com/u/1024025?v=4", "gravatar_id": ""...
2,315
1,014
# Generated by Django 3.1.5 on 2021-05-01 10:36 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('globals', '0003_auto_20191024_1242'), ('counselling_cell', '0001_initial'), ] operations = [ migrat...
1,306
418
import os class config(): input_dir = '' max_len = '128' pretrain_model_dir = '' home_dir = os.getcwd() + '/' data_dir = home_dir + 'raw_data/ske/' tf_serving_addr = '127.0.0.1:8501' bert_vocab_dir = home_dir + 'pretrained_model/chinese_wwm_ext_L-12_H-768_A-12/vocab.txt' bert_config_dir ...
2,650
1,669
from __future__ import absolute_import from .client import * __version__ = '0.2.2'
86
32
from django.db import models from django.utils.translation import ugettext_lazy as _ from ..conf import settings class UserAgreement(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, primary_key=True, verbose_name=_("user"), related_name="agreement", on...
440
137
import json import sys import os import requests from datasets.diff_helper import DiffHelper from common.constants import BASE_HEADERS, FAIR_API_ENDPOINT, SSL_VERIFY, FAIR_URL, DRY_RUN def dataset_url(code): return f"{FAIR_API_ENDPOINT}{code}" def get_request(dataset_code): resp = requests.get( datase...
2,076
695
import os import json from collections import OrderedDict import pandas as pd def write_json_to_file(json_data, json_file_path): parsed = json.loads(json_data) parsed = json.dumps(parsed, indent=4, sort_keys=True) obj = open(json_file_path, 'w') obj.write(parsed) obj.close() # replace " with ' ...
18,207
4,842
from QUANTAXIS import QA_fetch_stock_day_adv, QA_fetch_stock_list_adv, QA_fetch_stock_day_full_adv, QA_Setting import pandas as pd QASETTING = QA_Setting() DATABASE = QASETTING.client.quantaxis # def getAllTradeCal(): # return pd.DataFrame(DATABASE.trade_date.find({"is_open": 1})) class MongoDataLoader: de...
1,173
430
import sys import time import numpy as np import scipy as sp import pandas as pd import math import warnings from pyspark.sql import SparkSession from pyspark import StorageLevel from pyspark.ml.feature import Normalizer from pyspark.ml.feature import StringIndexer, StandardScaler from pyspark.ml.feature import OneHotE...
2,934
1,018
import re from .Entity import Entity from .SmellSource import SmellSource from .ontologies import ODEUROPA class SmellEmission(Entity): def __init__(self, seed, smell, source='', carrier='', lang='en'): super().__init__(seed) self.setclass(ODEUROPA.L12_Smell_Emission) self.add(ODEUROPA.F1...
800
280
# -*- coding: utf-8 -*- MNIST_DATASET_PATH = 'raw_data/mnist.pkl.gz' TEST_FOLDER = 'test/' TRAIN_FOLDER = 'train/' MODEL_FILE_PATH = 'model/recognizer.pickle' LABEL_ENCODER_FILE_PATH = 'model/label_encoder.pickle' # Manual DEMO_HELP_MSG = '\n' + \ 'Input parameter is incorrect\n' + \ 'Display ...
489
197
#! /usr/bin/env python def cut_the_sticks(a): cuts = [] while len(a) > 0: cutter = a.pop() if cutter == 0: continue for i in range(len(a)): a[i] -= cutter cuts.append(len(a) + 1) return cuts if __name__ == '__main__': _ = input() value = map...
435
166
# coding: utf-8 # ----------------------------------------------------------------------------- # Copyright (c) 2015 Tiago Baptista # All rights reserved. # ----------------------------------------------------------------------------- """ Path-finding exercise using the pac-man game. Using the mouse, choose a target l...
2,330
698
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from django.contrib.auth.models import User from django.test import TestCase from cms.api import assign_user_to_page, create_page from ..helpers import get_request from ..views import SearchResultsView class PermissionsTestCase(TestCase): def set...
3,867
1,133
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ################################################## # GNU Radio Python Flow Graph # Title: FSO Communication Block Modules Test # Author: M Mansour Abadi # Description: Modules from FSO_Comm are used in a simple FSO comunication link including various channel effects. # Gen...
12,179
4,951
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from wikidataintegrator import wdi_core, wdi_login import logging import pickle __author__ = "Riemer van der Vliet" __copyright__ = "Copyright 2020, Laboratory of Systems and Synthetic Biology" __credits__ = ["Riemer van der Vliet", "Jasper Koehorst"] __license_...
6,194
1,922
import heapq import logging import os from tensorflow.keras.callbacks import Callback class ModelCheckpoint(Callback): def __init__( self, filepath: str, monitor: str, mode: str = "max", save_every_n_epochs: int = None, save_n_best=1, save_optimizer=False, ...
3,449
1,088
"""Change activity picture paths to file ids. Revision ID: 1f4385bac8f9 Revises: c8cd32037cde Create Date: 2018-03-30 16:01:56.532893 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmake...
3,851
1,294
# -*- coding: utf-8 -*- from functools import wraps from .utils import run_function class Signal(object): def __init__(self, name, doc=''): self.name = name self.doc = doc self.receivers = {} class Namespace(dict): def signal(self, name, doc=None): try: return se...
1,165
354
#pedir a altura e a largura de uma parede e dizer quantos litros de tinta vai gastar sabendo que cada litro de tinta pinta 2m2 altura = float(input('Qual a altura da parede? ')) largura = float(input('Qual a largura da parede? ')) area = altura * largura tinta = (altura * largura) / 2 print('Voce tem a area de {}x{} ...
463
171
from django.http import HttpResponse from django.shortcuts import render def funwithmath(request): return render (request, 'funwithmath.html')
148
41
# -*-coding:Utf-8 -* from repetier_ui import * import time import set_ifttt from FUTIL.my_logging import * my_logging(console_level = DEBUG, logfile_level = INFO) HD = repetier_printer (repetier_api(api_key='142a8eed-7d86-4bea-96bc-cfcf5b3ca742'),'HD') sys.path.insert(0,'/home/pi') import iftt_key ifttt0 = set_if...
1,155
504
# BSD Licence # Copyright (c) 2009, Science & Technology Facilities Council (STFC) # All rights reserved. # # See the LICENSE file in the source distribution of this software for # the full license text. # Copyright (C) 2007 STFC & NERC (Science and Technology Facilities Council). # This software may be distributed un...
5,195
1,517
from PyQt5.Qt import QMainWindow from prev_projects.DATAFIT.UTILITY.OBSERVER import GraphObserver from prev_projects.DATAFIT.UTILITY.META import Meta from prev_projects.DATAFIT.VIEW.UI import Ui_GraphWindow class GraphView(QMainWindow, GraphObserver, metaclass=Meta): """ Represents graphical view of experime...
2,942
952
import pandas as pd class Normalizer: csv_data = 'dataset/water_potability.csv' # file from work data def __init__(self) -> None: self.dataset = pd.read_csv(self.csv_data) self.__normalize_data__() self.__separate__() ''' @ convert all info to number ''' def __normalize_data__(self) -> Non...
1,205
399
import sys if len(sys.argv) != 2: print("command is 'python <vtk file>'") sys.exit(1) from paraview.simple import * proxy = OpenDataFile(sys.argv[1]) r = proxy.GetClientSideObject() r.Update() g = r.GetOutput() if g.GetNumberOfPoints() != 441 or g.GetNumberOfCells() != 800: print('Output grid is incorre...
541
201
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/09_generative_models.generative_base.ipynb (unless otherwise specified). __all__ = ['GenerativeModel', 'beam_search'] # Cell from ..imports import * from ..torch_imports import * from ..torch_core import * from ..layers import * # Cell class GenerativeModel(nn.Module...
3,594
1,194
nota1 = float(input('nota 1: ')) nota2 = float(input('nota 2: ')) media = (nota1 + nota2)/2 print('A media entre a nota 1 e a nota 2 é {}'.format(media))
154
70
"""rio_tiler.mosaic.methods.defaults: default mosaic filling methods.""" import numpy from .base import MosaicMethodBase class FirstMethod(MosaicMethodBase): """Feed the mosaic tile with the first pixel available.""" def __init__(self): """Overwrite base and init First method.""" super(Firs...
5,588
1,866
import os, sys import random import argparse from pathlib import Path from tqdm import tqdm import cv2 import math import pyexr import shutil import numpy as np PACKAGE_PARENT = '..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpat...
13,442
6,921
# -*- coding: utf-8 -*- from distutils.version import LooseVersion from marshmallow.utils import missing # Make marshmallow's validation functions importable from webargs from marshmallow import validate from webargs.core import dict2schema, ValidationError from webargs import fields __version__ = "5.3.2" __version_...
498
156
#!C:\Users\stpny\Downloads\grasp_public-master\grasp_public-master\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'imageio==2.5.0','console_scripts','imageio_remove_bin' __requires__ = 'imageio==2.5.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] =...
483
203
import logging import sys from .pipeline import MWFPipeline def build(config): config["source"] = config["source"] or {} config["tweaks"] = config["tweaks"] or [] config["converter"] = config["converter"] or {} config["generator"] = config["generator"] or [] pipeline = MWFPipeline(config["source"...
1,351
389
from django.shortcuts import render from django.http import HttpResponse import json # Create your views here. def info(request): userInfo = { 'id': '4291d7da9005377ec9aec4a71ea837f', 'name': '天野远子', 'username': 'admin', 'password': '', 'avatar': '/avatar2.jpg', 'status': 1, 'telephone': ...
21,345
7,522
import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit from matplotlib import dates import os import pickle from datetime import datetime from pprint import pprint import sys import math import traceback import time os.chdir('C:/Users/Sarah Hanna/Documents/Data/WHI long term record/co...
3,278
1,465
num = int(input("Insira um numero para descobrir se este é par ou impar: ")) if num % 2 == 0: print("Este numero é par") else: print("Este numero é impar")
161
64
""" Configuration for docs """ # source_link = "https://github.com/[org_name]/pos_multie_print" # docs_base_url = "https://[org_name].github.io/pos_multie_print" # headline = "App that does everything" # sub_heading = "Yes, you got that right the first time, everything" def get_context(context): context.brand_html =...
342
116
from .import_track import * from .reimportable import *
56
17
import os import shutil import pyfbi from xbrr.edinet.client.document_client import DocumentClient from xbrr.edinet.reader.reader import Reader from xbrr.edinet.reader.doc import Doc from xbrr.edinet.reader.aspects.finance import Finance @pyfbi.target def check(): _dir = os.path.join(os.path.dirname(__file__), "....
837
321
PRIMES = [3] def next_prime(): num = PRIMES[-1] + 2 # odd + 2 is the next odd, don't check evens for primality is_prime = False while True: lim = num**0.5 # don't check for prime factors larger than this for p in PRIMES: if p > lim: is_prime = True ...
1,096
365
from django.apps import AppConfig class PuzzleConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'puzzle'
144
49
from .client import Client from .consts import * class FutureAPI(Client): def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) # query position def get_position(self): ...
10,701
3,434
#%% # read full assignment # think algo before implementing # dont use a dict when you need a list # assignment is still = and not == # dont use itertools when you can use np.roll # check mathemathical functions if the parentheses are ok # networkx is awesome # sometimes while true is better than just too small for loo...
2,254
866
#!/usr/bin/env python import math import argparse from fractions import Fraction parser = argparse.ArgumentParser() parser.add_argument('filename') parser.add_argument('--column', '-c', required=True) parser.add_argument('--error-column', '-e') args = parser.parse_args() filename = args.filename columns = list(map(i...
1,423
395
import unittest from challenge1 import * """class Test_Read_Graph_Method(unittest.TestCase): def __init__(self): super(TestingClass, self).__init__() self.filepath = "graph_data.txt" self.vertices, self.edges = read_graph(filepath) def test_read(self): self.assertTrue(self.v...
7,968
3,514
import numpy as np from scipy.io.wavfile import read import torch def get_mask_from_lengths(lengths): max_len = torch.max(lengths).item() if torch.cuda.is_available(): ids = torch.arange(0, max_len, out=torch.cuda.LongTensor(max_len)) else: ids = torch.arange(0, max_len, out=torch.LongTens...
870
329
# Copyright 2021,2022 Sony Group Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
8,526
2,714
#!/usr/bin/env python # circuits.py - convert a Boolean circuit to an equivalent Boolean formula # # Copyright 2016 Jeffrey Finkelstein <jeffrey.finkelstein@gmail.com>. # # This file is part of NetworkX. # # NetworkX is distributed under a BSD license; see LICENSE.txt for more # information. """ ======== Circuits =====...
3,454
1,044
from typing import Dict, Tuple import torch from torch import Tensor from torchtools.tensors.function import unsqueeze class TensorGroup: def __init__(self, tensors: Dict[str, Tensor], check_validity: bool=True): self.tensors = tensors if check_validity: assert self.check_tensors_len...
4,669
1,486
from django.urls import path from django.conf.urls import url, include from django.views.generic.base import TemplateView from merlinservices import views from rest_framework.routers import DefaultRouter from rest_framework.schemas import get_schema_view from rest_framework_bulk.routes import BulkRouter #router = Defa...
5,029
1,615
import torch import torch.nn.functional as F import datetime as dt import pandas_datareader class FullyConnected(torch.nn.Module): def __init__(self, in_features, out_features, dropout=0.): super().__init__() self.fc = torch.nn.Linear(in_features, out_features) self.norm = torch....
1,134
446
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
1,148
426
# -*- coding: utf-8 -*- """ Test suite for the community-developed Python SDK for interacting with Lacework APIs. """ import pytest from laceworksdk.api.v2.datasources import DatasourcesAPI from tests.api.test_base_endpoint import BaseEndpoint # Tests @pytest.fixture(scope="module") def api_object(api): return...
687
237
"""expand_mnist.py ~~~~~~~~~~~~~~~~~~ Take the 50,000 MNIST training images, and create an expanded set of 250,000 images, by displacing each training image up, down, left and right, by one pixel. Save the resulting file to ../data/mnist_expanded.pkl.gz. Note that this program is memory intensive, and may not run on...
2,793
962
# -*- coding: utf-8 -*- """ A set of factory function to help create usual cases of coordinator """ __author__ = "Begon Jean-Michel <jm.begon@gmail.com>" __copyright__ = "3-clause BSD License" __date__ = "20 January 2015" import math from .image import * from .util import (OddUniformGenerator, NumberGenerator, ...
17,489
5,157
import pygame import numpy as np from math import * import json WHITE = (255, 255, 255) BLACK = (0, 0, 0) RAINBOW = (0, 0, 0) rainbow = True WIDTH, HEIGHT = 800, 600 #WIDTH, HEIGHT = 1600, 900 def drawLine(point1, point2, screen): if rainbow: pygame.draw.line(screen, RAINBOW, (point1[0], point1[1]), (po...
2,944
1,098
import sqlite3 book=sqlite3.connect("bookstore.db") curbook=book.cursor() #curbook.execute('''create table books (book_id integer primary key autoincrement , book_name text(20), author text(20), price integer);''') while True: x=input("want to enter data yes/no: ") if x=='yes': book_id=int(input("Ente...
708
226
tanmuContent = ''' <style> .barrage-input-tip { z-index: 1999; position: absolute; left: 10px; width: 179.883px; height: 35.7422px; line-height: 35.7422px; border-radius: 35.7422px; box-sizing: border-box; color: rgb(255, 255, 255); ...
13,110
5,065
from xrsolver import Problem import solver # This example is the second case from https://www.youtube.com/watch?v=WJEZh7GWHnw s = solver.Solver() p = Problem() x1 = p.generateVariable("x1", lb=0, ub=3) x2 = p.generateVariable("x2", lb=0, ub=3) x3 = p.generateVariable("x3", lb=0, ub=3) x4 = p.generateVariable("x4",...
871
411
# Copyright (c) 2021 ipyradiant contributors. # Distributed under the terms of the Modified BSD License. from typing import Union import ipycytoscape as cyto import ipywidgets as W import rdflib import traitlets as trt from ipyradiant.query.api import SPARQLQueryFramer from ipyradiant.rdf2nx.uri_converter import URI...
11,669
3,542
from typing import List, TypeVar from src.main.serialization.codec.codec import Codec from src.main.serialization.codec.codecCache import CodecCache from src.main.serialization.codec.object.noneCodec import NoneCodec from src.main.serialization.codec.utils.byteIo import ByteIo from src.main.serialization.codec.utils.b...
2,165
693
"""Main routines for interacting with an Apple TV.""" import asyncio import datetime # noqa from ipaddress import IPv4Address from typing import List import aiohttp from pyatv import conf, exceptions, interface from pyatv.airplay import AirPlayStreamAPI from pyatv.const import Protocol from pyatv.dmap import DmapAp...
3,049
915
import glob import os from doc2vec import read_file, embed_document def get_file_embeddings(): # Returns a list of names in list files. txt_files = glob.glob('**/*.txt', recursive=True) pdf_files = glob.glob('**/*.pdf', recursive=True) docx_files = glob.glob('**/*.docx', recursive=True) file_names...
1,323
416
#!/usr/bin/env python3 import sys import os import argparse from string import Template import re # Patch site-packages to find numpy import jinja2 if sys.platform.startswith("win"): site_packages_path = os.path.abspath(os.path.join(os.path.dirname(jinja2.__file__), "../../../ext-site-packages")) else: site_packa...
8,902
3,359
import cgi from datetime import datetime import urllib import braintree from braintree.util.crypto import Crypto from braintree.error_result import ErrorResult from braintree.exceptions.forged_query_string_error import ForgedQueryStringError from braintree.util.http import Http from braintree.successful_result import S...
3,290
940
# Generated by Django 3.0.4 on 2020-04-05 12:18 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('paint', '0006_auto_20200405_1746'), ] operations = [ migrations.AlterModelTable( name='office_expense', table=...
358
145
from flask import Flask app = Flask(__name__,static_folder='../static')
72
23
from copy import deepcopy import string from esprit import versions unicode_punctuation_map = dict((ord(char), None) for char in string.punctuation) class Query(object): def __init__(self, raw=None): self.q = QueryBuilder.match_all() if raw is None else raw if "query" not in self.q: s...
4,412
1,401
from . import models from . import serializers from rest_framework import viewsets, permissions class CompetitionViewSet(viewsets.ModelViewSet): """ViewSet for the Competition class""" queryset = models.Competition.objects.all() serializer_class = serializers.CompetitionSerializer permission_classes ...
2,074
584
# Moore Voting # Majority Element # Given an array of size n, find the majority element. # The majority element is the element that appears more than ⌊ n/2 ⌋ times. # assume at leat one element class Solution(object): def majorityElement(self, nums): count, major_num = 0, nums[0] for num in nums: ...
1,273
386
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: evmos/incentives/v1/incentives.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflect...
13,844
5,569
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
15,332
4,264
import re import urllib import numbers from clayful.models import register_models from clayful.requester import request from clayful.exception import ClayfulException class Clayful: base_url = 'https://api.clayful.io' default_headers = { 'Accept-Encoding': 'gzip', 'User-Agent': 'clayful-python', 'Clayfu...
5,598
2,131
from dataclasses import dataclass from typing import Dict from racecar_gym.bullet import load_world, load_vehicle from racecar_gym.tasks import Task, get_task from racecar_gym.core import World, Agent from .specs import ScenarioSpec, TaskSpec def task_from_spec(spec: TaskSpec) -> Task: task = get_task(spec.task_n...
1,478
466
#! /usr/bin/env python3 """Implementation of the main functions of the application: editing user data, thematic search, other console commands""" import sys import re from collections import Counter from .report import Report from . import vklib as vk from .vklib import apply_vk_method from .usrdata import UsrData fr...
26,972
9,218
#!/usr/bin/env python # -*- coding: utf-8 -*- import copy import argparse import cv2 as cv import numpy as np import mediapipe as mp from utils import CvFpsCalc def get_args(): parser = argparse.ArgumentParser() parser.add_argument("--device", type=int, default=0) parser.add_argument("--width", help='c...
10,226
4,094
"""Vista del inventario del modulo de prestamos tecnologicos.""" # Django REST Framework from rest_framework import viewsets, mixins # Permisos from rest_framework.permissions import IsAuthenticated from andromeda.modules.inventory.permissions import IsAdmin, IsStaff # Modelos from andromeda.modules.loans.models imp...
1,413
383
import matplotlib.pyplot as plt x = ["N=1", "N=2", "N=3", "N=4", "N=5","N=6"] y = [0.9365, 0.9865, 0.9895, 0.9950,0.9880,0.9615] rects = plt.barh(x, y, color=["red", "blue", "purple", "violet", "green", "black"]) for rect in rects: # rects 是三根柱子的集合 width = rect.get_width() print(width) plt.text(width, rec...
876
508
from _pytest.logging import LogCaptureFixture from loguru import logger def test_log_configuration(caplog: LogCaptureFixture) -> None: message = "Test message" logger.info(message) assert message in caplog.text
226
68
n, k, v = int(input()), int(input()), [] for i in range(n): v.append(int(input())) v = sorted(v, reverse=True) print(k + v[k:].count(v[k-1]))
142
62
#!/usr/bin/env python3 """ Date : 2021-09-06 Purpose: learning to work with strings """ import argparse # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Crow\'s Nest -- choose the correct article', ...
1,160
347
""" Clip rendering helpers. """ import vapoursynth as vs from enum import Enum from threading import Condition from typing import BinaryIO, Callable, Dict, List, Optional, TextIO, Union from concurrent.futures import Future from functools import partial from .progress import Progress, BarColumn, FPSColumn, TextColumn...
9,397
2,951
from django import forms from django.utils.translation import ugettext_lazy as _ from geekjobs.models import Job """ class JobForm(forms.Form): title = forms.CharField(label='Job title', max_length=380) city = forms.CharField(label='City', max_length=100, required=False) state = forms.ChoiceField(label='St...
1,689
509
import math from typing import Tuple, Set from solutions.runner.base_solution import BaseSolution from solutions.runner.readers.base_reader import BaseReader TREE = "#" class Day3Reader(BaseReader): @staticmethod def transform_raw_line(line: str): line = line.strip() return line class Da...
1,133
358
import base58 import datetime import json import os import pandas as pd import requests import shutil import time import web3 import yaml from Crypto.Cipher import AES, PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto.Random import get_random_bytes from decimal import Decimal from typing import Any, Callable fro...
10,003
3,445
import requests from bs4 import BeautifulSoup def locate(i): my_loc = requests.get('https://ipinfo.io').json() if str(i).isdigit(): return 'Invalid input. Try a string.' else: if i == 'ip': return my_loc['ip'] elif i == 'city' or i == 'capital': return my_loc['city'] elif i == 'region' or i == 'stat...
2,108
918
#! python3 # __author__ = "YangJiaHao" # date: 2018/1/26 class Solution: def lengthOfLongestSubstring(self, s: str) -> int: d = dict() l, r = 0, 0 res = 0 while r < len(s): if s[r] not in d: d[s[r]] = None r += 1 res = max(...
1,045
321
import asyncio import os from youwol_utils import WhereClause, QueryBody, Query, Path, flatten from .configurations import Configuration from .utils import format_download_form, post_storage_by_chunk, md5_from_folder from .utils_indexing import format_doc_db_record, post_indexes, get_version_number_str async def in...
2,636
782
import urllib.request import json url = 'http://graph.facebook.com/fmasanori' resp = urllib.request.urlopen(url).read() data = json.loads(resp.decode('utf-8')) print(data)
174
65
__all__ = [ 'AdminCmd', 'CreateComplexModelCmd', 'CreateSimpleModelCmd', 'EnableBashCompleteCmd', ] from argparse import RawDescriptionHelpFormatter from .command import OasisBaseCommand, OasisComputationCommand class EnableBashCompleteCmd(OasisComputationCommand): """ Adds required command ...
1,769
476
# Copyright (C) 2018 The python-bitcoin-utils developers # # This file is part of python-bitcoin-utils # # It is subject to the license terms in the LICENSE file found in the top-level # directory of this distribution. # # No part of python-bitcoin-utils, including this file, may be copied, # modified, # propagated, or...
1,802
617
def get_field_name_from_line(line): return line.split(':')[1].strip() def remove_description(line): if '-' in line: return line.split('-')[0].strip() else: return line def split_multiple_field_names(line): if ',' in line: field_names = line.split(',') return map(lambda ...
801
277
from distutils.core import setup setup( name='plex', version='0.1.0', author='Christian Dean', author_email='c1dea2n@gmail.com', packages=['plex'], license='MIT', platforms='any', description='Generic, lighweight regex based lexer.', long_description=open('README.md').read(), )
317
106
from django.contrib import admin from .models import KwikPost, Comment, Like # Register your models here. @admin.register(KwikPost) class KwikPostAdmin(admin.ModelAdmin): list_display = ['user', 'featured_image', 'slug', 'post_body', 'created_at'] list_filter = ['created_at'] prepopulated_fields = {'slug...
595
195
# -*- coding: utf-8 -*- from __future__ import absolute_import import six import sys from ..client import client from .util import json def convert_to_solve_object(resp, **kwargs): from . import types _client = kwargs.pop('client', None) if isinstance(resp, list): return [convert_to_solve_obje...
3,113
994