text
string
size
int64
token_count
int64
from elasticsearch import Elasticsearch from flask import request, jsonify from flask_restful import Resource from db.manager import get_conn import settings conn = get_conn() def append_range_filter(f, key, _from, to): d = {} if _from or to: d['range'] = {} d['range'][key] = {} if _fro...
2,079
646
import sys import unittest from contextlib import contextmanager try: from io import StringIO except ImportError: from StringIO import StringIO from vpk import cli @contextmanager def capture_stdout(): new_out = StringIO() old_out = sys.stdout try: sys.stdout = new_out yield sys....
3,056
1,054
from _LogLikelihood import LogLikelihood from _LogPrior import LogPrior #from _ScaleDependentLogLikelihoodGaussian import ScaleDependentLogLikelihoodGaussian from _ScaleDependentLogPrior import ScaleDependentLogPrior
218
65
# To pass env vars to Python scripts run by Publik in services which remove custom env vars: # https://unix.stackexchange.com/questions/44370/how-to-make-unix-service-see-environment-variables # So we hardcode the values in the file below when the container starts import sys sys.path.insert(0, "/home") from pyenv impor...
1,768
716
import numpy from torch.utils.data import DataLoader from tqdm import tqdm from loss.FocalLoss import FocalLossForSigmoid import torch from metrics.calculate_metrics import calculate_metrics import shutil from metrics.average_meter import AverageMeter import torch.multiprocessing from torch.nn.utils.clip_gra...
8,377
2,416
import os from PIL import Image import numpy from PIL import ImageChops """ TESTED: No duplicates in: - within validation images first part (stopped because of training - took to much time) """ image_path="../../IR_images/combined_dataset/val_images/images" # image_path="../../IR_images/combined_data...
961
321
import os, glob from dateutil import parser from bs4 import BeautifulSoup ext = lambda line, cap: line.replace("\s", "").replace(cap, "").strip() def write_post(doc): meta = { 'title' : ext(doc[0], "TITLE:"), 'date' : parser.parse(ext(doc[2], "DATE:")).strftime("%Y-%m-%d"), 'tag' : ext...
1,983
683
import numpy as np from .layer import Layer class ReshapeLayer: def __init__(self, layer_name, input_shape, output_shape): super.__init__(layer_name) self.input_shape = input_shape self.output_shape = output_shape def __repr__(self): s = "ReshapeLayer(input_shape={}, output_sha...
702
193
def specialization(a, spec, jobs): if a>=0 and a<=2: return(spec + ': интерес к данной профессиональной сфере не выражен') elif a>=3 and a<=6: return(spec + ': профессиональная направленность и интерес выражены в средней степени. ' + 'Возможно вам будут интересны такие профессии будущего, как ' + j...
3,342
1,401
# Functions for use in downloading files. import logging, os, requests, json, hashlib, urllib from requests_toolbelt.utils import dump from retry import retry logger = logging.getLogger(__name__) def create_md5(worker, filename, save_path): # Generate md5 logger.info('{}: Generating md5 hash for {}.'.format...
4,003
1,265
# coding: utf-8 import re import datetime from .feed import read_file __author__ = "Rafał Karoń <rafalkaron@gmail.com>" def clipps_str_to_html_str(clipps_str): """Return a string that contains the converted \"Kindle Clippings.txt file\" to HTML.""" # ADD ELEMENTS (SVG favicon encoded with: https://yoksel.gith...
9,246
4,324
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import #from Domain import Domain from future import standard_library standard_library.install_aliases() from .HelicopterHover import HelicopterHover, HelicopterHoverExtended fro...
1,308
374
from construct import Adapter, Int32ub, Enum class EnumAdapter(Adapter): def __init__(self, enum_class, subcon=Int32ub): super().__init__(Enum(subcon, enum_class)) self._enum_class = enum_class def _decode(self, obj, context, path): return self._enum_class[obj] def _encode(self, ...
365
119
import vagrant import os from subprocess import CalledProcessError from strider.common.instance_data import InstanceData, SshData import strider.common.logger class Vagrantbox(object): def __init__(self, name=None, ssh=None, basebox=None, bake_na...
2,740
720
#!/usr/bin/env python # -*- coding: utf-8 -*- """ The Academy / ASC Common LUT Format Sample Implementations are provided by the Academy under the following terms and conditions: Copyright © 2015 Academy of Motion Picture Arts and Sciences ("A.M.P.A.S."). Portions contributed by others as indicated. All rights reserv...
4,739
1,811
## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to non...
10,177
3,171
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name="hubmap-sdk", version="1.0.1", author="Hubmap", author_email="api-developers@hubmapconsortium.org", description="Python Client Libary to use HuBMAP web services", long_de...
880
313
# -*- encoding:utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import unittest import pyparsing from mysqlparse.grammar.data_type import data_type_syntax class DataTypeSyntaxTest(unittest.TestCase): def test_bit(self): self.assertEquals(data_type_syntax.par...
14,095
4,228
import pandas as pd from spandex import TableLoader import pandas.io.sql as sql loader = TableLoader() def db_to_df(query): """Executes SQL query and returns DataFrame.""" conn = loader.database._connection return sql.read_frame(query, conn) ## Export to HDF5- get path to output file h5_path = loader.ge...
2,615
974
import matplotlib.pyplot as plt import matplotlib.dates as mdates import seaborn as sns import pandas as pd from minder_utils.formatting.label import label_by_week, label_dataframe from minder_utils.feature_engineering import Feature_engineer from minder_utils.feature_engineering.calculation import * from minder_utils....
7,060
2,494
# https://practice.geeksforgeeks.org/problems/cyclically-rotate-an-array-by-one2614/1 # Given an array, rotate the array by one position in clock-wise direction. # Input: # N = 5 # A[] = {1, 2, 3, 4, 5} # Output: # 5 1 2 3 4 def rotate_cycle(a): n = len(a) tmp = a[-1] for i in range(1,n): a[-i] ...
442
210
# Copyright 2015 The TensorFlow 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 applica...
10,800
3,763
from .base import BaseTestCase pass
38
13
from backend.settings import BASE_DIR import os import subprocess import stat rupture_dir = os.path.abspath(os.path.join(BASE_DIR, os.pardir)) client_dir = os.path.join(rupture_dir, 'client') def inject(victim): _create_client(victim) _create_injection(victim) _run_injection(victim) def _create_clien...
1,559
566
from urllib.parse import urlencode from django.conf import settings from django.contrib.sites.shortcuts import get_current_site def provider_logout_url(request): """ This function is used to construct a logout URL that can be used to log the user out of the Identity Provider (Authentication Service). ...
952
292
import pymongo import dns import serial from pymongo import MongoClient import struct cluster = MongoClient("") serialPort = serial.Serial(port= "COM1", baudrate=9600 ,bytesize =8 , timeout =None, parity='N',stopbits=1) db=cluster["<greenHouse>"] collection = db["greenhouses"] while serialPort.readline(): resul...
978
321
# Copyright 2017 Artyom Losev # Copyright 2018 Kolushov Alexandr <https://it-projects.info/team/KolushovAlexandr> # License MIT (https://opensource.org/licenses/MIT). { "name": """E-commerce Category Cache""", "summary": """Use this module to greatly accelerate the loading of a page with a large number of produ...
837
301
import pkg_resources __all__ = [] def check_pdpbox(): try: ver = pkg_resources.get_distribution("pdpbox").version assert ver >= '0.2.0+13.g73c6966', f'''You have version {ver} of pdpbox. Use of this function requires pdpbox>=0.2.0+13.g73c6966, which is not currently ...
848
266
# -*- coding: utf-8 -*- """ Created on Thu Dec 11 11:37:39 2014 @author: sm1fg Construct the magnetic network and generate the adjustments to the non-magnetic atmosphere for mhs equilibrium. """ import os import warnings import numpy as np import astropy.units as u from scipy.interpolate import RectBivaria...
18,526
8,410
from rest_framework import serializers from s3_file_uploads.constants import ACCESS_CONTROL_TYPES, PRIVATE from s3_file_uploads.models import UploadedFile class UploadedFileSerializer(serializers.ModelSerializer): file_name = serializers.CharField(source='file.name', read_only=True) file = serializers.URLFie...
961
282
""" Copyright (c) 2015-present, Philippine-California Advanced Research Institutes- The Village Base Station Project (PCARI-VBTS). All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. """ from django.contrib import messages ...
1,873
571
'''1. Faça um programa que pede para o usuário digitar uma palavra e imprima cada letra em uma linha.''' #Informando frase a ser verificada frase = input('Digite uma palavra: ') #Convertendo frase em palavras, e imprimindo depois for letra in frase: print(letra)
268
95
from tfbldr.nodes import Conv2d from tfbldr.nodes import ConvTranspose2d from tfbldr.nodes import VqEmbedding from tfbldr.nodes import BatchNorm2d from tfbldr.nodes import Linear from tfbldr.nodes import ReLU from tfbldr.nodes import Sigmoid from tfbldr.nodes import Tanh from tfbldr.nodes import OneHot from tfbldr.node...
16,307
6,866
# -*- coding: utf-8 -*- def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) def story_points(start): for i in range(10): result = fibonacci(i) if result >= start: break return result
311
117
from typing import List from typing import Union import numpy as np import torch from cata.teachers.ensembles import base_teacher_ensemble from cata.utils import custom_functions class BothRotationTeacherEnsemble(base_teacher_ensemble.BaseTeacherEnsemble): """Teacher ensemble (primarily for mean-field limit regi...
6,162
1,831
import json import logging import os import shlex import subprocess from pathlib import Path from types import SimpleNamespace import coloredlogs import fire from .adminFiles import ( DockerComposeFile, DotenvFile, GitlabCIFile, JsonFile, PackageJsonFile, Pipfile, RuntimeTxtFile, YarnR...
7,176
2,376
a = 'ARRYR' b = 'ARSYS' levenshtein(a,b) # ANSWER a) # It quantifies the number of single-letter changes to morph one into the other # # ANSWER b) # We could encode the 'price' of changing between particular amino acids # thereby acknowledging that some substitutions are more or less costly/likely
300
99
from dazzler.system import Page from dazzler.components import core from tests.components import ts_components as tsc page = Page( __name__, core.Container([ tsc.TypedComponent( 'override', children=core.Container('foobar'), num=2, text='foobar', ...
743
229
""" An application dedicated to creating, editing, and deleting Gists in GitHub """ from __future__ import absolute_import import toga import pyperclip from toga.style import Pack from toga.style.pack import COLUMN, ROW from .common.Search import search from functools import partial class GistsGetter(toga.App): d...
4,464
1,354
from quanser.hardware import HIL, HILError, PWMMode from quanser.multimedia import Video3D, VideoCapture, Video3DStreamType, MediaError, ImageFormat, ImageDataType from quanser.devices import RPLIDAR, RangingMeasurements, RangingMeasurementMode, DeviceError, RangingDistance from .q_misc import Utilities import numpy as...
7,401
2,824
'''Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. OBS: considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1.''' '''print('--' * 15) pri...
1,689
781
import itertools import math import simulate import harvesting import plot from decimal import setcontext, ExtendedContext # Don't raise exception when we divide by zero #setcontext(ExtendedContext) #getcontext().prec = 5 def compare_prime_vs_rebalancing(series, years=30, title=''): (r1, r2) = itertools.tee(serie...
919
355
import random import string import hashlib def make_salt(): return ''.join(random.choice(string.letters) for x in xrange(5)) # Implement the function valid_pw() that returns True if a user's password # matches its hash. You will need to modify make_pw_hash. def make_pw_hash_with_salt(name, pw, salt): h = h...
492
191
from datetime import datetime from hdx.data.dataset import Dataset from hdx.scraper.utilities import ( get_isodate_from_dataset_date, string_params_to_dict, ) class TestUtils: def test_string_params_to_dict(self): result = string_params_to_dict("a: 123, b: 345") assert result == {"a": "1...
769
306
from random import randrange from django.conf import settings from django.contrib.contenttypes.fields import GenericRelation from django.db import models from hitcount.models import HitCountMixin, HitCount from imagekit.models import ProcessedImageField from pilkit.processors import ResizeToFill from django_cleanup im...
3,796
1,372
import configparser import logging from flask import Flask from flask_pymongo import PyMongo from Crypto.PublicKey import RSA # Value mapping LOG_LEVELS = {'INFO': logging.INFO, 'DEBUG': logging.DEBUG, 'WARN': logging.DEBUG, 'ERROR': logging.ERROR} # Create application app = Flask(__name__) # Read external config co...
1,361
461
import sys import numpy as np import cv2 from easydict import EasyDict as edict from base_tracker import BaseTracker import path_config sys.path.append("external/SiamDW/lib") from tracker.siamrpn import SiamRPN import models.models as models from utils.utils import load_pretrain class SiamDW(BaseTracker): def __...
1,587
587
import math import torch class DQN(torch.nn.Module): def __init__(self, action_space, history=4, hidden_size=512, noisy_std=0.1, quantile=True): super().__init__() self.atoms = 200 if quantile else 51 self.action_space = action_space self.quantile = quantile self.conv1 =...
3,346
1,251
import urllib.request from html.parser import HTMLParser from urllib import parse from modules.base.handle_timeout import timeout class ElementsFinder(HTMLParser): def __init__(self, base_url, page_url): super().__init__() self.base_url = base_url self.page_url = page_url self.lin...
1,479
431
import numpy as np import torch from torchvision.utils import make_grid from base import BaseTrainer from utils import inf_loop, MetricTracker, confusion_matrix_image import copy import sys import time from model.metric import Accuracy, TopkAccuracy def get_top_k(x, ratio): """it will sample the top 1-ratio of th...
7,460
2,267
from prob.problems import * from opti.de import DE from opti.cmaes import CMAES from opti.cmaes_origin import CMAESO from opti.cmaes_maes import CMAESM from opti.cmaes_large import CMAESL # beta from opti.cmaes_bipop import CMAESB if __name__ == "__main__": TaskProb = Sphere(50, -50, 50) Task = DE(TaskProb, ...
341
151
from BaiduMapAPI.common import convertCoord, expandUp import pytest def test_convertCoord(): coord = convertCoord("12.32323,56.23422") assert coord == "12.32323,56.23422" coord = convertCoord((12.32323,56.23422)) assert coord == "12.32323,56.23422" def test_expandUp(): test_dict = {"a" : "A", "b":...
574
279
""" PyCBA - Utility functions for interacting with PyCBA """ import re import numpy as np from typing import Tuple def parse_beam_string( beam_string: str, ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """ This function parses a beam descriptor string and returns CBA input vectors. The ...
3,520
1,195
# Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
10,363
3,473
"""Constants for the System Bridge integration.""" import asyncio from aiohttp.client_exceptions import ( ClientConnectionError, ClientConnectorError, ClientResponseError, ) from systembridge.exceptions import BridgeException DOMAIN = "system_bridge" BRIDGE_CONNECTION_ERRORS = ( asyncio.TimeoutError,...
422
119
""" BIO measure - defines and describes a measure for BIO compliance """ from domain.base import Base class Measure(Base): """ Measures that help to in BIO compliance. """ _explain = None _not_applicable = None def __init__(self, identifier, description, identifiers, url=None, done=False): ...
1,705
506
from cs50 import get_string text = get_string("Text: ") text_length = len(text) letters = 0 sentences = 0 words = 1 for i in range(text_length): if text[i].isalpha(): letters += 1 for i in range(text_length): if ord(text[i]) == 46 or ord(text[i]) == 33 or ord(text[i]) == 63: sentences += 1 f...
615
266
from django.contrib import admin from .models import Category, ImagePost, Location # Register your models here. admin.site.register(ImagePost) admin.site.register(Category) admin.site.register(Location)
206
57
import math from random import randint # pylint: disable=I0011,invalid-name class Vector(object): def __init__(self, x, y=None): self.x = x if y is None: self.y = x else: self.y = y def get_distance(self, other): distance = self.get_distance_components(o...
1,574
545
from math import floor remove_spaces = lambda inlst: [i for i in inlst if i != ' '] def sf2i(inp): if float(inp).is_integer(): return str(int(inp)) else: return str(inp) def fix_signs(inlst): i = 0 while i < len(inlst): if inlst[i] in '+-': # first sign is detected ...
12,532
4,688
import pytest from pytest_mock import MockerFixture from pystratis.api.balances import Balances from pystratis.core.types import Address from pystratis.core.networks import CirrusMain def test_all_strax_endpoints_implemented(strax_swagger_json): paths = [key.lower() for key in strax_swagger_json['paths']] for...
2,556
819
def isPerCube(n): x = n**(1/3) x= x+0.5 x = int(x) if x**3==n: return True return False """ x = 2 while True: y = n / (x * x) if (x == y): print(x) if x == int(x): return True else: return False ...
381
143
## This program prints out the first 10 square roots that are even ## for x in range(1,10): y = (2*x)**2 # If n^2 is even hence n must be even as well print(y)
179
62
import sys sys.path.append("/sandbox/code/github/threefoldtech/zeroCI/backend") from redis import Redis from health_recover import Recover from utils.utils import Utils recover = Recover() class Health(Utils): def get_process_pid(self, name): cmd = f"ps -aux | grep -v grep | grep '{name}' | awk '{{pri...
1,690
526
"""Module containing class `RecordingImporter`.""" from pathlib import Path import itertools import logging import os from django.db import transaction from vesper.command.command import CommandExecutionError from vesper.django.app.models import ( DeviceConnection, Job, Recording, RecordingChannel, RecordingFil...
13,284
3,528
############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from odoo import fields, models class ResCompany(models.Model): _i...
1,096
322
import requests def random_quote(type=''): '''A function to get random quotes''' if type == "today": response_quote = requests.get("https://zenquotes.io/api/today/ff5e73b15a05ca51951b758bd7943ce803d71772") if response_quote.status_code == 200: quote_data = response_quote.json() ...
2,033
670
from math import prod from pathlib import Path class BitStream: 'Deliver integers from a stream of bits created from a hexadecimal string' bit_str: str pos: int def __init__(self, hex_nibbles_str: str) -> None: def binary_nibble_str(hex_nibble_str: str) -> str: 'Convert, for examp...
3,401
1,138
# -*- coding: utf-8 -*- """ Created on Wed Mar 3 17:13:15 2021 Database: https://www.kaggle.com/c/santander-customer-satisfaction @author: Herikc Brecher """ # Import from libraries from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.model_selection i...
6,328
2,202
# write your code here from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String, Integer from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///flashcard.db?check_same_thread=False') Base = declarative_base() Session = sessio...
4,502
1,322
from dataclasses import dataclass from datetime import datetime import json from types import SimpleNamespace import isce3 from isce3.core import LUT2d, Poly1d, Orbit from isce3.product import GeoGridParameters import numpy as np from ruamel.yaml import YAML from shapely.geometry import Point, Polygon from compass.ut...
9,862
3,161
from web import create_app import ntplib if __name__ == '__main__': app = create_app(debug=False) app.run(host='0.0.0.0', port=5000)
142
60
import datetime from methinks.db import Entry import pytest from server.app import create_app from server.app import db as _db from sqlalchemy import event from sqlalchemy.orm import sessionmaker @pytest.fixture(scope="session") def app(request): """ Returns session-wide application. """ return create...
2,227
664
import os import environ env = environ.Env( # set casting, default value DEBUG=(bool, False) ) # reading .env file environ.Env.read_env() # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development s...
3,339
1,165
#!/usr/bin/python2 """ Simple socket server using threads """ import socket import sys from thread import * import os import logging HOST = '' # Symbolic name meaning all available interfaces PORT = 9998 # Arbitrary non-privileged port LOG_FORMAT = '%(asctime)-15s %(message)s' SMART_LOG = '/var/log/smart/smart...
2,891
840
import numpy as np from utils.helpers import * percentiles = [10, 25, 50, 75, 90] percentile_keys = ["ten", "twenty_five", "fifty", "seventy_five", "ninty"] def calc_drh(flow_matrix): """Dimensionless Hydrograph Plotter""" average_annual_flow = calculate_average_each_column(flow_matrix) number_of_rows = ...
1,348
453
import torch.nn as nn __all__ = ["Model"] class Model(nn.Module): pass
78
32
from django.contrib.auth.models import Group, Permission from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from .statistical import UserPagination from apps.meiduo_admin.serializer.user_group import UserGroupSerializer, GroupPerSerializer class UserGroupView(ModelViewSet): ...
591
160
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.conf.urls import url, include from rest_framework import routers, serializers, viewsets from . import views router = routers.DefaultRouter() router.register(r'announcements', views.AnnouncementViewSet) urlpatterns = [ url...
355
115
from app.db.wrappers import ClickHouse DBS = {} async def init_databases(config): """ Usage example DBS["clickhouse"] = await ClickHouse.init_async(config["clickhouse"]) DBS["mysql"] = await MySQL.init_async(config["mysql"]) """ pass async def shutdown_databases(): """ await ClickHo...
414
139
from ravendb.documents.conventions.document_conventions import DocumentConventions from ravendb.exceptions.exceptions import DatabaseDoesNotExistException from ravendb.http.request_executor import RequestExecutor from ravendb.http.server_node import ServerNode from ravendb.http.topology import UpdateTopologyParameters ...
1,108
317
#!/usr/bin/env python3 import csv import logging import logging.config import re import argparse import json import sys from .log import log from . import datatypes logger = logging.getLogger(__name__) default_column_mapping = { 'DTSTART': 0, 'DTEND': 1, 'DTSTAMP': 2, 'UID': 3, 'CREATED': 4, ...
14,091
4,136
# -*- coding: utf-8 -*- """ Created on Mon Oct 11 18:00:28 2021 @author: Mohammad Eslami """ try: import rpy2 print('===> rpy2 version: ', rpy2.__version__) from rpy2.robjects.packages import importr # import rpy2's package module import rpy2.robjects.packages as rpackages # R vector of ...
1,462
480
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-10-04 19:47 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('financial_activities', '0004_merge_20160928_1603'), ] operations = [ migrations.Ren...
8,949
3,068
import json import os import pickle import numpy as np import pandas as pd import pytest from barrage.utils import io_utils @pytest.fixture() def sample_dict(): return {"unit": "test"} def test_save_json(artifact_path, sample_dict): filename = "unit_test.json" io_utils.save_json(sample_dict, filename,...
2,654
921
import asyncio import requests from bs4 import BeautifulSoup from datetime import date, datetime import discord import numpy as np from urllib.error import HTTPError import yt_dlp as youtube_dl from discord.ext import commands import os from pytz import timezone from yt_dlp.utils import DownloadError, ExtractorError fr...
20,998
6,759
""" Given an integer number n, return the difference between the product of its digits and the sum of its digits. """ class Solution: def subtractProductAndSum(self, n: int) -> int: if n < 10: return 0 running_prod = 1 running_sum = 0 while n > 0: re...
480
138
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from dotenv import load_dotenv load_dotenv() import os import json import requests from concurrent.futures import ThreadPoolExecutor from flask import Flask, flash, request, redirect, url_for, session from video_captioning.main import upload_vid...
1,031
345
from http import HTTPStatus from requests.exceptions import SSLError from pytest import fixture from unittest import mock from tests.unit.mock_for_tests import ( CYBERCRIME_RESPONSE_MOCK, EXPECTED_DELIBERATE_RESPONSE, EXPECTED_OBSERVE_RESPONSE, EXPECTED_RESPONSE_500_ERROR, EXPECTED_RESPONSE_404_ER...
5,154
1,784
#!/usr/bin/env python # encoding: utf-8 """ untitled.py Created by Jérémie on 2013-10-26. Copyright (c) 2013 __MyCompanyName__. All rights reserved. """ """ # Problem 1 lim=1000 s=0 for i in range(lim): if i%3==0 or i%5==0: s+=i print s print sum([x for x in range(1000) if x % 3== 0 or x % 5== 0]) """ """ # Probl...
2,658
1,935
""" @file @brief Function to test others functionalities """ import os import pandas from pyquickhelper.loghelper import fLOG from ..faq.faq_matplotlib import graph_cities from ..special import tsp_kruskal_algorithm, distance_haversine def american_cities(df_or_filename, nb_cities=-1, img=None, fLOG=fLOG): """ ...
1,900
663
#task 1 r=float(input("Enter the radius of the circle?\n")) pi=3.143 area=pi*r*r print("Area of the circle is ",area) #task 2 x=input("Enter the file name\n") print(x+".py")
175
76
"""Simple NTP spoofing tool.""" from pypacker.layer12.ethernet import Ethernet from pypacker.layer3 import ip from pypacker.layer4.udp import UDP from pypacker.layer567 import ntp from pypacker import psocket # interface to listen on IFACE = "wlan0" # source address which commits a NTP request and we send a wrong ans...
2,049
946
#!/usr/bin/env python3 from __future__ import print_function from builtins import range, map import unittest import sys import pickle import numpy as np from mpmath import mp from testutils import DpkTestCase from .numexpr import NumericExpression from .numexpr import isclose from .basics import OffsetExpression, D...
7,524
2,860
from progression import Progression class FibonacciProgression(Progression): def __init__(self, first=0, second=1): super().__init__(start=first) self._previous = second - first def _advance(self): self._previous, self._current = self._current, self._previous + self._current ...
468
149
import numpy as np from numba import njit, prange from openamundsen import constants, constants as c, heatconduction from openamundsen.snowmodel import SnowModel from . import snow class MultilayerSnowModel(SnowModel): def __init__(self, model): self.model = model s = model.state.snow num...
18,587
6,738
# scripts/custom_task_manager.py import os import subprocess from abc import ABCMeta, abstractmethod from pretty_printer import * class CustomTaskManager(object): def __init__(self): self.tasks = list() def printMessages(self): for task in self.tasks: task.printHelpMessage() de...
2,746
848
def abbreviate(): pass
27
10
from django.urls import path from django.contrib.auth.views import LoginView from .views.activity_view import * from .views.activity_type_view import * from .views.event_view import * from .views.flow_view import * from .views.lane_view import * from .views.pool_view import * from .views.process_type_view import * from...
3,961
1,259
import unittest from pysapets.gorilla import Gorilla from pysapets.animal import Animal import pysapets.constants as constants from unittest.mock import patch from io import StringIO from copy import deepcopy class GorillaTest(unittest.TestCase): def setUp(self): self.gorilla = Gorilla() self.friends = [se...
2,106
730