text
string
size
int64
token_count
int64
# Generated by Django 2.2 on 2020-08-01 08:08 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users', '0013_auto_20200731_1810'), ] operations = [ migrations.AlterField( model_name='profile',...
1,580
666
from typing import Any, List, Callable from fastapi import APIRouter, HTTPException, status, BackgroundTasks from app import schemas from app.core import docker_client import json from copy import deepcopy router = APIRouter() @router.get("/images", response_model=schemas.DockerImageRespond) def get_docker_image(...
762
236
"""Model-related utilities. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from . import backend as K from .utils.generic_utils import has_arg from .utils.generic_utils import to_list from .engine.input_layer import Input from .engine.input_layer import...
10,409
2,765
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from __future__ import unicode_literals import json import os import os.path import subprocess import sys import unittest import pytest from ...__main__ import TESTING_TOOLS_ROOT CWD = os.getcwd() DATA_DIR = os.path.join...
53,602
17,765
''' Wavelet kernel slice allows kernel operation on feature subset active_dims is iterable of feature dimensions to extract input_dim must equal dimension defined by active_dims ''' import numpy as np import tensorflow as tf from .. import util from . import kernel from .kernel_extras import * class WaveletSlice(ke...
2,223
771
#!/usr/bin/python3 #program to parse png images and change images # cmd: python3 transform.py # you must have local input/ and output/ directories # # name: R. Melton # date: 12/27/20 # cmdline: python transform.py cmd show image='city.png' --ulx=1 --uly=2 --brx=0 --bry=9 # python transform.py show city.png #...
8,084
3,051
""" Would you rather? This plugin includes would you rather functionality """ import asyncio import random import re import discord import bot import plugins from pcbot import Config client = plugins.client # type: bot.Client db = Config("would-you-rather", data=dict(timeout=10, responses=["**{name}** would **{cho...
4,563
1,303
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Copyright 2019-2020 ARM Limited or its affiliates # # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the...
5,690
1,780
import random import time from multiprocessing import Pool def worker(name: str) -> None: print(f'Started worker {name}') worker_time = random.choice(range(1, 5)) time.sleep(worker_time) print(f'{name} worker finished in {worker_time} seconds') if __name__ == '__main__': process_names = [f'compu...
437
153
# -*- coding: utf-8 -*- """ Created on Mon Sep 7 11:48:59 2020 @author: mazal """ """ ========================================= Support functions of pydicom (Not sourced) ========================================= Purpose: Create support functions for the pydicom project """ """ Test mode 1 | Basics...
45,541
13,758
import re regex = re.compile(r'[\n\r\t]') def acm_digital_library(soup): try: keywords = set() keywords_parent_ol = soup.find('ol', class_="rlist organizational-chart") keywords_divs = keywords_parent_ol.findChildren('div', recursive=True) for kw_parent in keywords_divs: ...
8,378
2,551
from django.db import models from django.urls import reverse from django.utils import timezone from django.utils.safestring import mark_safe from django.conf import settings MAX_LEN_AUTHORS_FIELD = 512 CITATION_FORMAT_FLAVORS = ['html', 'ris', 'bibtex', 'biblatex'] DEFAULT_KEYWORDS = ['surface', 'topography'] class...
6,642
2,080
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-07-24 19:36 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('vendor', '0002_store_image'), ] operations = [ migrations.AddField( ...
489
165
""" Your module description """ """ this is my second py code for my second lecture """ #print ('hello world') # this is a single line commment # this is my second line comment #print(type("123.")) #print ("Hello World".upper()) #print("Hello World".lower()) #print("hello" + "world" + ".") #print(2**3) #my_st...
440
178
def play_recursively_combat(p1: list, p2: list) -> bool: rounds = set() winner = None while len(p1) > 0 and len(p2) > 0: r = tuple(p1 + [-1] + p2) if r in rounds: return True else: rounds.add(r) c1 = p1.pop(0) c2 = p2.pop(0) if c1 <= ...
1,579
650
from enum import Enum class LoginOpCode(Enum): ''' Opcodes during login process ''' LOGIN_CHALL = 0x00 LOGIN_PROOF = 0x01 RECON_CHALL = 0x02 # currently do not in use RECON_PROOF = 0x03 # currently do not in use REALMLIST = 0x10 class LoginResult(Enum): ''' Error codes ''' SUCC...
335
133
# -*- coding: utf-8 -*- from .LineApi import LINE from .lib.Gen.ttypes import *
80
33
''' Created on Jun 17, 2021 @author: Sean ''' import PDF2CSV_GUI def main(): j = PDF2CSV_GUI.Convert_GUI() if __name__ == "__main__": main()
164
83
#!/usr/bin/python import praw reddit = praw.Reddit('mob-secondbot') subreddit = reddit.subreddit("learnpython") for submission in subreddit.hot(limit=5): print("Title: ", submission.title) print("Text: ", submission.selftext) print("Score: ", submission.score) print("---------------------------------...
325
102
from subprocess import Popen, PIPE, call name = "kazuate_liar.o" src = """ #include <iostream> #include <random> using namespace std; int main() { random_device rd; mt19937 mt(rd()); uniform_int_distribution<int> randfive(0, 4); uniform_int_distribution<int> randint(1, 100); int count = 0; ...
1,052
414
""" Terrafort Generate terraform templates for specific resources """ import click from .providers.aws import Aws @click.group() @click.option('--commands', is_flag=True, help="Output import commands instead of a terraform template") @click.version_option() @click.pass_context def cli(ct...
649
219
import discord import app_util class Ping(app_util.Cog): def __init__(self, bot: app_util.Bot): self.bot = bot @app_util.Cog.command( command=app_util.SlashCommand( name='ping', description='shows avg ping of client' ), guild_id=877399405056102431 ) async ...
528
210
#!/usr/bin/env python3 import sys import re import numpy as np from PIL import Image moves = { 'e': (2, 0), 'se': (1, 2), 'sw': (-1, 2), 'w': (-2, 0), 'nw': (-1, -2), 'ne': (1, -2) } # Save (x, y): True/False in tiles. True = black, False = white. tiles = {} for line in open(sys.argv[1]).read().splitlines(): po...
2,017
807
#!/usr/bin/env python # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import from __future__ import print_function import argparse import gzip import json import os import s...
16,451
5,194
"""Write raw files to BIDS format. example usage: $ mne_bids raw_to_bids --subject_id sub01 --task rest --raw data.edf --bids_root new_path """ # Authors: Teon Brooks <teon.brooks@gmail.com> # Stefan Appelhoff <stefan.appelhoff@mailbox.org> # # License: BSD (3-clause) import mne_bids from mne_bids import wr...
3,743
1,182
class Calculations: def __init__(self, first, second): self.first = first self.second = second def add(self): print(self.first + self.second) def subtract(self): print(self.first - self.second) def multiply(self): print(self.first * self.second) ...
1,460
444
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") ''' Rotate an array A to the right by a given number of steps K. Covert the array to a deque Apply the rotate() method the rotate the deque in positive K steps Convert the deque to array ''' from collec...
460
149
# -*- coding: utf-8 -*- """ Python Markdown A Python implementation of John Gruber's Markdown. Documentation: https://python-markdown.github.io/ GitHub: https://github.com/Python-Markdown/markdown/ PyPI: https://pypi.org/project/Markdown/ Started by Manfred Stienstra (http://www.dwerg.net/). Maintained for a few yea...
37,741
11,791
import os class StressedNetConfig: def __init__(self, synaptic_environmental_constraint=0.8, group_environmental_constraint=0.6, stress_factor=0.8, save_folder=os.path.expanduser("~/.nervous/models/")): self._synaptic_environmental_const...
2,230
643
# Copyright 2020 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 agreed to...
6,365
2,072
import datetime import boto3 US_EAST_REGION = {'us-east-1'} US_EAST_AVAILABILITY_ZONES = {'us-east-1a', 'us-east-1b', 'us-east-1c', 'us-east-1e'} # note d is missing INSTANCE_VERSION = 'Linux/UNIX (Amazon VPC)' def fetch_spot_prices(region, start_time, end_time, instance_type, instance_version=INSTANCE_VERSION): ...
5,106
1,438
from .nearest_neighbor_index import NearestNeighborIndex from .kd_tree import *
81
30
''' Author: huangbaochen<huangbaochenwo@live.com> Date: 2021-12-11 20:04:19 LastEditTime: 2021-12-11 21:46:16 LastEditors: huangbaochen<huangbaochenwo@live.com> Description: 测试Try单子 No MERCY ''' import pytest from fppy.try_monad import Try, Success, Fail from fppy.option import Just, Nothing @pytest.mark.try_monad def...
2,562
958
from datetime import date from typing import Dict, Optional from sqlalchemy.orm import Session from sqlalchemy.sql.expression import func from app.database.models import Quote TOTAL_DAYS = 366 def create_quote_object(quotes_fields: Dict[str, Optional[str]]) -> Quote: """This function create a quote object from...
952
285
n, k = map(int, input().split()) w = list(map(int, input().split())) r = sum(map(lambda x: (x+k-1)//k, w)) print((r+1)//2)
123
59
import os import sys def is_active(): return True def get_name(): return "Server" def can_build(): if (os.name!="posix"): return False return True # enabled def get_opts(): return [ ('use_llvm','Use llvm compiler','no'), ('force_32_bits','Force 32 bits binary','no') ] def get_flags(): return [ (...
1,432
675
from telemetry.TruckConstants import ConstantValues from telemetry.TruckCurrent import CurrentValues from telemetry.TruckPositioning import Positioning class TruckValues: constant_values = None current_values = None positioning = None def __init__(self): self.current_values = CurrentValues()...
413
111
import csv from pyspark.sql import SparkSession from pyspark.sql.types import IntegerType spark = SparkSession.builder.appName("Assignment4").getOrCreate() sc = spark.sparkContext # load data to dataframe path = 'fake_data.csv' df = spark.read.format('csv').option('header','true').load(path) # cast income as an int...
1,483
620
import factory from django.contrib.auth import get_user_model class UserFactory(factory.DjangoModelFactory): class Meta: model = get_user_model() first_name = factory.Faker('name') last_name = factory.Faker('name') email = factory.Faker('email')
274
85
from dataclasses import dataclass, field from reamber.base.Hold import Hold, HoldTail from reamber.o2jam.O2JNoteMeta import O2JNoteMeta @dataclass class O2JHoldTail(HoldTail, O2JNoteMeta): pass @dataclass class O2JHold(Hold, O2JNoteMeta): """ Defines the O2Jam Bpm Object The O2Jam Bpm Object is stored...
482
186
import lightbulb from apscheduler.schedulers.asyncio import AsyncIOScheduler from peacebot.core.utils.time import TimeConverter def fetch_scheduler(ctx: lightbulb.Context) -> AsyncIOScheduler: return ctx.bot.d.scheduler async def convert_time(ctx: lightbulb.Context, time: str) -> float: seconds = await Tim...
566
185
import unittest from appium import webdriver class MSiteDefaultBrowserAndroidUITests(unittest.TestCase): def setUp(self): # Default browser does not exist for android >= 6.0 desired_caps = { 'platformName': 'Android', 'deviceName': 'Android Emulator', 'appPac...
855
276
""" Created on 17-June-2020 @author Jibesh Patra The types extracted during runtime usually look something like --> <class 'numpy.ndarray'> or <class 'seaborn.palettes._ColorPalette'> change them to --> ndarray, ColorPalette """ import re remove_chars = re.compile(r'>|\'|<|(class )|_|(type)') def process_types(tp...
458
170
from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * from matplotlib import pyplot as plt from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas import matplotlib.ticker as ticker import numpy as np import random, matplotlib...
4,254
1,397
'''Functional tests for CPG''' from .. import CircuitPlayground from .. import __version__ as CircuitPlaygroundVersion import time def funcTest(timestamps: bool = False) -> None: cpg = CircuitPlayground() if timestamps: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\nRUNNING...
7,561
2,702
from django.db import models class Account(models.Model): clsNb = models.IntegerField() Name = models.CharField(max_length=10) pw = models.IntegerField() def __str__(self): return self.Name
216
69
from math import sqrt import torch from torch_geometric.utils import geodesic_distance def test_geodesic_distance(): pos = torch.Tensor([[0, 0, 0], [2, 0, 0], [0, 2, 0], [2, 2, 0]]) face = torch.tensor([[0, 1, 3], [0, 2, 3]]).t() out = geodesic_distance(pos, face) expected = [ [0, 1, 1, sqrt...
1,307
583
# Copyright 2009-present MongoDB, Inc. # # 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 agreed to in wri...
31,292
8,649
"""This module tests Stanford NLP processors.""" import os import unittest from texar.torch import HParams from forte.pipeline import Pipeline from forte.data.readers import StringReader from forte.processors.stanfordnlp_processor import StandfordNLPProcessor from ft.onto.base_ontology import Token, Sentence class ...
1,415
387
#! /usr/bin/env python3 # -*- coding: utf-8 -*- """ Serve current folder files in a HTTP webserver. """ import socketserver from threading import Thread from http.server import SimpleHTTPRequestHandler PORT = 8000 def start_http_server(port=PORT): httpd = socketserver.TCPServer(("", port), SimpleHTTPRequestHand...
496
164
# coding: utf-8 class AppTestCompile: def test_simple(self): import sys co = compile('1+2', '?', 'eval') assert eval(co) == 3 co = compile(memoryview(b'1+2'), '?', 'eval') assert eval(co) == 3 exc = raises(ValueError, compile, chr(0), '?', 'eval') assert str(...
7,393
2,408
import yfinance as yf import matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd from IPython.display import Markdown import numpy as np from datetime import date, timedelta def plot_and_get_info(ticker, start = None, en...
12,207
3,945
#!/usr/bin/env python # -*- coding: utf-8 -*- ########################################################### # WARNING: Generated code! # # ************************** # # Manual changes may get lost if file is generated again. # # Only code inside the [MANUAL] ta...
5,008
2,101
# -*- coding: utf-8 -*- # # Copyright (c) 2021, Dana Lehman # Copyright (c) 2020, Geoffrey M. Poore # All rights reserved. # # Licensed under the BSD 3-Clause License: # http://opensource.org/licenses/BSD-3-Clause # from .quiz import Quiz, Question, GroupStart, GroupEnd, TextRegion BEFORE_ITEMS = '''\ <?xml version...
26,632
8,517
#!/usr/bin/env python """Tests for `bids_statsmodels_design_synthesizer` package.""" import pytest import subprocess as sp from pathlib import Path SYNTHESIZER = "aggregate_stats_design.py" from bids_statsmodels_design_synthesizer import aggregate_stats_design as synth_mod # from bids_statsmodels_design_synthesizer...
2,360
864
#!/usr/bin/env python # coding: utf-8 __author__ = 'whoami' """ @version: 1.0 @author: whoami @license: Apache Licence 2.0 @contact: skutil@gmail.com @site: http://www.itweet.cn @software: PyCharm Community Edition @file: plugin_api.py @time: 2015-11-28 下午1:52 """ from linux import cpu,disk,iostats,loadavg,memory,net...
689
273
import numpy as np import eyekit import algorithms import core data = eyekit.io.load(core.FIXATIONS / 'sample.json') passages = eyekit.io.load(core.DATA / 'passages.json') original_sequence = data['trial_5']['fixations'] fixation_XY = np.array([fixation.xy for fixation in original_sequence], dtype=int) word_XY = np....
1,425
559
# # Autogenerated by Thrift Compiler (0.9.0) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py # from thrift.Thrift import TType, TMessageType, TException, TApplicationException from ttypes import * from thrift.Thrift import TProcessor from thrift.transport import TTransport ...
98,817
34,279
#! /usr/bin/env python from .core import gemucator
52
20
import graphene from graphene_django import DjangoObjectType from graphene_django.converter import convert_django_field from pyuploadcare.dj.models import ImageField
166
42
#!/usr/bin/python3 ''' This script follows formulas put forth in Kislyuk et al. (2011) to calculate genome fluidity of a pangenome dataset. Variance and standard error are estimated as total variance containing both the variance due to subsampling all possible combinations (without replacement) of N genomes from th...
15,518
5,231
# # This module provides the Instance class that encapsulate some complex server instances related operations # from __future__ import print_function from json import loads from neutronclient.v2_0 import client as neutron_client from novaclient import client as nova_client from cinderclient import client as cinder_cli...
7,610
2,206
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Tools to create profiles (i.e. 1D "slices" from 2D images).""" import numpy as np import scipy.ndimage from astropy import units as u from astropy.convolution import Box1DKernel, Gaussian1DKernel from astropy.coordinates import Angle from astropy.table ...
13,314
3,969
# -*- coding: utf-8 -*- def main(): a = input() # See: # https://www.slideshare.net/chokudai/abc007 if a == 'a': print('-1') else: print('a') if __name__ == '__main__': main()
221
97
"""versatileimagefield Field mixins.""" import os import re from .datastructures import FilterLibrary from .registry import autodiscover, versatileimagefield_registry from .settings import ( cache, VERSATILEIMAGEFIELD_CREATE_ON_DEMAND, VERSATILEIMAGEFIELD_SIZED_DIRNAME, VERSATILEIMAGEFIELD_FILTERED_DIR...
7,270
2,162
# 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
9,450
2,988
import open3d as o3d import numpy as np pc_load_pathname = '/home/caizhongang/github/waymo_kitti_converter/007283-000.bin' pc = np.fromfile(pc_load_pathname, dtype=np.float32).reshape(-1, 3) pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(pc) axis = o3d.geometry.TriangleMesh.create_coordinat...
417
184
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@managedit.ie> # # 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/lice...
2,306
700
"""node-path implementation for OpenGLContext """ from vrml.vrml97 import nodepath, nodetypes from vrml.cache import CACHE from OpenGLContext import quaternion from OpenGL.GL import glMultMatrixf class _NodePath( object ): """OpenGLContext-specific node-path class At the moment this only adds a single method,...
1,696
455
import random from math import sqrt sum = 0 for x in range(101): sum += x print(sum) ''' range(101) 0-100 一共101个数 range(1,101) 1-100 range(1,101,2) 1-100间的奇数 步长为2 range(100,0,-2) 100-0间的偶数 步长为-2 ''' sum = 0 for x in range(100, 0, -2): sum += x print(sum) # while # 0-100间的随机数 answer = random.randint(0, 1...
1,042
526
# Copyright (C) 2018, HTCondor Team, Computer Sciences Department, # University of Wisconsin-Madison, WI. # # 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/license...
12,340
3,337
# Copyright (c) 2021 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...
26,347
8,067
from .api import run_query_get_token from .api import convert_to_dask from .api import run_query_get_results from .api import run_query_get_concat_results from .api import register_file_system from .api import deregister_file_system from .api import FileSystemType, DriverType, EncryptionType from .api import SchemaFro...
661
208
class Constants(object): LOGGER_CONF = "common/mapr_conf/logger.yml" USERNAME = "mapr" GROUPNAME = "mapr" USERID = 5000 GROUPID = 5000 ADMIN_USERNAME = "custadmin" ADMIN_GROUPNAME = "custadmin" ADMIN_USERID = 7000 ADMIN_GROUPID = 7000 ADMIN_PASS = "mapr" MYSQL_USER = "admin"...
1,938
829
# Jeonghyun Kim, UVR KAIST @jeonghyunct.kaist.ac.kr import os, sys import json import h5py import numpy as np import quaternion import torch from torch.utils.data import Dataset BASE_DIR_1 = os.path.dirname(os.path.abspath(__file__)) # scan2cad BASE_DIR = os.path.dirname(BASE_DIR_1) # dataset ROOT_DIR = os.path.dirn...
12,367
4,411
#!/usr/bin/env python """ Compute diffusion coefficient from MSD data. Time interval, DT, is obtained from in.pmd in the same directory. Usage: msd2diff.py [options] MSD_FILE Options: -h, --help Show this message and exit. -o, --offset OFFSET Offset of given data. [default: 0] --plot Plot ...
3,590
1,404
import os f = open(os.path.join(os.path.dirname(__file__), '../input/5/part2.txt'), 'r') class InstructionSet: def __init__(self, instructions): self.instructions = instructions self.currentIndex = 0 self.numberSteps = 0 def _changeOffsetValue(self, index): if self.instructi...
1,172
365
import behave @behave.when('I add $1200 to my account') def add_usd_1200(context): context.account.add_cash(amount=1200) @behave.then('It becomes $3200 in my account') def check_for_increase_to_usd_1880(context): assert context.account.current_cash == 3200
269
115
"""Tests camera and system functions.""" import unittest from unittest import mock from blinkpy.blinkpy import Blink from blinkpy.helpers.util import BlinkURLHandler from blinkpy.sync_module import BlinkSyncModule, BlinkOwl from blinkpy.camera import BlinkCamera, BlinkCameraMini @mock.patch("blinkpy.auth.Auth.query"...
11,944
3,883
from __future__ import absolute_import import numpy as np from openmdao.api import Group from .dynamic_pressure_comp import DynamicPressureComp from .lift_drag_force_comp import LiftDragForceComp from .cd0_comp import CD0Comp from .kappa_comp import KappaComp from .cla_comp import CLaComp from .cl_comp import CLComp...
2,807
819
import matplotlib.pyplot as plt import argparse, csv, numpy, time, os, re def main(resultsFile, toolName): filesToCalc = [] toolNames = [] if os.path.isfile(resultsFile): # the user must have defined an exact file to plot filesToCalc.append(resultsFile) toolNames.appen...
7,035
2,150
# -*- coding: utf-8 -*- # ===== Default imports ===== import asyncio import logging # ===== External libs imports ===== from aiogram import Bot, Dispatcher, types from aiogram.dispatcher import FSMContext # ===== Local imports ===== from analytics import BotAnalytics from db_manager import DbManager from lang_man...
23,402
6,313
# 6. Специални числа # Да се напише програма, която чете едно цяло число N, въведено от потребителя, и генерира всички възможни "специални" # числа от 1111 до 9999. За да бъде “специално” едно число, то трябва да отговаря на следното условие: # • N да се дели на всяка една от неговите цифри без остатък. # Пример: при N...
930
396
import pytest import numbers import numpy as np from numpy.testing import assert_raises from numpy.testing import assert_array_equal from numpy.testing import assert_equal from numpy.testing import assert_raises_regex from skopt.space import LogN, Normalize @pytest.mark.fast_test def test_logn2_integer(): transf...
1,815
661
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # # 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/LICEN...
29,526
9,483
import numpy as np import multiprocessing as mp import pyfftw from numpy import pi, exp, sqrt, sin, cos, conj, arctan, tanh, tan from numpy import heaviside as heav from include import helper import h5py # ---------Spatial and potential parameters-------------- Mx = My = 64 Nx = Ny = 128 # Number of grid pts dx = dy...
6,694
3,006
from __future__ import print_function import requests import sys import os verbose=True try: username=os.environ['USERNAME'] password=os.environ['PASSWORD'] except: print("Crumb Diaganostic requires USERNAME/PASSWORD to be set as environment variables") sys.exit(-1) jenkins_url=os.environ['JENKINS_URL'...
1,033
330
# -*- coding: utf-8 -*- for i in range(int(raw_input())): x, y = [int(x) for x in raw_input().split()] if x > y: x, y = y, x x += 1 if x % 2 == 0 else 2 print sum([j for j in range(x, y, 2)])
219
103
import tensorflow as tf FLIPPING_TENSOR = tf.constant([1.0, -1.0, 1.0]) @tf.function def sample_data(points, labels, num_point): if tf.random.uniform(shape=()) >= 0.5: return points * FLIPPING_TENSOR, labels return points, labels mock_data = tf.constant([ [1., 2., 3.], [4., 5., 6.], [7....
625
272
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'This is the app index page.'
118
40
# Generated by Django 3.1.6 on 2021-02-16 11:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('schedule', '0026_event'), ] operations = [ migrations.AlterField( model_name='group', name='students', f...
629
202
import aiohttp import asyncio import time import time import argparse import glob import os import shutil import random import re import requests import sys from concurrent import futures import pdfkit import time from retrying import retry from pygments import highlight from pygments.lexers import...
10,683
3,803
from django.test import SimpleTestCase as TestCase from corehq.apps.app_manager.models import _parse_xml import os class XMLParsingTest(TestCase): def testUnicodeError(self): """Tests a bug found in Unicode processing of a form""" file_path = os.path.join(os.path.dirname(__file__), "data", "un...
722
217
import protocolbuffers.Consts_pb2 as Consts_pb2 from google.protobuf import descriptor, message, reflection DESCRIPTOR = descriptor.FileDescriptor(name = 'Localization.proto', package = 'EA.Sims4.Network', serialized_pb = '\n\x12Localization.proto\x12\x10EA.Sims4.Network\x1a\x0cConsts.proto"\x85\n\n\x14Loc...
25,605
9,889
# input N, M = map(int, input().split()) Ds = [*map(int, input().split())] # compute dp = [False] * (N+1) for ni in range(N+1): if ni == 0: dp[ni] = True for D in Ds: if ni >= D: dp[ni] = dp[ni] or dp[ni-D] # output print("Yes" if dp[-1] else "No")
287
130
# sorting n=int(input()) array=list(map(int,input().split())) i=0 count=[] counter=0 while i<len(array): min=i start=i+1 while(start<len(array)): if array[start]<array[min]: min=start start+=1 if i!=min: array[i],array[min]=array[min],array[i] count.append(i) ...
447
167
import unittest from app.models import News # News = news.News class NewsTest(unittest.TestCase): ''' Test Class to test the behaviour of the Movie class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.new_news = News('abc-news','ABC NEWS...
1,043
319
import argparse parser = argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases parser.add_argument('--focus', type=str, default="") parser.add_argument('--version', type=str, default="") parser.add_argument('--retrieve', type=str, default="focus") args = parser.pars...
365
119
""" This script cleans and prepares the data set of bookings for the future usage """ import argparse import logging import sys import pandas as pd from preprocessing.common import canonize_datetime, raw_data_to_df, check_processed_columns, check_data OLD_BREAKPOINT_MATCHER = { 2001: [ (1, 1, "New Year"...
7,699
3,223
from sanic import Blueprint, Request, HTTPResponse, response from sanic.models.handler_types import RouteHandler from functools import wraps from inspect import isawaitable from typing import Callable, Dict, Any, Union, Awaitable, List, Optional ACCEPTED_WISH_VERS = ['wish.alpha.v1'] WishHandler = Callable[..., Union...
1,309
410