text
string
size
int64
token_count
int64
import numpy as np import os import torch import torch.utils.data as data import pdb import pickle from pathlib import Path from scipy import signal import librosa import scipy from itertools import permutations from numpy.linalg import solve import numpy as np import soundfile as sf from convolutive_prediction import ...
28,191
9,936
#coding:utf-8 # # id: bugs.core_4160 # title: Parameterized exception does not accept not ASCII characters as parameter # decription: # tracker_id: CORE-4160 # min_versions: ['3.0'] # versions: 3.0 # qmid: None import pytest from firebird.qa import db_factory, isql_act, Action # vers...
3,053
1,140
import TreeClassification as T T.clearScreen() dataTraining= T.loadData("dataTraining.txt") X=dataTraining[:,0:3] y=dataTraining[:,3:4] Threshold=30 #Training TrainedTree = T.SplitTree(X, y,ThresholdCount=Threshold) newX,newY=T.PredictTree(X,y,TrainedTree) #CheckAccuracy Xy=T.concatenateVectors(X,y) ...
784
331
#!/usr/bin/env python """Tests for the jwcf hawki module. Authors ------- Johannes Sahlmann """ import netrc import os from astropy.table import Table import pytest from ..archive_helpers import get_exoplanet_orbit_database, gacs_list_query local_dir = os.path.dirname(os.path.abspath(__file__)) ON_TRAVIS = os...
1,535
581
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 2 14:33:13 2018 @author: Nathan """ import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler # load dataset data,target =load_iris().data,load_...
1,264
453
import os TRANSFORMERS = '/home/noone/documents/github/transformers' TOKENIZERS = '/home/noone/documents/github/tokenizers' DATASETS = '/home/noone/documents/github/datasets' MODELS = os.path.join(TRANSFORMERS, 'src/transformers/models') DEBERTA_V2 = os.path.join(MODELS, 'deberta_v2') DEBERTA_V3 = os.path.join(MO...
1,013
386
#Par ou Impar- para qnd o jogador perder e mostra o tanto de vitoria consecutivas from random import randint c = 0 while True: print('\033[1;33m-' * 30) n = int(input('ESCOLHA UM NÚMERO: ')) e = str(input('PAR OU IMPAR? ')).strip().upper()[0] print('-' * 30) j = randint(0, 10) if e == 'P': ...
830
385
""" This file tests that sendmmsg works correctly. Target files: - libdesock/src/write.c """ import ctypes import desock import helper data = bytes(range(65, 115)) cursor = 0 def _get_data(size): global cursor ret = bytes(data[cursor: cursor + size]) assert(len(ret) == size) cursor += size r...
1,727
706
import numpy as np from math import factorial import scipy.signal #Gaussian filter with convolution - faster and easier to handle ## Degree is equal to the number of values left and right of the central value ## of the gaussian window: ## ie degree=3 yields a window of length 7 ## It uses normalized weights (sum of ...
8,409
3,059
import os from datetime import datetime, timedelta import discord from matplotlib import pyplot as plt import discordbot.config_discordbot as cfg from discordbot.run_discordbot import gst_imgur import discordbot.helpers from gamestonk_terminal.helper_funcs import plot_autoscale from gamestonk_terminal.common.technica...
3,879
1,354
import argparse import os import shutil import numpy as np import torch as t from torch.optim import Adam from utils.batch_loader import BatchLoader from utils.parameters import Parameters from model.rvae_dilated import RVAE_dilated if __name__ == "__main__": parser = argparse.ArgumentParser(description='RV...
5,011
1,729
from graphql import GraphQLResolveInfo import frappe from renovation_core.utils.auth import generate_otp, verify_otp VERIFY_OTP_STATUS_MAP = { "no_linked_user": "NO_LINKED_USER", "no_otp_for_mobile": "NO_OTP_GENERATED", "invalid_otp": "INVALID_OTP", "verified": "VERIFIED", } def generate_otp_resol...
1,152
438
import os import numpy as np from shapely.wkt import loads from shapely.geometry import Point from shapely.geometry.base import BaseGeometry import pandas as pd import geopandas as gpd import rasterio import skimage from fiona._err import CPLE_OpenFailedError from fiona.errors import DriverError from warnings import wa...
6,050
1,873
from .von_mises_stiefel import * from .von_mises_fisher import * from .model import * from .metrics import * from .loss import *
129
45
from django import template from blog_app.models import Post from django.utils import timezone register = template.Library() @register.simple_tag(name='list_tags') def get_list_tags(pos, cnt_head_tag, cnt_side_tag): list_tags = Post.tag.most_common() if pos == 'head': return list_tags[:cnt_head_tag] ...
980
325
__author__ = 'Bohdan Mushkevych' from os import path from azure.storage.blob import BlockBlobService from flow.core.abstract_filesystem import AbstractFilesystem, splitpath class AzureBlobFilesystem(AbstractFilesystem): """ implementation of Azure Page Blob filesystem https://docs.microsoft.com/en-us/azur...
3,941
1,198
from typing import Type, Any, Dict, Optional class RegistryItem: def __init__(self, type: Type, value: Any) -> None: self.type = type self.value = value class TypesRegistry: def __init__(self): self.__data: Dict[Type, RegistryItem] = {} self.__by_name: Dict[str, RegistryItem]...
1,085
321
from tqdm import tqdm import json import os def save_jsonl(data_list, filename): with open(filename, 'w', encoding='utf-8') as fo: for data in data_list: fo.write("{}\n".format(json.dumps(data))) fo.close() print("Success save file to %s \n" %filename) def save_json(d...
591
205
import asyncio import pytest import re import uuid from aiohttp.test_utils import teardown_test_loop from aioredis import create_redis from arq import ArqRedis, Worker from atoolbox.db import prepare_database from atoolbox.db.helpers import DummyPgPool from atoolbox.test_utils import DummyServer, create_dummy_server fr...
6,563
2,144
from django.conf.urls import include, url from django.contrib import admin from django.views.generic import View urlpatterns = [ url(r'^client/', include('client.urls', namespace = 'client', app_name = 'client')), url(r'^app/', include('app.urls', namespace = 'app', app_name = 'app')), url('', include('django....
477
159
from django.contrib import admin from prediction.models import product from prediction.models import price # Register your models here. admin.site.register(product) admin.site.register(price)
193
48
""" imutils/big/make_shards.py Generate one or more webdataset-compatible tar archive shards from an image classification dataset. Based on script: https://github.com/tmbdev-archive/webdataset-examples/blob/7f56e9a8b978254c06aa0a98572a1331968b0eb3/makeshards.py Added on: Sunday March 6th, 2022 Example usage: pytho...
5,813
2,317
# -*- coding: utf-8 -*- # Copyright (c) 2018-2021, earthobservations developers. # Distributed under the MIT License. See LICENSE for more info. import os from io import BytesIO from typing import List, Optional, Union from fsspec.implementations.cached import WholeFileCacheFileSystem from fsspec.implementations.http ...
2,917
980
""" Non-orthogonal Reflection by Ira Greenberg. Based on the equation (R = 2N(N * L) - L) where R is the reflection vector, N is the normal, and L is the incident vector. """ # Position of left hand side of floor. base1 = None # Position of right hand side of floor. base2 = None # A list of subpoints along the floo...
2,927
986
import numpy as np from module import Module class Linear(Module): def __init__(self, name, input_dim, output_dim, l2_coef=.0): super(Linear, self).__init__(name) self.l2_coef = l2_coef # coefficient of l2 regularization. self.W = np.random.randn(input_dim, output_dim) # weights of the...
1,182
368
from pymongo import MongoClient from bson import ObjectId from bson.json_util import dumps from json import loads client = MongoClient('localhost', 27017) IOT_DB = client.iot_db IOT_SCHEMAS = IOT_DB.iot_schemas IOT_DATA = IOT_DB.iot_data
239
90
from .base_page import BasePage from .locators import LoginPageLocators class LoginPage(BasePage): def should_be_login_page(self): self.should_be_login_url() self.should_be_login_form() self.should_be_register_form() def should_be_login_url(self): assert "login" in self.brows...
659
209
import pytest from marshmallow_jsonapi import fields from starlette.applications import Starlette from starlette_jsonapi.resource import BaseResource from starlette_jsonapi.schema import JSONAPISchema def test_schema_urls(app: Starlette): class TResource(BaseResource): type_ = 'test-resource' TResour...
4,310
1,306
# -*- coding: utf-8 -*- """ Django settings for demo project. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ # Build paths inside the project like this: os.path.j...
3,280
1,140
from Cryptodome.PublicKey import RSA import hashlib import json def recover(key): private_key_readable = key.exportKey().decode("utf-8") public_key_readable = key.publickey().exportKey().decode("utf-8") address = hashlib.sha224(public_key_readable.encode("utf-8")).hexdigest() wallet_dict = {} wal...
818
291
def isPower(n): ''' Determine if the given number is a power of some non-negative integer. ''' if n == 1: return True sqrt = math.sqrt(n) for a in range(int(sqrt)+1): for b in range(2, int(sqrt)+1): if a ** b == n: return True return False
316
102
# Add your own choices here! fruit = ["apples", "oranges", "pears", "grapes", "blueberries"] lunch = ["pho", "timmies", "thai", "burgers", "buffet!", "indian", "montanas"] situations = {"fruit":fruit, "lunch":lunch}
218
90
''' Stolen straight from https://stackoverflow.com/a/51337247/1224827 ''' try: import PIL import PIL.Image as PILimage from PIL import ImageDraw, ImageFont, ImageEnhance from PIL.ExifTags import TAGS, GPSTAGS import os import glob except ImportError as err: exit(err) class Worker(object): ...
1,806
590
from __future__ import absolute_import from .load import load_ckpt from .save import save_ckpt
102
36
import os from rllab.envs.normalized_env import normalize from rllab.misc.instrument import stub, run_experiment_lite from sandbox.rocky.tf.envs.base import TfEnv from rllab.envs.gym_env import GymEnv from railrl.algos.ddpg import DDPG from railrl.policies.nn_policy import FeedForwardPolicy from railrl.qfunctions.nn_q...
1,730
827
import re import pytest from hiku import query as q from hiku.graph import Graph, Node, Field, Link, Option, Root from hiku.types import Record, Sequence, Integer, Optional, TypeRef from hiku.utils import listify from hiku.engine import Engine, pass_context, Context from hiku.builder import build, Q from hiku.executo...
17,974
6,431
__author__ = 'Brian Nguyen' def greeting(msg): print("We would like to say: " + msg)
90
35
#!/usr/bin/python3 #### A tool for blocking all verified users on Twitter. ## You may want to create a (public or private) Twitter list named 'exceptions' and add verified users to it. ## This 'exceptions' list that you create on Twitter is for verified accounts that you like and do not want to block. #### Import dep...
6,251
1,853
""" Common functions --- Package: PACKET-MAPPER Author: Sapunov Nikita <kiton1994@gmail.com> """ import netaddr import socket def ip2str(address): """ Print out an IP address given a string Args: address (inet struct): inet network address Returns: str: Printable/readable IP address...
586
191
#!/usr/bin/env python # -*- coding: utf-8 -*- # This script tests the function that builds the Un-Net model combined # with the ResNet50 model as an encoder. The test does not look for # numerical values but checks if the model returns am object or not. # This is because there are several tests within the UNet class t...
1,236
453
# Exploit Title: PHP 8.1.0-dev - 'User-Agentt' Remote Code Execution # Date: 23 may 2021 # Exploit Author: flast101 # Vendor Homepage: https://www.php.net/ # Software Link: # - https://hub.docker.com/r/phpdaily/php # - https://github.com/phpdaily/php # Version: 8.1.0-dev # Tested on: Ubuntu 20.04 # References: ...
1,988
735
""" Module that contains the command line app. Why does this file exist, and why not put this in __main__? You might be tempted to import things from __main__ later, but that will cause problems: the code will get executed twice: - When you run `python -mflashcards` python will execute ``__main__.py`` as a...
2,271
641
import aiohttp import asyncio import time start_time = time.time() async def get_pokemon(session,url): async with session.get(url) as resp: pokemon = await resp.json() return pokemon["name"] async def main(): async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=64,verif...
744
252
from matplotlib import rc rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) rc('text', usetex=True) rc('legend',**{'fontsize':11}) # Font size for legend from mpl_toolkits.axes_grid.axislines import SubplotZero import matplotlib as mpl mpl.rcParams['lines.linewidth'] = 2.5 import matplotlib.pyplot as plt...
3,454
1,432
import json import urllib2 import traceback import cgi from flask import render_template, request import web.util.tools as tools import lib.http as http import lib.es as es from web import app from lib.read import readfile def get(p): host = p['c']['host']; index = p['c']['index']; # debug p['debug'] = ...
3,820
1,167
#!/usr/bin/python3 from board_util import GoBoardUtil from gtp_connection import GtpConnection class PolicyPlayer(object): """ Plays according to the Go4 playout policy. No simulations, just random choice among current policy moves """ version = 0.1 name = "Policy Probabilistic Player...
1,043
303
from keras.preprocessing.image import img_to_array from keras.models import load_model import numpy as np import argparse import imutils import cv2 ap = argparse.ArgumentParser() ap.add_argument("-m1", "--model1", required=True, help="path to model1") ap.add_argument("-m2", "--model2", required=True, help="path to mo...
1,531
632
""" This module contains the general settings used across modules. """ FPS = 60 WINDOW_WIDTH = 1100 WINDOW_HEIGHT = 600 TIME_MULTIPLIER = 1.0
143
62
# -*- coding: utf-8 -*- import logging from logging import handlers import pickle import time import uuid from bson.binary import Binary from bson.json_util import dumps from flask import request from flask_classful import FlaskView import pymongo from requests import ConnectTimeout, ConnectionError from katana.share...
7,974
2,382
import threading import traceback import socketserver import struct import time import sys import http.client import json import uuid import config import dns.rdatatype import dns.rdataclass args = config.args QTYPES = {1:'A', 15: 'MX', 6: 'SOA'} custom_mx = uuid.uuid4().hex # https://github.com/shuque/pydig GNUv2...
7,400
2,499
from django.template import Library, Node, TemplateSyntaxError from django.utils.encoding import force_unicode from convert.base import MediaFile, EmptyMediaFile, convert_solo from convert.conf import settings register = Library() class ConvertBaseNode(Node): def error(self, context): if sett...
3,278
1,027
from unittest.mock import MagicMock import datetime import json import unittest from tda.orders import EquityOrderBuilder from tda.utils import Utils from . import test_utils class MockResponse: def __init__(self, json, ok, headers=None): self._json = json self.ok = ok self.headers = hea...
7,826
2,747
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
9,535
2,501
from discord.ext import commands import asyncio import time class AntiSelfDeprecation(commands.Cog): def __init__(self, bot): self.bot = bot self.bot.nono_words = [] self.dumb = ('im dumb', 'i\'m dumb', 'im stupid', 'i\'m stupid') self.not_dumb = ('im not dumb', 'i\'m not dumb', ...
2,088
691
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
10,809
4,153
import queue import threading from subprocess import PIPE, Popen procs = [] stdout = queue.Queue() def process_stdout(proc): while (line := proc.stdout.readline()) != b"": stdout.put(line.decode().strip()) procs.remove(proc) def create_proc(uri): proc = Popen(["unbuffer", "xdg-open", uri], stdo...
431
148
import factory from pages.official_documents_page.models import OfficialDocumentPage, OfficialDocumentCollectionOfficialDocumentPage from pages.base_page.factories import JanisBasePageFactory from pages.official_documents_collection.factories import OfficialDocumentCollectionFactory from wagtail.documents.models import...
1,834
452
from flask import Blueprint, render_template, request, redirect, url_for from flask_login import current_user, login_required from flask_cors import CORS from flask_qa.extensions import db from flask_qa.models import Question, User, Stats, Notes import json main = Blueprint('main', __name__) @main.route('/')...
6,927
2,223
from __future__ import print_function from __future__ import absolute_import from __future__ import division try: basestring except NameError: basestring = str import os import sys import ast from compas_rhino.forms import TextForm from compas_rhino.forms import ImageForm import System import rhinoscriptsy...
7,453
2,099
import torch import numpy as np import matplotlib.pyplot as plt from lib.utils import moving_average, check_numpy @torch.no_grad() def visualize_pdf(maml): i = 0 plt.figure(figsize=[22, 34]) for name, (weight_maml_init, bias_maml_init) in maml.initializers.items(): weight_base_init, _ = maml.untra...
3,539
1,334
from __future__ import division # import urllib2 import os, sys import numpy as np import pandas as pd from collections import defaultdict from sklearn import feature_extraction from sklearn import preprocessing from random import seed, shuffle # sys.path.insert(0, '../../fair_classification/') # the code for fair cla...
3,170
1,063
#!/usr/bin/env python # # Copying a pin is not representative of typical user behavior on Pinterest. # # This script is intended to demonstrate how to use the API to developers, # and to provide functionality that might be convenient for developers. # For example, it might be used as part of a program to generate an # ...
2,300
679
import unreal BL_ColorRamp4 = unreal.AssetToolsHelpers.get_asset_tools().create_asset('BL_ColorRamp4', '/Engine/Functions/BLUI/', unreal.MaterialFunction, unreal.MaterialFunctionFactoryNew()) BL_ColorRamp4.set_editor_property("expose_to_library", True) BL_ColorRamp4.set_editor_property("library_categories_text", (...
10,308
4,058
import os import re import glob import argparse import pandas as pd list_test = ['alexnet', 'inception3', 'inception4', 'resnet152', 'resnet50', 'vgg16'] # Naming convention # Key: log name # Value: ([num_gpus], [names]) # num_gpus: Since each log...
6,731
2,803
def foo(x=Non<caret>):
22
12
# This is an automatically generated file. # DO NOT EDIT or your changes may be overwritten import base64 from xdrlib import Packer, Unpacker from ..type_checked import type_checked from .survey_message_command_type import SurveyMessageCommandType from .topology_response_body import TopologyResponseBody __all__ = ["S...
2,687
824
# Generated by Django 3.1.5 on 2021-01-14 22:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('poll', '0001_initial'), ] operations = [ migrations.CreateModel( name='Topic', fields=[ ('id', model...
763
235
class Solution: def longestSubarray(self, nums: List[int]) -> int: k = 1 max_len, i = 0, 0 for j in range(len(nums)): if nums[j] == 0: k -= 1 if k < 0: if nums[i] == 0: k += 1 i += 1 max_...
370
130
# -*- coding: ISO-8859-1 -*- # setup.py: the distutils script # import os import setuptools import sys from distutils import log from distutils.command.build_ext import build_ext from setuptools import Extension # If you need to change anything, it should be enough to change setup.cfg. PACKAGE_NAME = 'pysqlite3' VER...
5,375
1,669
#!/usr/bin/env python import cairo from .utils import hex_to_rgba, parse_unit def parse_size(size): """take a size as str (es: 14px), return its value in px/pt as int """ if hasattr(size, 'isdigit'): if size.isdigit(): return int(size) return parse_unit(size[:-2], size[-2:]) ...
5,267
1,718
ROOT_WK_API_URL = "https://api.wanikani.com/v2/" RESOURCES_WITHOUT_IDS = ["user", "collection", "report"] SUBJECT_ENDPOINT = "subjects" SINGLE_SUBJECT_ENPOINT = r"subjects/\d+" ASSIGNMENT_ENDPOINT = "assignments" REVIEW_STATS_ENDPOINT = "review_statistics" STUDY_MATERIALS_ENDPOINT = "study_materials" REVIEWS_ENDPOINT ...
462
214
from inversefed import consts import torch from torchvision import datasets, transforms class DataLoader: def __init__(self, data, device): self.data = data self.device = device def get_mean_std(self): if self.data == 'cifar10': mean, std = consts.cifar10_mean...
1,943
625
import os import time import pytest import logging from cassandra import ConsistencyLevel from dtest import Tester, create_ks from tools.data import create_c1c2_table, insert_c1c2, query_c1c2 from tools.assertions import assert_stderr_clean since = pytest.mark.since ported_to_in_jvm = pytest.mark.ported_to_in_jvm lo...
10,651
3,483
from collections.abc import Iterable as ABCIterable def call_with_args(func, args): if isinstance(args, dict): return func(**args) elif isinstance(args, ABCIterable): return func(*args) else: return func(args)
248
75
import wikipedia from topicblob import TopicBlob #get random wikipeida summaries wiki_pages = ["Facebook","New York City","Barack Obama","Wikipedia","Topic Modeling","Python (programming language)","Snapchat"] wiki_pages = ["Facebook","New York City","Barack Obama"] texts = [] for page in wiki_pages: text = ...
817
302
from sepal_ui import model from traitlets import Any class DmpModel(model.Model): # inputs event = Any(None).tag(sync=True) username = Any(None).tag(sync=True) password = Any(None).tag(sync=True)
215
74
#!/usr/bin/env python """An environment that takes as input databases of environments and runs episodes, where each episode is a search based planner. It then returns the average number of expansions, and features (if training) Author: Mohak Bhardwaj """ from collections import defaultdict import numpy as np import os...
9,154
2,967
from sanic_jwt import exceptions class User: def __init__(self, id, username, password): self.user_id = id self.username = username self.password = password def __repr__(self): return "User(id='{}')".format(self.user_id) def to_dict(self): return {"user_id": self....
966
297
import unittest from rx.testing import TestScheduler, ReactiveTest class TestDoWhile(ReactiveTest, unittest.TestCase): def test_dowhile_always_false(self): scheduler = TestScheduler() xs = scheduler.create_cold_observable( self.on_next(50, 1), self.on_next(100, 2), ...
5,087
1,866
""" Script testing 14.4.2 control from OWASP ASVS 4.0: 'Verify that all API responses contain a Content-Disposition: attachment; filename="api.json" header (or other appropriate filename for the content type).' The script will raise an alert if 'Content-Disposition' header is present but not follow the format - Cont...
1,459
438
import uvicorn if __name__ == '__main__': <<<<<<< HEAD uvicorn.run('app.main:app', host='0.0.0.0', port=80) ======= uvicorn.run('app.main:app', host='0.0.0.0', port=2323) >>>>>>> c583e3d93c9b7f8e76ce1d676a24740b62ef3552
230
132
MAX_N = 10000 + 1 isprime = [True] * (MAX_N) isprime[0] = False isprime[1] = False for i in range(2, MAX_N): if not isprime[i]: continue for j in range(i+i, MAX_N, i): isprime[j] = False T = int(input()) for _ in range(T): n = int(input()) for i in range(n//2, 1, -1): if isprim...
399
172
# # PySNMP MIB module DOCS-LOADBALANCING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DOCS-LOADBALANCING-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:53:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
48,201
17,049
from permutation_palindrome import is_permutation_palindrome import unittest class TestIsPermutationPalindrome(unittest.TestCase): def test_returns_true_if_possible_palindrome(self): """Returns true if a palindrome is possible with a given permutation of a string""" result = is_permutation_palindr...
671
213
from sagemaker.estimator import Framework from sagemaker.model import FrameworkModel from sagemaker.predictor import RealTimePredictor import subprocess def _run_command(command): return ( subprocess.run(command.split(" "), stdout=subprocess.PIPE,) .stdout.decode("utf-8") .strip() ) ...
3,199
985
# coding=utf-8 def pdf2text(pdf_path,encoding="ASCII7"): import subprocess import os.path pdf_path = os.path.abspath(pdf_path) subprocess.call(["pdftotext","-l","1","-enc",encoding,"-q",pdf_path]) text = os.path.splitext(pdf_path)[0] + ".txt" return text def pick_out_doi(txt): import re ...
835
340
# Copyright 2017 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...
2,313
676
#Author:Li Shen from django import forms from apps.forms import FormMixin class PublicCommentForm(forms.Form,FormMixin): #CharField字长在form可不定义,但是在model模型中必须定义 content=forms.CharField() news_id=forms.IntegerField()
228
87
### Data Preprocessing ## 1. Json to Transcript ## 2. Aligner ## 3. Text Replace from jamo import h2j import json import os, re, tqdm import unicodedata from tqdm import tqdm import hparams as hp name = hp.dataset first_dir = os.getcwd() transcript = name + '_transcript.txt' dict_name = name + '_k...
6,446
2,469
#!/usr/bin/env python3 import requests import os import json CACHET_HOSTNAME = os.environ.get("CACHET_HOSTNAME") URL = f"https://{CACHET_HOSTNAME}/api/v1/components" HEADERS = { 'X-Cachet-Token': os.environ.get("CACHET_TOKEN") } with requests.Session() as session: session.headers.update(HEADERS) respon...
1,435
441
import numpy as np from mpmath import besselj, mpf, pi, sqrt from ..funcs import j1_over_x @np.vectorize def mpmath_jn_over_x(i, x): xx = mpf(x) if x == 0: return float(1 / mpf(3)) else: return float(sqrt(pi / mpf(2) / xx) * besselj(i + mpf("1/2"), xx) / xx) def test_j1_over_x(): x ...
489
237
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- # Copyright (c) 2016 France-IOI, MIT license # # http://opensource.org/licenses/MIT # This tool launches an isolated execution. It is intended as a wrapper around # the execution of any command. import argparse, os, sys DEFAULT_EXECPARAMS = { 'timeLimitMs': 60000...
2,176
737
#!/usr/bin/env python # -*- coding:utf-8 -*- import smtplib from email.mime.text import MIMEText from email.header import Header #发送邮件函数 def smail(sub,body): tolist = ["xx@qq.com", "xx@qq.com"] cc = ["xx@qq.com", "xx@163.com"] sender = '管理员 <worktest2020@163.com>' subject = sub smtpserver = 'smtp.1...
837
351
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) from collections import deque n, m = map(int, readline().split()) s = readline().rstrip().decode()[::-1] index = 0 ans = deque([]) for i in range(n): for j in range(m,...
583
203
"""Unit test to test app.""" import os from unittest import TestCase import mock from src import app class TestApp(TestCase): """Unit test class to test other methods in the app.""" def test_valid_env(self): key = 'ENV_1' os.environ[key] = 'test' app.get_or_raise(key) del os...
1,790
608
#!/usr/bin/python3 import os import sys from http.server import HTTPServer, BaseHTTPRequestHandler class MyHandler(BaseHTTPRequestHandler): def do_GET(self): # do not change paths if self.path == '/apis/apps.openshift.io/v1/namespaces/testNamespace/deploymentconfigs?labelSelector=services.server...
2,224
729
import unittest from unittest import TestCase from e2cnn.nn import * from e2cnn.gspaces import * import random class TestNonLinearitiesFlipRotations(TestCase): def test_dihedral_norm_relu(self): N = 8 g = FlipRot2dOnR2(N) r = FieldType(g, list(g.representations.values()) * ...
11,487
4,250
import unittest from QuattroComponents.Player import Anonymous_player from QuattroComponents.Card import Card from TestModule.GetMethodName import get_method_name_decorator from collections import deque def reset_player_attributes(anonymous: Anonymous_player): anonymous.player1_changed = False anonymous.playe...
5,880
1,724
# coding: utf-8 """ Octopus Server API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 2019.6.7+Branch.tags-2019.6.7.Sha.aa18dc6809953218c66f57eff7d26481d9b23d6a Generated by: https://github.com/swagger-api...
10,012
3,058
import re def str2bool(my_str): """returns a reasonable boolean from a string so that "False" will result in False""" if my_str is None: return False elif isinstance(my_str, str) and my_str.lower() == "false": return False elif isinstance(my_str, str) and my_str.lower() == "off": ...
660
223