id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11522234 | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
VERSION = (0, 1)
backendapp = 'django_wysiwyg'
# Do some settings checks.
if backendapp not in settings.INSTALLED_APPS:
raise ImproperlyConfigured("The '{0}' application is required to use the '{1}' plugin.".format(backendap... |
11522242 | import tensorflow as tf
import unittest
from context import fastISM
from fastISM.models.bpnet import bpnet_model
class TestCustomStopLayer(unittest.TestCase):
# testing introducing stop layers at intermediate nodes (early_stop_layers)
# that are not necessarily in STOP_LAYERS (i.e. not a dense/flatten etc
... |
11522285 | from __future__ import annotations
from rich.console import Console
from typing import ItemsView, KeysView, ValuesView, NamedTuple
from . import log
from .geometry import Region, Size
from .widget import Widget
class RenderRegion(NamedTuple):
region: Region
order: tuple[int, ...]
clip: Region
class ... |
11522323 | from django.apps import AppConfig
class BeatServerConfig(AppConfig):
name = "beatserver"
verbose_name = "Beat Server"
|
11522325 | import paddlehub as hub
love_module = hub.Module(name="ernie_gen_lover_words")
if __name__=='__main__':
test_texts = ['情人节', '故乡', '小编带大家了解一下程序员情人节']
results = love_module.generate(texts=test_texts, beam_width=1)
for result in results:
print(result) |
11522336 | import os
import matplotlib
#Allow headless use
if os.environ.get('DISPLAY') is None:
print("Falling back to Agg engine")
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.colors
import matplotlib.image
import matplotlib.gridspec as gridspec
import matplotlib.dates as mdates
import matplot... |
11522367 | import random
import tempfile
from os.path import exists, join
from arbol import aprint, asection
from tifffile import imread
from dexp.datasets import ZDataset
from dexp.datasets.operations.tiff import dataset_tiff
from dexp.datasets.synthetic_datasets import generate_nuclei_background_data
from dexp.utils.backends ... |
11522376 | import os
import os.path
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
]
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
def make_dataset(path_files):
if path_files.find('.txt') != -1:
... |
11522382 | from .ISAM.ISAM import Indice
from .ISAM.Cilindro import Cilindro, Registro
from .ISAM import BinWriter as bi
import os
import pickle
import shutil
class TabsStruct:
def __init__(self, name, cols, ruta):
# numero de columnas
self.countCol = cols
# nombre de la tabla
self.name = name... |
11522399 | from random import shuffle
def rota(rooms):
result = []
for _ in xrange(0, 7, len(rooms)):
shuffle(rooms)
result.extend(rooms)
return result[:7]
|
11522401 | import torch
import os
import math
from torch.autograd import Variable
import numpy as np
from PIL import Image
from util import util
import numpy as np
def color_map(i):
colors = [
[255,0,0],
[0,255,0],
[0,0,255],
[128,128,0],
[0,128,128]
]
if i < 5:
return... |
11522436 | import unittest
from conans.test.tools import TestClient
from conans.model.ref import ConanFileReference, PackageReference
from conans.paths import CONANFILE, CONANINFO
import os
from conans.model.info import ConanInfo
from conans.test.utils.cpp_test_files import cpp_hello_conan_files
from conans.paths import CONANFILE... |
11522442 | import torch
import numpy as np
from collections import OrderedDict
from copy import deepcopy
from robopose.utils.logging import get_logger
from robopose.lib3d.robopose_ops import loss_refiner_CO_disentangled_reference_point
from robopose.lib3d.transform_ops import add_noise, invert_T, transform_pts
from robopose.li... |
11522447 | import argparse
import numpy as np
from keras.layers import (LSTM, BatchNormalization, Convolution3D, Dense, Dropout, Flatten, Input,
MaxPooling3D, TimeDistributed, ZeroPadding3D)
from keras.models import Model, Sequential
from src.data import import_labels
from src.io_data import get_durati... |
11522460 | import dcase_util
audio_container = dcase_util.containers.AudioContainer().load(
filename=dcase_util.utils.Example.audio_filename()
)
audio_container.filename = None
audio_container.plot_wave() |
11522498 | import os
from torchvision import datasets
from torch.utils.data import Dataset
import numpy as np
import tqdm
from enum import Enum
import PIL.Image
__all__ = ['DatasetType', 'DATASETS', 'CIFAR10Dataset', 'NIHDataset', 'SVHNDataset']
class CIFAR10Dataset(Dataset):
def __init__(self, root, split, transform=None,... |
11522525 | from rest_framework.generics import ListAPIView
from search.views.paper import PaperDocumentView
from search.views.post import PostDocumentView
from search.views.person import PersonDocumentView
from search.views.hub import HubDocumentView
from utils.permissions import ReadOnly
from rest_framework.response import Respo... |
11522539 | import logging
import numpy as np
import re
import time
from copy import deepcopy
from os import getenv
import ner_model
import sentry_sdk
from flask import Flask, jsonify, request
from nltk.tokenize import word_tokenize
sentry_sdk.init(getenv("SENTRY_DSN"))
logging.basicConfig(format="%(asctime)s - %(name)s - %(lev... |
11522554 | import json
import os
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pickle
font = {'size' : 25}
matplotlib.rc('font', **font)
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
colors = [[0, 0.447, 0.7410], [0.85, 0.325, 0.098], [0.466, ... |
11522559 | import argparse
import sys
import yaml
from six import StringIO
from django.utils.text import camel_case_to_spaces
from lepo.router import Router
HANDLER_TEMPLATE = '''
def {func_name}(request, {parameters}):
raise NotImplementedError('Handler {operation_id} not implemented')
'''.strip()
def generate_handler_s... |
11522570 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.water_heaters_and_thermal_storage import WaterHeaterHeatPumpPumpedCondenser
log = logging.getLogger(__name__)
class TestWaterHeaterHeatPumpPumpedCondenser(unittest.TestCase):
... |
11522577 | from .seq2seq import Seq2SeqModel
from .nary_tree2seq import NaryTree2SeqModel
from .mm2seq import MM2SeqModel
from .code2seq import Code2Seq
from .hi_transformer_summarization import HiTransformerSummarizationModel
from .transformer import TransformerModel
# from .transformer_summarization_ft import TransformerFtModel... |
11522585 | import math
import time
import docker
from flask import jsonify, current_app
from flask_socketio import emit
from app import socket_io
from app.libs.certification import get_certification, cert_file_path
from app.libs.error_code import Success, StopFail, StartFail, RemoveFail
from app.validators.client_forms import L... |
11522607 | from tir.technologies.webapp_internal import WebappInternal
from tir.technologies.apw_internal import ApwInternal
from tir.technologies.core.config import ConfigLoader
from tir.technologies.core.base_database import BaseDatabase
"""
This file must contain the definition of all User Classes.
These classes will contain ... |
11522631 | from spacy.symbols import IS_PUNCT
import re
import string
from spacy.tokenizer import Tokenizer
from spacy.util import compile_prefix_regex, compile_infix_regex, compile_suffix_regex
def create_medspacy_tokenizer(nlp):
"""Generates a custom tokenizer to augment the default spacy tokenizer
for situatio... |
11522647 | import os
import sys
import torch
from ncc import LOGGER
from ncc import tasks
from ncc.utils import checkpoint_utils
from ncc.utils import utils
from ncc.utils.file_ops.yaml_io import load_yaml
from ncc.utils.logging import progress_bar
def main(args):
return _main(args, sys.stdout)
def _main(args, output_fi... |
11522770 | import numpy as np
import subprocess
import os
import uuid
import cloudpickle
import multiprocessing
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
LINE_WIDTH = 0.25
SIAY = 60 * 60 * 24 * 365.25
USE_N_CORES = 30
# Read Ben's data for Cascadia
pts, _tris, t, slip_all, state_all = np.lo... |
11522771 | from __future__ import annotations
import ast
from functools import partial
from flake8_pie.base import Error
from flake8_pie.utils import is_if_test_func_call
def pie788_no_bool_condition(node: ast.If | ast.IfExp, errors: list[Error]) -> None:
if is_if_test_func_call(node=node, func_name="bool"):
error... |
11522813 | l=int(input('Enter size of the array: '))
a=[]
print("Enter",l,"elements")
for i in range(l):
a.append(int(input()))
x=[]
i=0
n=1
while(i<=l and n<l+1):
if sum(a[i:i+n])==0:
x.append(a[i:i+n])
i+=1
if(i+n==l+1):
n+=1
i=0
print("Output:",len(x)) |
11522880 | import pytest
import lemoncheesecake.api as lcc
def test_log_invalid_argument():
with pytest.raises(TypeError, match="got int"):
lcc.log_debug(1)
with pytest.raises(TypeError, match="got int"):
lcc.log_info(1)
with pytest.raises(TypeError, match="got int"):
lcc.log_warning(1)
... |
11522897 | import os
import warnings
from typing import Optional, Union
import cv2
import imageio
import numpy as np
import torch
from ..geometry.geometryutils import relative_transformation
from torch.utils import data
from . import datautils
__all__ = ["ICL"]
class ICL(data.Dataset):
r"""A torch Dataset for loading in ... |
11522920 | import json
import requests
from fabric.colors import red
def publish_deploy_event(name, component, environment):
url = environment.fab_settings_config.deploy_event_url
if not url:
return
token = environment.get_secret("deploy_event_token")
if not token:
print(red(f"skipping {name} ev... |
11522951 | import kitten
def test_chunks():
assert list(kitten.chunks([1, 2, 3, 4, 5, 6, 7, 8], 3)) == [
[1, 2, 3],
[4, 5, 6],
[7, 8],
]
|
11522957 | import pytest
import ptf.testutils as testutils
import logging
import pprint
from tests.common.fixtures.ptfhost_utils import change_mac_addresses # lgtm[py/unused-import]
from tests.common.dualtor.mux_simulator_control import toggle_all_simulator_ports_to_rand_selected_tor_m # lgtm[py/unused-import]
from tests... |
11522966 | from PyResis import propulsion_power
from D3HRE.simulation import Task, Reactive_simulation
from D3HRE.core.mission_utility import Mission
from D3HRE.core.file_reading_utility import read_route_from_gpx
from D3HRE.optimization import Constraint_mixed_objective_optimisation
from D3HRE.core.battery_models import Battery_... |
11522990 | from copy import deepcopy
from globals import *
import zones as zns
import life as lfe
import render_los
import bad_numbers
import zones
import alife
import numpy
import tiles
import maps
import logging
import time
import sys
def astar(life, start, end, zones, chunk_mode=False, terraform=None, avoid_tiles=[], avoi... |
11522994 | import os
from os.path import dirname, join, realpath
import pytest
import vcr
from pygitguardian import GGClient
base_uri = os.environ.get("TEST_LIVE_SERVER_URL", "https://api.gitguardian.com")
my_vcr = vcr.VCR(
cassette_library_dir=join(dirname(realpath(__file__)), "cassettes"),
path_transformer=vcr.VCR.... |
11523002 | from handler.base_plugin import CommandPlugin
from utils import parse_user_id
from utils import plural_form
import asyncio, re
# Requirements:
# ChatMetaPlugin
# StoragePlugin
class VoterPlugin(CommandPlugin):
__slots__ = ("command_groups", "votes")
def __init__(self, vote_commands=None, vote_undo_commands... |
11523023 | from datetime import datetime, timedelta
import pytest
import eventlet
from detox.proc import Resources
class TestResources:
def test_getresources(self):
x = []
class Provider:
def provide_abc(self):
x.append(1)
return 42
resources = Resource... |
11523025 | from fastapi import APIRouter, Request
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
import json
from pydantic import BaseModel
import s3fs
from typing import Optional, TypedDict, List
router = APIRouter()
s3 = s3fs.S3FileSystem(anon=False, client_kwargs={"region_name": "us-e... |
11523079 | import networkx as nx
import numpy.testing as npt
from GraphRicciCurvature.OllivierRicci import OllivierRicci
def test_compute_ricci_curvature_edges():
G = nx.karate_club_graph()
orc = OllivierRicci(G, method="OTD", alpha=0.5)
output = orc.compute_ricci_curvature_edges([(0, 1)])
npt.assert_almost_eq... |
11523085 | import rospy
from simulation_brain_link.msg import MissionMode
from simulation_evaluation.msg import Referee as RefereeMsg
from simulation_groundtruth.msg import GroundtruthStatus
from std_msgs.msg import String as StringMsg
from simulation.utils.ros_base.node_base import NodeBase
class DriveTestNode(NodeBase):
... |
11523093 | from doajtest.fixtures import ArticleFixtureFactory
from portality.bll import exceptions
from portality.models import Article
from portality.bll.exceptions import ArticleMergeConflict
from datetime import datetime
class BLLArticleMockFactory(object):
@classmethod
def merge_mock(cls, article):
pass
... |
11523122 | from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as base_auth_views
from django.conf import settings
from django.conf.urls.static import static
from django.urls import reverse_lazy
from django.views.generic import RedirectView
urlpatterns = [
# Admin ... |
11523126 | import pytest
from lucid.misc.io.scoping import io_scope, scope_url
def test_empty_io_scope():
path = "./some/file.ext"
scoped = scope_url(path)
assert scoped == path
|
11523240 | from instructions import to_stack_registers
from opcodes import INTERNAL_CALL_OPCODE
from expressionblock import ExpressionBlock
import os
def get_prefix(depth):
return " " * depth
class ExternalFunction(object):
def __init__(self, signature, graph, tracker, entry_exit):
self.signature = signature
self.grap... |
11523256 | from __future__ import absolute_import
from __future__ import print_function
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.utils ... |
11523283 | import pdb
import h5py
import torch
import numpy as np
from base.base_data_loader import BaseDataLoader
class DataLoaderSimple(BaseDataLoader):
"""
Simple DataLoader without expert rewards or trajectories.
"""
def __init__(self, opts):
super(DataLoaderSimple, self).__init__(opts)
# Da... |
11523331 | import logging
import traci
import random
class Platoon():
def __init__(self, startingVehicles):
"""Create a platoon, setting default values for all variables"""
logging.info("Creating a new platoon with: %s", startingVehicles)
self._vehicles = list(startingVehicles)
self._active ... |
11523340 | from visual_mpc.video_prediction.setup_predictor import setup_predictor
from visual_mpc.video_prediction.vpred_model_interface import VPred_Model_Interface
from video_prediction.models.indep_multi_savp_model import IndepMultiSAVPVideoPredictionModel
import video_prediction
base_dir = video_prediction.__file__
base_di... |
11523370 | from aimi import app
import sys
if __name__ == '__main__':
if sys.argv[-1] == "-t":
app.run(True)
else:
app.run(False)
|
11523381 | from basehandler import BaseHandler
from oracle.oracle_db import KeyValue
import json
import logging
import time
from shared.liburl_wrapper import safe_pushtx
TURN_LENGTH_TIME = 60 * 1
class TransactionVerificationError(Exception):
pass
class TransactionSigner(BaseHandler):
def __init__(self, oracle):
sel... |
11523384 | import re
import unittest
from python_aternos import atjsparse
class TestJs2Py(unittest.TestCase):
def setUp(self) -> None:
self.tests = []
with open('token.txt', 'rt') as f:
lines = re.split(r'[\r\n]', f.read())
del lines[len(lines)-1] # Remove empty string
self.tests = lines
self.results = [
... |
11523478 | from records_mover.records.records_format import DelimitedRecordsFormat
import unittest
import json
class TestDelimitedRecordsFormat(unittest.TestCase):
def test_dumb(self):
records_format = DelimitedRecordsFormat(variant='dumb')
# Should match up with
# https://github.com/bluelabsio/recor... |
11523513 | package = "s3cmd"
version = "1.0.1"
url = "http://s3tools.org"
license = "GPL version 2"
short_description = "Command line tool for managing Amazon S3 and CloudFront services"
long_description = """
S3cmd lets you copy files from/to Amazon S3
(Simple Storage Service) using a simple to use
command line client. Supports... |
11523551 | from featuretools.primitives import AggregationPrimitive
from featuretools.variable_types import Numeric
from tsfresh.feature_extraction.feature_calculators import \
absolute_sum_of_changes
class AbsoluteSumOfChanges(AggregationPrimitive):
"""Returns the sum over the absolute value
of consecutive changes ... |
11523554 | import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import numpy as np
### Classification ###
def make_meshgrid(x, y, h=.02):
"""Create a mesh of points to plot in
Parameters
----------
x: data to base x-axis meshgrid on
y: data to base y-axis meshgrid on
h: stepsize for mesh... |
11523572 | from collections import OrderedDict
import torch
import torch.nn as nn
import numpy as np
from typing import Dict, List
def intable(value):
try:
int(value)
return True
except:
return False
def create_slice(index, dim):
slice_list = []
for i in range(0, dim):
slice_l... |
11523600 | from panda3d.core import *
from direct.showbase.DirectObject import DirectObject
from direct.interval.MetaInterval import Sequence, Parallel
from direct.interval.LerpInterval import LerpHprInterval, LerpPosInterval
from direct.interval.FunctionInterval import Func
__all__ = ['CameraControler']
class CameraControler (... |
11523646 | import base64
import io
import logging
import os
from heapq import nsmallest
import numpy as np
from PIL import Image
from dotenv import load_dotenv
from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing import image
from objdic... |
11523677 | import efel
import numpy as np
import math
import matplotlib.pyplot as plt
stim_start = 100#ms
stim_end = 400#ms
decay_start_after_stim =1
decay_end_after_stim = 10
#feature_list = ['Spikecount','time_to_first_spike', 'min_AHP_indices','peak_voltage','mean_AP_amplitude', 'AHP_depth','AP_begin_indices', 'spike_half_widt... |
11523701 | import json
from unittest.mock import ANY
from purpleserver.graph.tests.base import GraphTestCase
class TestSystemConnections(GraphTestCase):
def test_query_system_connections(self):
response = self.query(
"""
query get_system_connections {
system_connections {
... |
11523804 | if __name__ == "__main__":
## setup the Django with public settings for using the database
from main.tools import set_up
set_up.set_up_django_environment('main.tools.settings_for_script')
from law.models import Document
# prints the relative number of laws that have no text
import datetime
... |
11523959 | import gfapy
class Validator:
@staticmethod
def _validate_gfa_field(obj, datatype, fieldname = None):
"""Validate the content of a field of a Line instance.
Parameters:
obj: the value to be validated. It can be either a string (in which case
the encoded validation method is used) or any oth... |
11523963 | import pickle
import os
import random
import heapq
import operator
import hashlib
try:
import ujson as json
except:
import json
from copy import copy
from functools import partial
from collections import defaultdict, OrderedDict
from aser.eventuality import Eventuality
from aser.relation import Re... |
11524016 | from hyperparameter_hunter import Environment, CVExperiment
from hyperparameter_hunter.callbacks.bases import lambda_callback
from hyperparameter_hunter.utils.learning_utils import get_toy_classification_data
from hyperparameter_hunter.callbacks.recipes import confusion_matrix_oof
from sklearn.model_selection import Re... |
11524018 | import tomsup as ts
def test_tutorial():
# Get the competitive penny game payoff matrix
penny = ts.PayoffMatrix("penny_competitive")
tom_1 = ts.TOM(level=1)
init_states = tom_1.get_internal_states()
init_states["own_states"]["p_k"] = [0.3, 0.7]
tom_1.set_internal_states(init_states)
... |
11524037 | import pytest
from eth_tester.exceptions import TransactionFailed
from plasma_core.constants import NULL_ADDRESS, NULL_ADDRESS_HEX
from tests_utils.constants import PAYMENT_TX_MAX_INPUT_SIZE
ETH_ADDRESS_HEX = NULL_ADDRESS_HEX
@pytest.mark.parametrize("num_inputs", range(1, PAYMENT_TX_MAX_INPUT_SIZE))
def test_start_... |
11524045 | from btchip.btchip import getDongle # noqa
from binance_chain.ledger.client import LedgerApp # noqa
from binance_chain.ledger.wallet import LedgerWallet # noqa
|
11524051 | from haystack.file_converter.base import FileTypeClassifier
from haystack.file_converter.docx import DocxToTextConverter
from haystack.file_converter.markdown import MarkdownConverter
from haystack.file_converter.pdf import PDFToTextConverter
from haystack.file_converter.tika import TikaConverter
from haystack.file_con... |
11524055 | from __future__ import with_statement
import numpy
from .._common import to_output
__all__ = [
"read",
"write",
]
header_to_unit = {
"ELEM": "",
"X": "(M)",
"Y": "(M)",
"Z": "(M)",
"PRES": "(PA)",
"P": "(PA)",
"TEMP": "(DEC-C)",
"T": "(DEC-C)",
"PCAP_GL": "(PA)",
"PCA... |
11524069 | class Context:
def iter_roots(self):
c = self
while c:
if isinstance(c, ContextRoot):
yield c
c = c.get_context_parent()
def get_context_parent(self):
raise NotImplementedError
def get_context(self):
for r in self.iter_roots():
... |
11524079 | import unittest
from unittest.mock import MagicMock
from sanic_prometheus.endpoint import fn_by_type, get_from_url
def mk_request(url):
req = MagicMock()
req.path = url
return req
def az_url():
return "/".join('abcdefghijklmnopqrstuvwxyz')
class TestUrlEndpoint(unittest.TestCase):
def test_jus... |
11524082 | import torch
import numpy as np
import copy
import shelve
import collections
from collections import OrderedDict
import matplotlib as mpl
import matplotlib.pyplot as plt
import random
import math
import os
import enum
import yaml
from termcolor import colored
from . import Distribution
from .. import util
class Empi... |
11524102 | import os
import numpy as np
import cv2
import math
def DCmakedir(path):
if os.path.exists(path):
return
else:
os.mkdir(path)
def imageRotate(img,theta):
rows,cols = img.shape[0:2]
angle = -theta*math.pi/180
a = math.sin(angle)
b = math.cos(angle)
width = int(cols * math.fa... |
11524105 | import unittest
from rastervision.pipeline.utils import split_into_groups
class TestUtils(unittest.TestCase):
def test_split_into_groups(self):
lst = [1, 2, 3, 4, 5, 6]
g1 = split_into_groups(lst[:5], 3)
self.assertEqual(g1, [[1, 2], [3, 4], [5]])
g2 = split_into_groups(lst, 7)
... |
11524112 | from flask import g, request, jsonify
from flask_restx import Resource, fields
from pyinfraboxutils.ibflask import OK
from pyinfraboxutils.ibrestplus import api
cluster_setting_model = api.model('ClusterSetting', {
'name': fields.String(required=True),
'enabled': fields.Boolean(required=True),
})
@api.route... |
11524114 | from collections import namedtuple
import enum
import unicodedata
class Align(enum.Enum):
LEFT = 0
CENTER = 1
RIGHT = 2
# from https://bugs.python.org/msg145523
W = {
'F': 2, # full-width, width 2, compatibility character for a narrow char
'H': 1, # half-width, width 1, compatibility character for a nar... |
11524198 | import torch.nn as nn
from torch.nn import init
class c3d(nn.Module):
def __init__(self,num_class,init_weights=True):
super(c3d, self).__init__()
self.conv1a = nn.Conv3d(3, 64, kernel_size=3, padding=1)
self.conv2a = nn.Conv3d(64, 128, kernel_size=3, padding=1)
self.conv3a = nn.Conv... |
11524201 | import random
def tamper(payload, **kwargs):
possible_spaces = [2, 3, 4]
retval = ""
encoder = "/**/"
for char in retval:
if char == " ":
retval += encoder * random.choice(possible_spaces)
else:
retval += char
return retval |
11524210 | from unittest import TestCase
from excel4lib.macro import *
from excel4lib.lang import *
class TestExcel4Instruction(TestCase):
def test_excel4instruction_str(self):
formula = Excel4Formula(1, 2, "test", "test", 1, 2, 3)
self.assertEqual(str(formula), '=test("test",1,2,3)', 'Should be =test("test"... |
11524276 | from collections import defaultdict
def repeat_sum(lst):
count = defaultdict(int)
for a in lst:
for b in set(a):
count[b] += 1
return sum(k for k, v in count.iteritems() if v > 1)
|
11524297 | import os
import random
import time
import pytest
from ufo2ft.fontInfoData import (
dateStringToTimeValue,
getAttrWithFallback,
normalizeStringForPostscript,
)
@pytest.fixture
def info(InfoClass):
self = InfoClass()
self.familyName = "Family Name"
self.styleName = "Style Name"
self.units... |
11524316 | import threading
import time
import typing
import uuid
from cauldron import environ
from cauldron.environ.response import Response
from cauldron.cli.sync import comm
def send_remote_command(
command: str,
raw_args: str = '',
asynchronous: bool = True,
remote_connection: 'environ.Remot... |
11524380 | import numpy as np
# We lazy-load torch the first time one of the functions that requires it is called
torch = None
def _check_torch_import():
global torch
if torch is not None:
return
import importlib
torch = importlib.import_module('torch')
def tonp(tensor):
"""Takes any PyTorch tensor ... |
11524415 | from django.http import HttpResponse
from django.core.serializers import serialize
from .models import Point, Voivodeship
from django.views.generic import TemplateView
from django.core.cache import cache
def points_view(request):
points_as_geojson = serialize('geojson', Point.objects.all())
return HttpRespons... |
11524424 | from .circle import Circle
from .circlemarker import CircleMarker
from .polygon import Polygon
from .polyline import Polyline
from .rectangle import Rectangle
|
11524434 | from unittest import TestCase
from unittest.mock import MagicMock, patch
from signalflowgrapher.model.model import Model
from signalflowgrapher.commands.command_handler import CommandHandler
from signalflowgrapher.controllers.main_controller import MainController
from signalflowgrapher.commands.create_node_command impo... |
11524439 | from openprocurement.tender.core.procedure.views.award_document import BaseAwardDocumentResource
from openprocurement.tender.core.procedure.models.document import PostDocument, PatchDocument, Document
from openprocurement.tender.core.procedure.validation import (
validate_input_data,
validate_patch_data,
va... |
11524446 | from itertools import chain
import re
WORDS_TO_ROLLUP = {
'rollup-': 0,
'rollup': 1,
'rollup=maybe': 0,
'rollup=never': -2,
'rollup=iffy': -1,
'rollup=always': 1,
}
class IssueCommentCommand:
"""
A command that has been parsed out of a GitHub issue comment.
E.g., `@bors r+` => an... |
11524461 | import gym
from gym_extensions.continuous import mujoco
from gym.wrappers import Monitor
# available env list: https://github.com/Rowing0914/gym-extensions/blob/mujoco200/tests/all_tests.py
HalfCheetah_Env_list = [
"HalfCheetahGravityHalf-v1",
"HalfCheetahGravityThreeQuarters-v1",
"HalfCheetahGravityOneAnd... |
11524469 | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
h = {}
for c in s:
if c not in h:
h[c] = 0
h[c] += 1
for c in t:
if c not in h:
h[c] = 0
h[c] -= 1
for k in h:
if h[k] != 0:
... |
11524474 | import collections
import logging
logger = logging.getLogger(__name__)
VERY_EARLY = -100
EARLY = -50
NORMAL = 0
LATE = 50
VERY_LATE = 100
Handler = collections.namedtuple("Handler", "handler priority")
class ServiceLocator:
def __init__(self):
self.providers = collections.defaultdict(lambda: [])
d... |
11524527 | from __future__ import unicode_literals
from django.conf.urls import include, url
from braces.views import FormMessagesMixin
from envelope.views import ContactView
class MessagesContactView(FormMessagesMixin, ContactView):
form_invalid_message = "There was en error in the contact form."
form_valid_message ... |
11524529 | from genedom import BarcodesCollection
barcodes_collection = BarcodesCollection.from_specs(
n_barcodes=96, barcode_length=20, spacer='AA',
forbidden_enzymes=('BsaI', 'BsmBI', 'BbsI'),
barcode_tmin=55, barcode_tmax=70,
other_primer_sequences=(), heterodim_tmax=5,
max_homology_length=10, include_spac... |
11524549 | from os import path
from setuptools import setup
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), "r") as fh:
long_description = fh.read()
setup(name='google-search-results-serpwow',
version='1.1.11',
description='PIP package to scrape and parse Google, Bing, Yahoo,... |
11524582 | from spinup.utils.run_utils import ExperimentGrid
from spinup import ppo_pytorch
import torch
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--cpu', type=int, default=4)
parser.add_argument('--num_runs', type=int, default=3)
args = parser.parse_ar... |
11524592 | class Digitizing:
def dig(self, node1="", node2="", ninc="", **kwargs):
"""Digitizes nodes to a surface.
APDL Command: DIG
Parameters
----------
node1, node2, ninc
Digitize nodes NODE1 through NODE2 in steps of NINC. NODE2
defaults to NODE1 and NINC... |
11524595 | import os
import typing
from argparse import ArgumentParser
from cauldron import cli
from cauldron import environ
from cauldron.cli.commands.create import actions as create_actions
from cauldron.cli.commands.open import opener as project_opener
from cauldron.cli.commands.open import remote as remote_project_opener
fro... |
11524619 | from aws_cdk import (
aws_lambda as _lambda,
aws_apigatewayv2 as api_gw,
aws_apigatewayv2_integrations as integrations,
aws_ec2 as ec2,
aws_rds as rds,
aws_secretsmanager as secrets,
aws_ssm as ssm,
core
)
class TheRdsProxyStack(core.Stack):
def __init__(self, scope: core.Construc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.