text
string
size
int64
token_count
int64
import math # this algorithm calculates the maximum sum present in the sublists of length k # in the array nums=list(map(int,input("enter the elements of the list\n").split())) k=int(input("enter the size of the window :")) cursum=sum(nums[:k]) maxsum= cursum for i in range(1,len(nums)-k): cursum=cursum-nums[i-1]+n...
443
171
# A wrapper around configs/learning_gem5/part1/two_level.py # For some reason, this is implicitly needed by run.py root = None import m5 def run_test(root): # Called from tests/run.py # Add paths that we need m5.util.addToPath('../configs/learning_gem5/part1') m5.util.addToPath('../...
748
236
from collections import defaultdict from datetime import datetime from typing import Any, Dict, List, Optional from pyproj import Geod from pystac.utils import str_to_datetime from stactools.core.io import ReadHrefModifier from stactools.core.io.xml import XmlElement from stactools.core.projection import transform_fro...
13,233
4,559
""" This is similar to the assignmapper extensions in SQLAclhemy 0.3 and 0.4 but with some compatibility fixes. It assumes that the session is a ScopedSession, and thus has the "mapper" method to attach contextual mappers to a class. It adds additional query and session methods to the class to support the SQLAlchemy 0....
2,079
612
import gym import numpy as np from viewer import OpenCVImageViewer class GymWrapper(object): """ Gym interface wrapper for dm_control env wrapped by pixels.Wrapper """ metadata = {'render.modes': ['human', 'rgb_array']} reward_range = (-np.inf, np.inf) def __init__(self, env): self._e...
2,191
674
import os for run in range(1, 17): print (run) os.system('python3 app.py --input_uri ../camloc/oct22/'+str(run)+'.mp4 --mot --gui -l results.txt -o output.mp4') os.system('mv pixel-locs.txt camera_'+str(run)+'.txt')
229
93
from django.shortcuts import render from . import models from project import additional_scripts as scripts from django.http import HttpResponse, JsonResponse from django.template.loader import render_to_string from django.views.decorators.csrf import csrf_exempt import re # Create your views here. def get_default_...
3,175
992
# -*- coding: utf-8 -*- # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ Vispy backend for the IPython notebook (WebGL approach). """ from __future__ import division from ..base import (BaseApplicationBackend, BaseCanvasBackend, ...
11,952
3,342
fibMem= {} a="sam" def fib(n): for k in range(1,n+1): print "k : " + str(k) if k<=2: f=1 else: f=fibMem[k-1]+fibMem[k-2] print "printing f : " + str(f) fibMem[k]=f return fibMem[n] print fib(1000) #if __name__ == '__main__': # import timeit # print(timeit.timeit("print a", setup="from __m...
347
179
#Time-related functions 2020/12/22 """Get elapsed time"""#[関数] プログラムの計測時間の表示 def time_elapsed(): import time print(__doc__) start = time.time() print('== Replace the program you want to time here ==') and time.sleep(1) end = time.time() _time=end-start hour,min,sec=_time//3600,_...
635
263
from backend_sqlalchemy.backend_app.models.diseases import DiseasesModel from backend_sqlalchemy.backend_app.db import db from backend_sqlalchemy.backend_app.models.stats import StatsModel def get_stats(): """ Get stats """ all_stats = db.session.query(StatsModel.DID, StatsModel.FID, StatsModel.Sen) ...
434
158
# --------------------------------------------------------- # Save global and basin-mean sea-level curves as Excel file # Single file per basin # --------------------------------------------------------- import numpy as np import os import pandas as pd def main(): settings = {} settings['dir_data'] = os.gete...
6,661
2,416
from multiprocessing import context from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .models import Food, Order from .forms import FoodForm # Create your views here. def home_view(request, template='index.html'): products = Food.objects...
3,053
824
#! /usr/bin/python2.7 #coding=cp850 #mcit@geus.dk # #tail the in_files by lines and write them in out_subdir prepending the aws name # #TODO: quick hack: clean it up import glob, sys, os, os.path from collections import deque def tailer(in_files, lines_limit, out_subdir='.'): for path_name, aws_info in in_fi...
971
344
from django.db import models def user_upload_file_path(instance, filename): "find the path for user upload dir." return 'user_{0}/{1}'.format(instance.user.id, filename) class UploadFile(models.Model): desctiption = models.CharField(max_length=255, blank=True) upload_file = models.FileField(upload_t...
403
134
"""Innovation Maps URL Configuration The `urlpatterns` list routes URLs to views. """ from django.conf.urls import url from InnovationMaps.views import * urlpatterns = [ url(r'^about/$', about, name='innovationmaps_about'), url(r'^guide/$', guide, name='innovationmaps_guide'), url(r'^pdf/$', pdf, name='inn...
744
259
from django.db import models classBook(models.Model): isbn = models.CharField( verbose_name='ISBNコード', max_length=20 ) title = models.CharField( verbose_name='書名', max_length=100 ) price = models.IntegerField( verbose_name=...
885
305
import os, sys, json import numpy as np import xarray as xr from glob import glob from datetime import datetime from netCDF4 import Dataset, num2date, date2num from scipy.interpolate import griddata #- HYCOM GLBv0.08/latest (daily-mean) present + forecast #- Detail info: https://www.hycom.org/dataserver/gofs-3pt1/ana...
2,892
1,264
# Generated by Django 3.2.7 on 2021-10-02 01:57 # Add this file on migrations "clients" from django.db import migrations def apply_migration(apps, schema_editor): Group = apps.get_model('auth', 'Group') Group.objects.bulk_create([ Group(name=u'read_only'), ]) def revert_migration(apps, schema_ed...
663
230
# Project Euler - Problem 7 # What is the 10 001st prime number? import time start = time.time() s = "73167176531330624919225119674426574742355349194934\ 9698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511\ 12540698747158523863050715693290963295227443043557668966489504...
1,464
1,246
# Generated by Django 3.1.2 on 2021-05-16 16:33 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app1', '0091_auto_20210516_2201'), ] operations = [ migrations.AddField( model_name='idea', name='us...
628
227
""" Adding an attribute to a Python dictionary from the standard library - Stack Overflow: https://stackoverflow.com/questions/11532060/adding-an-attribute-to-a-python-dictionary-from-the-standard-library """ class Dict(dict): pass def Foo(): SELF=Dict() SELF.a=1 def b(): return SELF.a SELF...
374
139
import arff as arff import numpy as np datasetRepo = 'BreastCancer' datasetName = 'breast-cancer-wisconsinBinary' data_list=[] for row in arff.load('/home/lukas/Uni/AAThesis/Datasets/'+ datasetRepo +'/'+ datasetName +'.arff'): data_list.append(row) data_np=np.array(data_list,dtype=float) #eliminate missing #i...
901
342
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import clipl.utility.logger as logger log = logging.getLogger(__name__) import argparse import clipl.utility.jsonTools as jsonTools import clipl.utility.tools as tools import glob import os import shlex import sys from clipl.utility.tools import hadd de...
1,550
515
import codecs import collections from typing import * import os import tensorflow as tf import csv import tokenization import numpy as np import re import utils class InputExample(object): """A single training/test example for simple sequence classification.""" def __init__(self, guid, text, labels=None): ...
12,135
3,878
# Copyright (c) SenseTime. All Rights Reserved. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from siamrpnpp.core.config import cfg from siamrpnpp.tracker.siamrpn_tracker import SiamRPNTracker from siamrpnpp.tracker...
654
233
class Solution: def swimInWater(self, grid: List[List[int]]) -> int: t = 0 seen = set((0,0)) frontier = [(0,0)] while True: new_frontier = [] while frontier: y,x = frontier.pop() if grid[y]...
807
254
from PyQt5 import QtCore, QtWidgets, QtGui import pyqtgraph as pg import numpy as np import socket import pyproj from pyqtgraph import functions as fn from gps3 import gps3 import sys from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QLineEdit, QMessageBox from PyQt5.QtGui import QIc...
5,108
1,986
import numpy as np from dataclasses import dataclass from typing import List, Any from datetime import datetime @dataclass(frozen=True) class UDBFHeader: """Data-class for meta-data of the UDBFData class. Attributes: udbf_version (int): Version of the UDBF file structure times 100. vendor (st...
4,710
1,283
import logging import pytest from psyneulink.core.components.functions.transferfunctions import Linear from psyneulink.core.components.mechanisms.processing.transfermechanism import TransferMechanism from psyneulink.core.components.projections.pathway.mappingprojection import MappingProjection from psyneulink.core.co...
34,263
10,980
from vulyk.admin.models import AuthModelView, CKTextAreaField from wtforms.validators import Required from wtforms.fields import SelectField class PluginsSelectField(SelectField): def __init__(self, *args, **kwargs): choices = [ ("", ""), ] from vulyk.app import TASKS_TYPES ...
1,267
413
import pandas as pd import numpy as np from . import datamonger class PickyInvestor(): def __init__(self): self.hushen300df = ['600038.SH','600522.SH','600406.SH','601800.SH'] def setBrokerDatabase(self, db_instance): self.brokerdb = db_instance def setMarketDatabase(self, db_instance): ...
1,488
506
import os import numpy as np import tensorflow as tf import datetime import csv as csv import pandas as pd import operator print ("Packages loaded") #load training and testing data train = pd.read_csv('input/train.csv', header = 0, dtype={'Age': np.float64}) test = pd.read_csv('input/test.csv' , header = 0, dtype={'A...
5,717
2,144
# https://www.hackerrank.com/challenges/s10-poisson-distribution-2/problem # Enter your code here. Read input from STDIN. Print output to STDOUT x,y = list(map(float, input().split(" "))) cost1 = 160 + 40*(x+x**2) cost2 = 128 + 40*(y+y**2) print(round(cost1, 3)) print(round(cost2, 3))
286
126
import os import index.MovieDAO as movieDAO from pprint import pprint from index import SysConst import shutil def getAllMovies(path): movieTypes = set(["avi", "mp4", "mkv", "rmvb", "wmv", "txt"]) results = [] for fpath, dirs, fs in os.walk(path): for filename in fs: fullpath...
3,839
1,251
import torch import torch.nn.functional as F import torch.nn as nn # Custom imports from .base_semi_apppearance_temporal_simclr import SemiAppTemp_SimCLR_BaseRecognizer from ..builder import RECOGNIZERS from ..losses import CosineSimiLoss from ...utils import GatherLayer @RECOGNIZERS.register_module() class Semi_App...
30,555
10,359
"""This is a template file for holding version numbers.""" GRPC_VERSION = '1.11.0'
83
28
from __future__ import print_function from ast import dump from numpy.lib.npyio import save from calibration_library.metrics import ECELoss, CCELoss import io from logging import log from experiments.classCali_full_CRF import convcrf from experiments.classCali_full_CRF.convcrf import GaussCRF, get_default_conf import...
29,968
9,732
import time from django.http import HttpResponseRedirect from otree.models import Participant from . import models from ._builtin import Page, WaitPage class DecorateIsDisplayMixin(object): def __init__(self): super(DecorateIsDisplayMixin, self).__init__() # We need to edit is_displayed() method ...
9,585
2,866
# -*- coding: utf-8 -*- import pytest import time import sys import socket from .test_base_class import TestBaseClass from .as_status_codes import AerospikeStatus from aerospike import exception as e aerospike = pytest.importorskip("aerospike") try: import aerospike except: print("Please install aerospike pyt...
7,424
2,274
import argparse import os.path import sys import io import _io import filecmp from collections import OrderedDict from math import ceil import csv from queue import Queue, Empty def false(): return False class MyParser(argparse.ArgumentParser): def error(self, msg): sys.stderr.write('error: {}\n'.for...
7,175
2,260
# Generated by Django 2.0 on 2018-01-29 07:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('datatrans', '0004_alias_registration_fields_optional'), ] operations = [ migrations.AlterField( model_name='aliasregistration', ...
457
150
import dbus import time import logging from metadata import Metadata PLAYING = "playing" mpris = None MPRIS_NEXT = "Next" MPRIS_PREV = "Previous" MPRIS_PAUSE = "Pause" MPRIS_PLAYPAUSE = "PlayPause" MPRIS_STOP = "Stop" MPRIS_PLAY = "Play" mpris_commands = [MPRIS_NEXT, MPRIS_PREV, MPRIS_PAUSE, MPRI...
7,494
2,099
import paramiko,sys,os from socket import * host = raw_input('Enter host to scan: ') targetIP = gethostbyname(host) ssh = paramiko.SSHClient() def ssh_connect(user,password,code=0): ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) print("[*] Host: "+targetIP) print("[*] Tes...
1,305
520
#!/usr/bin/env python import logging import re import subprocess import time import urllib2 DIST_TEST_URL = "http://dist-test.cloudera.org" # GCE bills 10-minute minimum, so if we've started instances # more recently than 10 minutes ago, we shouldn't shut them down. SHRINK_LAG = 600 def get_stats(): page = urllib2...
1,743
626
class Solution: def kLengthApart(self, nums: List[int], k: int) -> bool: prev_1 = -1 for idx, i in enumerate(nums): if i==1: if prev_1==-1: prev_1 = idx continue if idx-prev_1-1>=k: prev_1 = idx ...
396
110
# content of test_expectation.py import pytest import nlu from nose2.tools import params import unittest from parameterized import parameterized, parameterized_class ''' Test every component in the NLU namespace. This can take very long ''' all_default_references = [] i=0 for nlu_reference in nlu.NameSpace.component_...
2,587
908
from flask import Blueprint from ..models import Permission main=Blueprint('main',__name__) from . import views,errors @main.app_context_processor def inject_permissions(): return dict(Permission=Permission)
220
66
#!/usr/bin/python3.4 # -*- coding: utf-8 -*- from forbiddenfruit import curse controlcodes = {'bold': '\x02', 'underlined': '\x1F', 'italic': '\x1D', 'reset': '\x0F', 'reverse': '\x16'} colorlist = {'white': '00', ...
2,158
672
salario = float(input("Enter o seu salario: ")) novosalario = salario + (salario*0.15) print('O valor do salario e {} e o acrescimo de 15% no novo salario e {}'.format(salario, novosalario))
192
74
import requests import time import os import json from pathlib import Path class mainScreen: def __init__(self): splash() self.menu = screen._screen([ ["select", None], ["select core",callSelectCore], ["time", getTime], ["splash", splash], ...
2,565
862
import pygame from pygame.locals import * import sys from pygame3D import * <<<<<<< HEAD import time ======= import numpy as np import time import cv2 import math >>>>>>> 8da8f0ff1109db951a4915c1aecb7f4d7de41630 pygame.init() camera = Camera(position=(0, 0, 0), rotation=(0, 0, 0), fov=137, clipping_pla...
2,753
1,193
from __future__ import (absolute_import, division, print_function) __metaclass__ = type try: import ovh from ovh.exceptions import APIError HAS_OVH = True except ImportError: HAS_OVH = False def ovh_api_connect(module): if not HAS_OVH: module.fail_json(msg='python-ovh must be installed to...
1,171
347
def VERSION(): VERSION = 'YOUR_VERSION_HERE' return VERSION
68
27
"""Compute rank correlations between word vector cosine similarities and human ratings of semantic similarity.""" import numpy as np import pandas as pd import argparse import os import scipy.spatial.distance import scipy.stats from .vecs import Vectors from .utensils import log_timer import logging logging.b...
5,962
1,842
# Copyright 2017 ProjectQ-Framework (www.projectq.ch) # # 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 app...
1,772
581
# Generated by Django 3.0.8 on 2020-08-01 23:15 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('backend', '0011_auto_20200731_2107'), ] operations = [ migrations.AlterField( model_name='code'...
1,356
436
import sentencepiece as spm import logging import json import sys import os import re import copy from typing import Any, Dict, List, Optional, Union from transformers import Wav2Vec2CTCTokenizer from itertools import groupby logger = logging.getLogger(__name__) logging.basicConfig( format="%(asctime)s - %(levelna...
8,345
2,621
import pytest from whylogs.app.config import SessionConfig from whylogs.app.session import ( Session, get_or_create_session, get_session, reset_default_session, session_from_config, ) def test_get_global_session(): session = get_or_create_session() global_session = get_session() ass...
2,794
826
import sys import argparse valid_chr = ["chr1", "chr2", "chr3", "chr4", "chr5", "chr6", "chr7", "chr8", "chr9", "chr10", "chr11", "chr12", "chr13", "chr14", "chr15", "chr16", "chr17", "chr18", "chr19", "chr20", "chr21", "chr22", "chrM", "chrX", "chrY"] def get_params(): parser = argparse.ArgumentParser(d...
863
383
""" Copyright (c) 2019 Intel 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 agreed to in wri...
1,742
573
import os from tests.package.test_python import TestPythonPackageBase class TestPythonPy3PytestAsyncio(TestPythonPackageBase): __test__ = True config = TestPythonPackageBase.config + \ """ BR2_PACKAGE_PYTHON3=y BR2_PACKAGE_PYTHON_PYTEST=y BR2_PACKAGE_PYTHON_PYTEST_ASYNCIO=y ...
672
226
print ('Hola Mundo desde demo.py')
35
12
from .column_types import ( # noqa: F401 Boolean, Bytea, Date, Decimal, Float, ForeignKey, Integer, Interval, JSON, JSONB, Numeric, PrimaryKey, Real, Secret, Serial, Text, Timestamp, Timestamptz, UUID, Varchar, ) from .base import ( # noq...
516
195
import ferramentas_usuarios as fe class Produto: codigo = fe.gera_codigo() def __init__(self, data_ger, prazo_ent, inicio_pro, final_proc, inicio_cont, final_cont): """Cria um banco de dados baseado em um arquivo TXT""" self.data_geracao = data_ger self.prazo_entrega = prazo_ent ...
519
185
'''tzinfo timezone information for Africa/Mbabane.''' from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i class Mbabane(DstTzInfo): '''Africa/Mbabane timezone definition. See datetime.tzinfo for details''' zone = 'Africa/Mbabane' ...
489
213
import warnings import numpy as np import matplotlib.pyplot as plt import pandas as pd from PIL import Image solutions = pd.read_csv('D:\\code\\galaxy-zoo-the-galaxy-challenge\\training_solutions_rev1.csv', sep = ',') solutions = solutions.loc[solutions["Class1.3"] < 0.5] solutions = solutions.loc[:, ["GalaxyID", "Clas...
1,108
448
# -*- coding: utf-8 -*- # Module 'phone_sender' of the project 'tingerwork' # :date_create: 11.12.2017.4:21 # :author: Tingerlink # :description: import json import requests import config.settings import tools.logger as logger class PhoneSender: def __init__(self): self.password = config.se...
2,470
830
import torch w=torch.tensor(2.0,requires_grad=True)#set variable y=w**2 z=2*y+5 z.backward()#grad print('수식을 w로 미분한 값 : {}'.format(w.grad))#call result
154
82
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file was originally developed for EvalNE by Alexandru Cristian Mara import argparse import numpy as np import networkx as nx import ast import time from utils import AROPE # Although the method says it requires python 3.5, it should be run with python 2.7 for optim...
4,155
1,289
import re _canonicalize_regex = re.compile('[-_.]+') def canonicalize_name(name: str) -> str: return _canonicalize_regex.sub('-', name).lower() def module_name(name: str) -> str: return canonicalize_name(name).replace('-', '_')
241
88
# -*- coding: utf-8 -*- import copy from mygrid.util import Phasor, R, P from mygrid.util import r2p, p2r from mygrid.grid import Section, TransformerModel, Auto_TransformerModel import numpy as np # from pycallgraph import PyCallGraph # from pycallgraph.output import GraphvizOutput from numba import jit from functo...
15,670
5,322
# Create a dataframe using pandas series import pandas as pd cols = ['a','b'] list_of_series = [pd.Series([1,2],index=cols), pd.Series([3,4],index=cols)] df = pd.DataFrame(list_of_series, columns=cols) print(df)
212
76
from typing import List import click from contxt.cli.clients import Clients from contxt.cli.utils import fields_option, print_table, sort_option from contxt.models.assets import Asset, AssetType @click.group() def assets() -> None: """Assets.""" @assets.command() @fields_option(default=["id", "label", "descri...
1,036
354
import numpy as np import pytest from lib4.brownian_motion import BrownianMotion, ParamBrownianMotion CORRECT_DATASET = [ # (seed, initial_state, sigma, state_trajectory) (123, 0.0, 10.0, np.array([ 0., -9.891213503, -13.56908001, -0.68982741, ])), (456, -2.0, 1.0, np.ar...
3,785
1,429
# System modules import sys import os import pdb import pathlib import copy import multiprocessing as mp import numpy as np import yaml # Path modifications paths = ["../../build/src", "../preproc", "../util"] for item in paths: addPath = pathlib.Path(__file__).parent / item sys.path.append(str(addPath.resolv...
4,280
1,341
from . import gather_conmats
29
10
from poetry.puzzle.solver import Solver
40
14
""" Script# : 3 INPUT: Raw Data File generated by Amazon Seller Central Portal for a particular seller that has been fed as webpage input by registered User AND undergone 'ordersFile_preprocessing' script. OUTPUT: Delivers data for Information Dashboard as a Pandas DataFrame or TextParserself. Generalization and a...
16,916
5,664
from cyaron import * max_node = 1000000 for i in range(5): io = IO(str(i + 1) + '.in', str(i + 1) + '.out') tree = Graph.tree(max_node) leaf = [] for i in tree.edges: if len(i) == 1: leaf.append(randint(0, 10000)) io.input_writeln(max_node) io.input_writeln(tree.to_str(outp...
448
195
import numpy as np import cv2 import pandas as pd from ._base import ModelBase def merge_similar_lines(l, lines): # Put unique lines in array if theres only 1, for looping if len(lines.shape) == 1: lines = np.array([lines]) # Translate line to align with each unique line d = np.column_stack...
19,091
6,592
from __future__ import print_function, absolute_import, division from argparse import ArgumentDefaultsHelpFormatter def func(args, parser): # delay import of the rest of the module to improve `osprey -h` performance from ..execute_worker import execute execute(args, parser) def configure_parser(sub_pars...
766
214
#!/usr/bin/sudo / usr/bin/python import RPi.GPIO as GPIO import random from time import sleep # Use board pin numbering GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) # Start a new dictionary with desired LED names leds = {'floor':[], 'top-left':[]} # Take name of led and list of pins for RGB def setupled(name, p...
4,772
2,326
import configparser from jinja2 import Template conf = configparser.ConfigParser() # 用config对象读取配置文件 conf.read("base.config.ini") sections = conf.sections() dit = {} def analyze_ini(): ''' 分析ini配置文件读取的数据,放到dit里面 :return: ''' for classname in sections: print(classname, conf.items(classname...
2,711
917
from functools import reduce from dynts.conf import settings from ...api import timeseries, is_timeseries class Expr: '''Base class for abstract syntax nodes ''' def count(self): '''Number of nodes''' return 1 def malformed(self): return False @property ...
9,833
2,992
""" Calculates distance of some (bpp, metric) point (for some metric) to some codec on some dataset. """ import os import numpy as np import scipy.interpolate from utils import other_codecs import constants from utils import logdir_helpers from collections import defaultdict from fjcommon import functools_ext as ft f...
5,633
2,009
#!/usr/bin/env python from __future__ import unicode_literals # Copyright 2016 Google 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/LICEN...
18,056
5,682
import os import unittest from runner import Runner MODULE_NAME = "e2e" RESOURCE_TYPE = "aws_vpc.this" class TestE2E(unittest.TestCase): @classmethod def setUpClass(self): self.snippet = """ provider "aws" { access_key = "test" region ...
2,245
674
import pandas as pd import numpy as np from collections import OrderedDict from .statistics import Statistics class PhoneNumber(Statistics): categories = { ('Only numbers', '^[0-9]+$'), ('Numbers and parentheses', '^(?:[0-9]*[\(][0-9]+[\)][0-9]*)+$'), ('Numbers and + symbol', '^(?:[0-9]*[\+][0-9]+)+$'), ('Nu...
854
335
from pydub import AudioSegment import os from pydub.utils import mediainfo from unittest import mock from service.core import process_message from service.aws_boto3 import ( listen_sqs_queue, create_s3_resource, create_sqs_resource, ) from service.settings import ( REQUEST_QUEUE_NAME ) """ These two f...
2,256
680
from typing import List, Union from binascii import unhexlify from ndnkdf import NDNKDF from vccs.server.db import PasswordCredential from vccs.server.factors import RequestFactor from vccs.server.hasher import VCCSYHSMHasher from vccs.server.log import audit_log async def authenticate_password( cred: PasswordCr...
3,156
1,097
import io from unittest import TestCase import pytest from django.core.files import File from django_dynamic_fixture import G from magplan.models import Attachment from magplan.xmd.utils import get_attachment_original_filename @pytest.mark.django_db class Test_get_attachment_original_filename(TestCase): def set...
1,226
359
import glob import numpy as np import os import pandas as pd import strictyaml import tempfile import shutil import warnings from collections import defaultdict from inspect import signature from strictyaml import Map, Str, Optional, Int, CommaSeparated import topicnet from topicnet.cooking_machine.dataset import Da...
17,877
6,079
from pac_library import * from regexp_naive import * def fetch_training_words(language): return(read_wordpairs('../daru-dataframe/spec/fixtures/'+language+'-train-high')) def fetch_testing_words(language): return(read_wordpairs('../daru-dataframe/spec/fixtures/'+language+'-dev')) def fetch_common_words(language)...
4,757
1,589
from django.urls import path,include from product.views import ( ProductDetailView, ProductView, shopping_cart, wishlist ) app_name='product' urlpatterns = [ path('product-detail/<int:pk>/', ProductDetailView.as_view(),name='product_detail'), path('product-list/', ProductView.as_view(),name=...
454
154
n = int(input()) new_n = ((((n * 2) * n) - n) // n) print(new_n)
66
38
# -*- coding: utf-8 -*- from GestureAgentsDemo.Render import Update, drawBatch from pyglet.text import Label from pyglet.clock import schedule_once class DynamicValue(object): """docstring for DynamicValue""" def __init__(self, value=0): self.value = value self.target = value self.tim...
1,346
413
from dataclasses import dataclass from jiant.tasks.lib.templates.shared import labels_to_bimap from jiant.tasks.lib.templates import multiple_choice as mc_template from jiant.utils.python.io import read_jsonl @dataclass class Example(mc_template.Example): @property def task(self): return MbeTask @dataclass class...
1,437
576
__all__ = ['win_peak_memory'] import ctypes from ctypes import wintypes GetCurrentProcess = ctypes.windll.kernel32.GetCurrentProcess GetCurrentProcess.argtypes = [] GetCurrentProcess.restype = wintypes.HANDLE SIZE_T = ctypes.c_size_t class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure): _fields_ = [ ('cb'...
1,590
549
import unittest from unittest.mock import Mock import os import shutil import tempfile import torchvision.models as models from trojai.modelgen.architecture_factory import ArchitectureFactory from trojai.modelgen.data_manager import DataManager from trojai.modelgen.config import ModelGeneratorConfig class MyArchFa...
3,120
1,020