text
string
size
int64
token_count
int64
import unittest from test import test_support import base64 class LegacyBase64TestCase(unittest.TestCase): def test_encodestring(self): eq = self.assertEqual eq(base64.encodestring("www.python.org"), "d3d3LnB5dGhvbi5vcmc=\n") eq(base64.encodestring("a"), "YQ==\n") eq(base64.encod...
9,390
4,253
import numpy as np from ctypes import c_void_p from .Shader import Shader from .transforms import * from OpenGL.GL import * class Path: # position=[x1, y1, z1, ..., xn, yn, zn] ; rotation = [[Rx1, Ry1, Rz1], ..., [Rxn, Ryn, Rzn]] def __init__(self, position, rotation=None): self.loadPath(position) ...
7,154
2,429
from argparse import ( ArgumentParser ) from os import getcwd as os_getcwd DEFAULT_OUTPUT_FOLDER = os_getcwd() DEFAULT_SAMPLE_VOLUME = 10000 def build_args_parser( program, description): parser = ArgumentParser( program, description, ) parser = add_arguments(pars...
1,406
454
import math x = float(input()) prop_2 = -(x**2) / math.factorial(2) prop_3 = (x**4) / math.factorial(4) prop_4 = -(x**6) / math.factorial(6) cos_x = float(1 + prop_2 + prop_3 + prop_4) print(prop_2) print(prop_3) print(prop_4) print(cos_x)
246
120
import pytest from datagateway_api.src.common.exceptions import BadRequestError, FilterError from datagateway_api.src.datagateway_api.filter_order_handler import FilterOrderHandler from datagateway_api.src.datagateway_api.icat.filters import PythonICATWhereFilter class TestICATWhereFilter: @pytest.mark.parametri...
3,211
1,091
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.loader import ItemLoader from scrapy.loader.processors import TakeFirst # class SpiderItem(scrapy.Item): # # define the fields for your...
1,099
469
# # (C) Copyright 2013 Enthought, Inc., Austin, TX # All right reserved. # # This file is open source software distributed according to the terms in # LICENSE.txt # """ Context holding multiple subcontexts. """ from __future__ import absolute_import from itertools import chain from collections import MutableMapping ...
7,160
1,911
"""A simple file to test the line_counter performance in python This is a multiline doctest """ __author__ = "Frederico Moeller" __copyright__ = "" __credits__ = ["Frederico Moeller"] __license__ = "MIT" __version__ = "1.0.1" __maintainer__ = "Frederico Moeller" __email__ = "" __status__ = "" #import things import ma...
634
214
"""Data pipelines.""" from collections import defaultdict, OrderedDict from tqdm import tqdm from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler import torch def get_info(examples, vocab=None, max_seq_len=256): """Gathers info on and creats a featurized example generator for...
4,602
1,451
# Take number, and convert integer to string # Calculate and return number of digits def get_num_digits(num): # Convert int to str num_str = str(num) # Calculate number of digits digits = len(num_str) return digits # Define main function def main(): # Prompt user for an int...
576
178
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division from future import standard_library standard_library.install_aliases() from builtins import * import re import sys import os import subprocess imp...
4,992
2,359
import asyncio from contextlib import AsyncExitStack from aiogram.dispatcher.filters.state import StatesGroup, State from aiogram.dispatcher.storage import FSMContextProxy from aiogram.types import Message, PhotoSize, ReplyKeyboardRemove, ContentTypes from aiogram.utils.helper import HelperMode from dialog.avatar_ima...
3,255
992
from skimage.metrics import structural_similarity as ssim from glob import glob from PIL import Image import numpy as np import ntpath import dhash import cv2 from database_structure import database_migrations IMAGE_FOLDER = "./image_store" ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg'] image_store_hash = dict() db_ops ...
5,144
1,564
import discord from discord.ext import commands import os import json from datetime import date, datetime, timedelta from .utils import helper_functions as hf from copy import deepcopy dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\', '/') class Jpserv(commands.Cog): """Module...
8,823
2,883
#!/usr/bin/env python3 from components import ProgramState import binaryninja as binja import argparse import os.path import curses # TODO...impliment live-refreashing the settings.json during run (add the keybinding and check for it here in the global input loop) # TODO...support multi-key presses? Not sure if this ...
2,027
667
# 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...
5,144
1,536
import moviepy.editor as mpy import moviepy.video.fx.all as vfx import subprocess as sp # Crop and resize video clip = mpy.VideoFileClip("smoke.mp4") (w, h) = clip.size cropped_clip = vfx.crop(clip, width=(h/128)*64, height=h, x1=w/4*3-100, y1=0).resize((64, 128)) cropped_clip.write_videofile('smoke-cropped.mp4') # C...
726
307
"""This contains the configuration of the Rolodex application.""" # Django Imports from django.apps import AppConfig class RolodexConfig(AppConfig): name = "ghostwriter.rolodex" def ready(self): try: import ghostwriter.rolodex.signals # noqa F401 isort:skip except ImportError: ...
336
100
# Generated by Django 4.0.3 on 2022-03-01 14:42 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('boards', '0023_alter_image_type'), ] operations ...
560
184
''' Created on Mar 22, 2020 @author: Michal.Busta at gmail.com ''' #get rid of the optimizer state ... import torch MODEL_PATH = '/models/model-b2-2.pth' state = torch.load(MODEL_PATH, map_location=lambda storage, loc: storage) state_out = { "state_dict": state["state_dict"], } torch.save(state_out, 'model-b2-2....
325
135
import os import re from setuptools import setup version = re.search( '^__version__\s*=\s*"(.*)"', open('braumeister/braumeister.py').read(), re.M ).group(1) def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="braumeister", packages=["braumeiste...
1,125
370
# standard library imports import os # third party imports import numpy as np from PIL import Image import torch.nn as nn from torchvision import transforms # local imports import config from . import utils from . import geometric_transformer class GeoTransformationInfer(nn.Module): def __init__(self, output_di...
3,493
1,572
from pathlib import Path import h5py import numpy as np from torchvision.datasets.vision import VisionDataset from PIL import Image import requests import zipfile from tqdm import tqdm def download_file_from_google_drive(id, destination): URL = "https://docs.google.com/uc?export=download" session = requests...
6,577
2,036
""" link: https://leetcode.com/problems/permutations-ii problem: 求全排列,nums中存在重复数 solution: 同46,加上排序即可 """ class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: if len(nums) == 1: return [nums] new_nums = nums.copy() new_nums.sort() ...
774
332
import findspark findspark.init() from pyspark import SparkConf,SparkContext from pyspark.streaming import StreamingContext from pyspark.sql import Row,SQLContext import sys import requests def tmp(x): y = (x.split(';')[7]).split(',') return (y) def forf(x): for i in x: yield (i,1) def topprint(time,rdd): re...
2,406
1,000
# Generated by Django 4.0.1 on 2022-01-20 13:10 import courses.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('courses', '0002_video_text_image_file_content'), ] operations = [ migrations.AlterModelOptions( name='content', ...
908
266
#Atoi stands for ASCII to Integer Conversion def atoi(string): res = 0 # Iterate through all characters of # input and update result for i in range(len(string)): res = res * 10 + (ord(string[i]) - ord('0')) return res #Adjustment contains rule of three for calculating an integer given an...
407
125
#!/usr/bin/python # Copyright 2016 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 appli...
3,672
1,080
################################################## # ./AppService_services.py # generated by ZSI.wsdl2python # # ################################################## from .AppService_services_types import * from .AppService_services_types import \ nbcr_sdsc_edu_opal_types as ns1 import urllib.parse, types from...
22,135
6,274
# Copyright (c) 2020-2022, NVIDIA CORPORATION. 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 ...
10,340
3,608
# -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding 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 require...
6,608
1,962
from unittest import TestCase import torch import transformers from model.bert_model import BertModel class TestBertModel(TestCase): def test_forward(self): # Bert Config vocab_size = 10 sequence_len = 20 batch = 32 num_classes = 3 expected_shape = (batch, seque...
767
257
import json import os import tempfile from unittest import TestCase import pytest from donjuan import Dungeon, DungeonRandomizer, Renderer class RendererTest(TestCase): def setUp(self): super().setUp() self.TEMP_DIR = tempfile.mkdtemp() def test_smoke(self): r = Renderer() a...
1,593
563
"""Spinnaker validate functions.""" import logging from .consts import API_URL from .utils.credentials import get_env_credential LOG = logging.getLogger(__name__) def validate_gate(): """Check Gate connection.""" try: credentials = get_env_credential() LOG.debug('Found credentials: %s', cred...
612
185
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-15 00:56 from __future__ import unicode_literals from django.conf import settings import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial =...
2,437
681
#!/usr/bin/env python # -*- coding: utf-8 -*- import sqlite3 as sqlite import os.path as osp import sys class Sqli(object): conn = '' cursor = '' def __init__(self, dbname): try: self.conn = sqlite.connect(osp.abspath(dbname)) except Exception, what: print wh...
2,258
684
""" easy way to use losses """ from center_loss import Centerloss import torch.nn as nn from FocalLoss import FocalLoss def center_loss(pred,label,num_calss,feature): loss = Centerloss(num_calss,feature) return loss(pred,label) def Focal_loss(pred,label,num_calss,alaph=None, gamma): loss = Centerloss(num...
599
231
# Copyright 2016 Rackspace Australia # 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 requi...
7,320
2,347
import os import sys import json sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../bert"))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))) import tokenization from config import config class Model_data_preparation(object): def __init__(self, DATA_...
8,889
3,031
import typing # noqa from google.protobuf import descriptor from google.protobuf.json_format import _IsMapEntry, _Printer from google.protobuf.message import Message # noqa from clarifai.rest.grpc.proto.clarifai.api.utils import extensions_pb2 def protobuf_to_dict(object_protobuf, use_integers_for_enums=True, ign...
3,222
948
from .capsulenet import *
26
10
#!/usr/bin/env python # # -*- coding: utf-8 -*- # # Copyright (c) 2018 JiNong, Inc. # All right reserved. # import struct import time import socket import select import traceback import hashlib import json from enum import IntEnum from threading import Thread, Lock from mate import Mate, ThreadMate, DevType from mbloc...
28,625
9,776
import demjson import sys from subprocess import Popen, PIPE import subprocess import xml.etree.ElementTree as ET import os from datetime import datetime from functions import runcommand #from sets import Set def getfailedcases(withBundle = True): xmlfile='build/reports/junit.xml' tree = ET.parse(xmlfile) ...
6,525
1,925
# flake8: noqa: F401 from .context_manager_hook import ContextManagerHook from .counter_hook import CounterHook from .file_open_hook import FileOpenHook from .logging_hook import LoggingHook from .profiler_hook import ProfilerHook from .runtime_audit_hook import RuntimeAuditHook from .stack_trace_hook import StackTrace...
572
202
import pytest import numpy as np import pandas as pd from hypothetical._lib import _build_des_mat def test_array(): d = np.array([[1., 1.11, 2.569, 3.58, 0.76], [1., 1.19, 2.928, 3.75, 0.821], [1., 1.09, 2.865, 3.93, 0.928], [1., 1.25, 3.844, 3.94, 1.009], ...
3,549
2,034
#!/usr/bin/env python3 # Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de # Barcelona (UAB). # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """Download big files from Google Drive.""" import shutil import sys import...
3,563
1,199
# -*- coding: utf-8 -*- """ 将耗时间的任务放到线程中以获得更好的用户体验。 """ import time import tkinter import tkinter.messagebox def download(): # 模拟下载任务需要花费10秒时间 time.sleep(10) tkinter.messagebox.showinfo('提示', '下载完成') def show_about(): tkinter.messagebox.showinfo('关于', '作者:罗浩') def main(): t...
763
351
""" GitLab webhook receiver - see http://doc.gitlab.com/ee/web_hooks/web_hooks.html """ import asyncio import json import logging from sinks.base_bot_request_handler import AsyncRequestHandler logger = logging.getLogger(__name__) try: import dateutil.parser except ImportError: logger.error("missing module p...
3,250
916
from evsim.system_simulator import SystemSimulator from evsim.behavior_model_executor import BehaviorModelExecutor from evsim.system_message import SysMessage from evsim.definition import * import os import subprocess as sp class Assessor(BehaviorModelExecutor): def __init__(self, instance_time, destruct...
1,220
404
import os from typing import Union, List from tei_entity_enricher.interface.postprocessing.io import FileReader, FileWriter from tei_entity_enricher.util.helper import local_save_path, makedir_if_necessary from tei_entity_enricher.util.exceptions import FileNotFound class GndConnector: def __init__( ...
19,786
5,316
import logging logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) logger.level = logging.DEBUG
122
34
from args import get_argparser, parse_args, get_aligner, get_bbox def render(aligner, bbox, z): aligner.total_bbox = bbox aligner.zs = z aligner.render_section_all_mips(z, bbox) if __name__ == '__main__': parser = get_argparser() args = parse_args(parser) a = get_aligner(args) bbox = get_bbox(args) ...
440
186
# -*- coding: utf-8 -*- # # 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...
52,806
13,227
#/usr/bin/python __version__ = '1.0' __author__ = 'alastair.maxwell@glasgow.ac.uk' ## ## Imports import string import os import errno import shutil import sys import glob import datetime import subprocess import logging as log import numpy as np import csv from io import StringIO import PyPDF2 from sklearn import prep...
31,196
11,811
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmedit.models.backbones import ContextualAttentionNeck, DeepFillEncoder from mmedit.models.common import SimpleGatedConvModule def test_deepfill_enc(): encoder = DeepFillEncoder() x = torch.randn((2, 5, 256, 256)) outputs = encoder(x) ...
3,966
1,565
# Generated by Django 2.2.13 on 2020-11-27 05:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mvp', '0003_hublocation'), ] operations = [ migrations.RemoveField( model_name='hublocation', name='longitude', ...
580
189
# Generated by Django 3.2.4 on 2021-07-14 11:55 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('adminapp', '0011_faq'), ] operations = [ migrations.AddField( model_name='faq', name='uuid', ...
751
237
import json import os import nibabel as nib import csv from operator import itemgetter # PATH TO PREPROCESSED DATA raw_data_path = '/home/lab/nnUNet_data/nnUNet_raw_data_base/nnUNet_raw_data/Task500_BrainMets' pixdim_ind = [1,2,3] # Indexes at which the voxel size [x,y,z] is stored # PATH TO JSON FILE with open('/h...
1,585
604
# -*- coding: utf-8 -*- """ tornadio2.tests.gen ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011 by the Serge S. Koval, see AUTHORS for more details. :license: Apache, see LICENSE for more details. """ from collections import deque from nose.tools import eq_ from tornadio2 import gen _queue = None def in...
2,794
985
#! /usr/bin/env python # -*- coding: utf-8 -*- # # author: Avinash Kori # contact: koriavinash1@gmail.com import torch import SimpleITK as sitk import numpy as np import nibabel as nib from torch.autograd import Variable from skimage.transform import resize from torchvision import transforms from time import gmtime, ...
21,122
7,454
import numpy as np from statsmodels.discrete.conditional_models import ( ConditionalLogit, ConditionalPoisson) from statsmodels.tools.numdiff import approx_fprime from numpy.testing import assert_allclose import pandas as pd def test_logit_1d(): y = np.r_[0, 1, 0, 1, 0, 1, 0, 1, 1, 1] g = np.r_[0, 0, 0...
7,334
3,368
def bypass_incompatible_branch(job): return (job.settings.bypass_incompatible_branch or job.author_bypass.get('bypass_incompatible_branch', False)) def bypass_peer_approval(job): return (job.settings.bypass_peer_approval or job.author_bypass.get('bypass_peer_approval', False)) def b...
905
328
# -*- coding: utf-8 -*- ''' Created on 02.11.2017 @author: fstallmann ''' from __future__ import absolute_import from collections import deque import bkt from bkt import dotnet Drawing = dotnet.import_drawing() from . import helpers as pplib class TextframeSpinnerBox(bkt.ribbon.RoundingSpinnerBox): ### Inst...
26,868
8,170
from __future__ import annotations import warnings from typing import Any, Dict, List, Optional, Set, Tuple, Union, TYPE_CHECKING from .cache import property_immutable_cache, property_mutable_cache from .constants import ( transforming, IS_STRUCTURE, IS_LIGHT, IS_ARMORED, IS_BIOLOGICAL, IS_MECH...
34,680
10,468
from .load import load_data, NUTRI_COLS, load_clean_rel_to_nutri
65
27
# from .noise_gen import CGMNoiseGenerator from .noise_gen import CGMNoise import pandas as pd import logging logger = logging.getLogger(__name__) class CGMSensor(object): def __init__(self, params, seed=None): self._params = params self.name = params.Name self.sample_time = params.sample...
1,402
453
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Thepeg(AutotoolsPackage): """Toolkit for High Energy Physics Event Generation""" home...
5,731
3,480
#!/usr/bin/env python # # Copyright © 2012-2016 VMware, 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 requi...
9,258
2,750
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
22,670
6,030
from abc import ABCMeta, abstractmethod import numpy as np class Agent(object): __metaclass__ = ABCMeta def __init__(self, name, id_, action_num, env): self.name = name self.id_ = id_ self.action_num = action_num # len(env.action_space[id_]) # self.opp_action_space = e...
1,893
648
# # @lc app=leetcode id=290 lang=python3 # # [290] Word Pattern # # https://leetcode.com/problems/word-pattern/description/ # # algorithms # Easy (35.86%) # Likes: 825 # Dislikes: 113 # Total Accepted: 164K # Total Submissions: 455.9K # Testcase Example: '"abba"\n"dog cat cat dog"' # # Given a pattern and a stri...
1,523
551
from torch import nn class MyAwesomeModel(nn.Module): def __init__(self): super().__init__() self.cnn = nn.Sequential(nn.Conv2d(in_channels=1, out_channels=5, kernel_size=3), nn.ReLU(), nn.Conv2d(in_channels=5, out_channels=3, kernel...
705
240
import unittest from musket_core import coders import numpy as np import pandas as pd import os import math fl=__file__ fl=os.path.dirname(fl) class TestCoders(unittest.TestCase): def test_binary_num(self): a=np.array([0,1,0,1]) bc=coders.get_coder("binary",a, None) self.as...
5,036
1,963
#!/usr/bin/env python3 import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) import scripts.lib.setup_path_on_import if __name__ == "__main__": if 'posix' in os.name and os.geteuid() == 0: print("manage.py should not be run as root. Use `su zulip` to drop ro...
1,706
564
import json, requests from bs4 import BeautifulSoup def fetch(): r = requests.get('http://clrhome.org/table/') if not r.ok: print('Cannot fetch {})'.format(r.url)) return None # remove newlines text = r.text.replace('\n', '') # Return the data as a BeautifulSoup object for easy querying return ...
2,385
840
from ..dojo_test_case import DojoTestCase from dojo.models import Test from dojo.tools.intsights.parser import IntSightsParser class TestIntSightsParser(DojoTestCase): def test_intsights_parser_with_one_critical_vuln_has_one_findings_json( self): testfile = open("unittests/scans/intsights/ints...
2,516
820
#!/usr/bin/env python # Copyright 2013-present Barefoot Networks, Inc. # Copyright 2018 VMware, 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/LIC...
5,046
1,507
class Heap: def __init__(self): self.items = dict() # key - (value, index) self.indexes = [] # index - key // to know indexes # Usefull functions def swap(self, i, j): x = self.indexes[i] # key of 1 item y = self.indexes[j] # key of 2 item # swa...
6,237
1,978
from __future__ import unicode_literals try: from unittest.mock import patch except ImportError: from mock import patch from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.test import TestCase from django.urls import reverse from rest_framework.t...
2,332
706
class Solution(object): def rearrangeString(self, str, k): """ :type str: str :type k: int :rtype: str """ ## greedy: count keeps the # of chars, valid keeps the leftmost valid index of a char. res=[] # count # of chars d=coll...
892
267
''' @file momentum_kinematics_optimizer.py @package momentumopt @author Brahayam Ponton (brahayam.ponton@tuebingen.mpg.de) @license License BSD-3-Clause @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft. @date 2019-10-08 ''' import os import numpy as np from momentumopt.kinoptpy.qp import...
16,041
5,688
import logging from gullveig import bootstrap_default_logger # Configure default logging def _configure_default_web_logger(): logger = logging.getLogger('gullveig-web') bootstrap_default_logger(logger) api_logger = logging.getLogger('gullveig-api') bootstrap_default_logger(api_logger) aio_logge...
435
137
import json import urllib import os import jupyterhub from tornado.httpclient import HTTPRequest, AsyncHTTPClient from traitlets import Unicode from jupyterhub.auth import Authenticator from tornado import gen class HttpAuthenticator(Authenticator): server = Unicode( None, allow_none=True, ...
1,482
398
import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt # NOT -> ParameterModule # NOT -> children_and_parameters # NOT -> flatten_model # NOT -> lr_range # NOT -> scheduling functions # NOT -> SmoothenValue # YES -> lr_find # NOT -> plot_lr_find # NOT TO BE MODIFIED class ParameterModu...
9,912
3,154
""" Test the lldb disassemble command on each call frame when stopped on C's ctor. """ from __future__ import print_function import os import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class IterateFrameAndDisassembleTestCase(T...
3,905
1,110
''' All the reserved, individual words used in MAlice. ''' A = "a" ALICE = "Alice" AND = "and" ATE = "ate" BECAME = "became" BECAUSE = "because" BUT = "but" CLOSED = "closed" COMMA = "," CONTAINED = "contained" DOT = "." DRANK = "drank" EITHER = "either" ENOUGH = "enough" EVENTUALLY = "eventually" FOUND = "found" H...
1,116
549
# !/usr/bin/env python3 # Author: C.K # Email: theck17@163.com # DateTime:2021-04-12 18:35:15 # Description: import os import sys class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: res, i = [], 0 for interval in intervals: ...
853
263
# This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2020 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) from pymortests.base import runmodule if __name__ == "__main__": runmodule(filename=__file__...
322
117
from ..utils import SyncClient, __version__ from .bucket import SyncStorageBucketAPI from .file_api import SyncBucketProxy __all__ = [ "SyncStorageClient", ] class SyncStorageClient(SyncStorageBucketAPI): """Manage storage buckets and files.""" def __init__(self, url: str, headers: dict[str, str]) -> No...
756
228
# The MIT License # # Copyright 2014, 2015 Piotr Dabkowski # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the 'Software'), # to deal in the Software without restriction, including without limitation the rights # to use, copy, modif...
1,755
567
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2020, Sandflow Consulting LLC # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, ...
141,721
57,421
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
1,484
429
import torch def expanded_pairwise_distances(x, y): ''' Input: x is a bxNxd matrix y is an optional bxMxd matirx Output: dist is a bxNxM matrix where dist[i,j] is the square norm between x[i,:] and y[j,:] if y is not given then use 'y=x'. i.e. dist[i,j] = ||x[i,:]-y[j,:]||^2 ...
1,886
741
from __future__ import absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals from django.http import HttpResponse, HttpResponseRedirect, JsonResponse, QueryDict #, HttpResponseForbidden, Http404, , JsonResponse from django.shortcuts import get_obj...
8,400
2,580
#!/usr/bin/env python3 # coding: utf8 # /*########################################################################## # # Copyright (c) 2015-2021 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files ...
6,351
1,984
# Copyright 2008-2015 Nokia Solutions and Networks # # 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 l...
7,072
2,114
from dedupe.api import StaticDedupe, Dedupe from dedupe.api import StaticRecordLink, RecordLink from dedupe.api import StaticGazetteer, Gazetteer from dedupe.core import randomPairs, randomPairsMatch, frozendict from dedupe.convenience import consoleLabel, trainingDataDedupe, trainingDataLink, canonicalize
308
91
import unittest from unittest import TestCase from misc import verify class TestVerify(TestCase): """Tests misc.py verifies function.""" def test_verify__with_zero_threshold_and_expected_succeeds(self): """Test passes when expected rate, actual rate and threshold are all zero.""" result = ve...
1,430
424
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding 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-...
4,271
1,366
def migrate(): print('migrating to version 2')
53
20