id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
90755 | from methods import load_json, save_json, chunks
from collections import Counter
from math import ceil
# External libs:
from tabulate import tabulate
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
import seaborn as sns
sns.set_style("white")
sns.set_context('paper', font_scale=7)
my_palette ... |
90762 | from setuptools import setup
setup(
name="memrepl",
version="1.0",
url="https://github.com/agustingianni/memrepl",
author="<NAME>",
author_email="<EMAIL>",
description=("Memory inspection REPL interface"),
license="MIT",
keywords="memory debugger repl reverse engineering",
py_module... |
90803 | from rpython.rlib import jit
from rpython.rlib.cache import Cache
from rpython.rlib.objectmodel import specialize, import_from_mixin
from rsqueakvm.util.version import Version
class QuasiConstantCache(Cache):
def _build(self, obj):
class NewQuasiConst(object):
import_from_mixin(QuasiConstantM... |
90830 | from maneuvers.maneuver import Maneuver
from rlutilities.linear_algebra import norm
from rlutilities.simulation import Car
FIRST_JUMP_DURATION = 0.1
BETWEEN_JUMPS_DELAY = 0.1
SECOND_JUMP_DURATION = 0.05
TIMEOUT = 2.0
class SpeedFlip(Maneuver):
def __init__(self, car: Car, right_handed=True, use_boost=... |
90843 | from __future__ import print_function
import numpy as np
np.set_printoptions(threshold='nan')
import h5py
import theano
import argparse
import itertools
import subprocess
import logging
import time
import codecs
import os
from copy import deepcopy
import math
import sys
from data_generator import VisualWordDataGener... |
90869 | from copy import deepcopy
from typing import List
from rdkit import Chem
from icolos.core.step_utils.obabel_structconvert import OBabelStructConvert
from icolos.utils.enums.compound_enums import (
CompoundContainerEnum,
EnumerationContainerEnum,
)
from icolos.utils.enums.program_parameters import SchrodingerEx... |
90878 | from typing import Optional, Dict, Union
import falcon
from falcon_multipart.middleware import MultipartMiddleware
from webtest.http import StopableWSGIServer
from py_fake_server.route import Route
from py_fake_server.endpoint import Endpoint
from py_fake_server.statistic import Statistic
class FakeServer(falcon.AP... |
90884 | import typing
from PyQt5.QtChart import QValueAxis, QChart, QBarSeries, QBarSet
from ParadoxTrading.Chart.SeriesAbstract import SeriesAbstract
class BarSeries(SeriesAbstract):
def __init__(
self, _name: str,
_x_list: typing.Sequence,
_y_list: typing.Sequence,
_col... |
90957 | from django.conf import settings
# Map of mode -> processor config
# {
# 'js': {
# 'processor': 'damn.processors.ScriptProcessor',
# 'aliases': {},
# },
# }
PROCESSORS = getattr(settings, "DAMN_PROCESSORS", {})
# File extension -> mode name
MODE_MAP = getattr(settings, "DAMN_MODE_M... |
90977 | def get_user_id(user_or_id):
if type(user_or_id) is str or type(user_or_id) is int:
return str(user_or_id)
elif hasattr(user_or_id, '__getitem__') and 'user_id' in user_or_id:
return str(user_or_id['user_id'])
elif hasattr(user_or_id, 'user_id'):
return str(user_or_id.user_id)
re... |
90979 | import config
import models.base
from models.task import TaskLock
def main():
app = config.App(config)
with app.app_context():
for lock in models.base.db.session.query(TaskLock).all():
if lock.step is not None:
lock.step.complete('Force release lock')
models.bas... |
90983 | from hypothesis import given, example, note
import hypothesis.strategies as st
import hypothesis
import strategies
import warnings
import base64
import json
import six
import blackboxprotobuf
warnings.filterwarnings(
"ignore",
"Call to deprecated create function.*",
)
try:
import Test_pb2
except:
im... |
90987 | import sys
import open3d
import numpy as np
import time
import os
from geometric_registration.utils import get_pcd, get_keypts, get_desc, loadlog
import cv2
from functools import partial
def build_correspondence(source_desc, target_desc):
"""
Find the mutually closest point pairs in feature space.
source ... |
91019 | import multiprocessing
from fastai.dataset import *
from fasterai.files import *
from pathlib import Path
from itertools import repeat
from PIL import Image
from numpy import ndarray
from datetime import datetime
def generate_image_preprocess_path(source_path: Path, is_x:bool, uid: str):
name = generate_image_prep... |
91061 | from discord.ext import commands
from .utils import utils
import datetime
import asyncio
import discord
import logging
log = logging.getLogger(__name__)
def check_roles(ctx):
if ctx.message.author.id == 1<PASSWORD>:
return True
return utils.check_roles(ctx, "Mod", "admin_roles")
def has_mute_role(ctx... |
91075 | NUM_VERSION = (0, 1)
VERSION = ".".join(str(nv) for nv in NUM_VERSION)
__version__ = VERSION
try:
from .encbup import (
File,
Key,
Reader,
Writer,
main,
)
except ImportError:
# Ignore if dependencies haven't been satisfied yet (when setting up).
pass
|
91079 | import torch
from torch import nn
class BaseAligner(nn.Module):
def __init__(self, add_identity = True, add_bias = True):
super(BaseAligner, self).__init__()
self.n_parameters = None
self.add_bias = add_bias
self.add_identity = add_identity
if self.add_bias:
... |
91080 | import sys
import os
import numpy as np
import cv2
from PIL import Image, ImageDraw, ImageFont
import acl
path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(path, ".."))
sys.path.append(os.path.join(path, "../../../../common/"))
from acllite_resource import AclLiteResource
from acllite_mod... |
91085 | import json
import multiprocessing
from multiprocessing import Process
import os
import random
import time
import traceback
import zmq
import zmq.decorators as zmqd
from aser.database.kg_connection import ASERKGConnection
from aser.server.utils import *
from aser.extract.aser_extractor import SeedRuleASERExtractor
from... |
91139 | import zmq
import sys
import threading
import time
from random import randint, random
def tprint(msg):
"""like print, but won't get newlines confused with multiple threads"""
sys.stdout.write(msg + '\n')
sys.stdout.flush()
class ServerTask(threading.Thread):
"""ServerTask"""
def __init__(self):
... |
91146 | import pytest
from django.conf import settings
from requests import put
from grandchallenge.uploads.models import UserUpload
from tests.algorithms_tests.factories import AlgorithmImageFactory
from tests.factories import UserFactory
from tests.verification_tests.factories import VerificationFactory
@pytest.mark.djang... |
91166 | from vms.models import BackupDefine
from api.decorators import api_view, request_data, setting_required
from api.permissions import IsAdminOrReadOnly
from api.utils.db import get_object
from api.vm.utils import get_vm, get_vms
from api.vm.snapshot.utils import get_disk_id, filter_disk_id
from api.vm.backup.utils impor... |
91187 | import numpy as np
import pandas as pd
from pathlib import Path
from typing import Dict, List, Union
from collections import OrderedDict
from pathos.multiprocessing import ThreadPool as Pool
from tqdm import tqdm
from src.utils import remap_label, get_type_instances
from .metrics import PQ, AJI, AJI_plus, DICE2, split... |
91202 | import sys
import contextlib
@contextlib.contextmanager
def stdout_redirect(stringIO):
sys.stdout = stringIO
try:
yield stringIO
finally:
sys.stdout = sys.__stdout__
stringIO.seek(0)
|
91205 | from abc import ABC, abstractmethod
from typing import AnyStr, List, Dict, Optional, Union
from functools import partial
class AdvancedFeaturizer(ABC):
pass
class SimpleFeaturizer(ABC):
id = None
parameters = []
# def __init__(self, files: Union[str, List[str]], series: Union[str, List[str], None]):... |
91244 | import socket
import struct
from threading import Thread
from python_qt_binding.QtCore import QMutex, QMutexLocker, QTimer
from qt_gui.plugin import Plugin
from pymavlink.mavutil import mavlink_connection
from pymavlink.dialects.v10.ardupilotmega \
import MAVLink_global_position_int_message
from pymavlink.dialect... |
91261 | import string
import random
def gen_rand_filename():
name = ""
for i in range(1, 10):
name += random.choice(list(string.ascii_uppercase + string.ascii_lowercase))
return name
def get_size(filename):
with open(filename, "rb") as file:
length = len(file.read())
return length
def... |
91264 | description = 'Actuators and feedback of the shutter, detector, and valves'
group = 'lowlevel'
excludes = ['IOcard']
devices = dict(
I1_pnCCD_Active = device('nicos.devices.generic.ManualSwitch',
description = 'high: Detector is turned on',
states = [0, 1],
),
I2_Shutter_safe = device('ni... |
91279 | from unittest import TestCase
from mock import patch, Mock
from torch import nn
from torchbearer.callbacks.manifold_mixup import ManifoldMixup
import torchbearer
import torch
class TestModule(nn.Module):
def __init__(self):
super(TestModule, self).__init__()
self.conv = nn.Conv1d(1, 1, 1)
... |
91282 | from wagtail.admin.edit_handlers import FieldPanel
from wagtail.contrib.modeladmin.views import CreateView, EditView
from .models import InvestmentCategorySettings
class CreateInvestmentView(CreateView):
def get_form_kwargs(self):
kwargs = super(CreateInvestmentView, self).get_form_kwargs()
kwarg... |
91299 | import onmt
import numpy as np
import argparse
import torch
import codecs
import json
import sys
import csv
parser = argparse.ArgumentParser(description='preprocess.py')
##
## **Preprocess Options**
##
parser.add_argument('-config', help="Read options from this file")
parser.add_argument('-train_src', required=T... |
91306 | import argparse
from collections import Counter, OrderedDict
from prenlp.tokenizer import *
TOKENIZER = {'nltk_moses': NLTKMosesTokenizer(),
'mecab' : Mecab()}
class Vocab:
"""Defines a vocabulary object that will be used to numericalize text.
Args:
vocab_size (int) : the max... |
91359 | import pytest
from rest_framework import serializers
from .models import Album, Track
from drf_jsonschema import to_jsonschema
from jsonschema import validate
@pytest.mark.django_db
def test_string_related_field():
album = Album.objects.create(
album_name="Collected Stories", artist="<NAME>")
track1 =... |
91367 | from ..exceptions import RedisError
from ..utils import b
from ..utils import nativestr
def parse_georadius_generic(response, **options):
if options['store'] or options['store_dist']:
# `store` and `store_diff` cant be combined
# with other command arguments.
return response
if not is... |
91390 | from datetime import datetime
from airflow import DAG
from airflow.operators.valohai import ValohaiSubmitExecutionOperator, ValohaiDownloadExecutionOutputsOperator
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2018, 1, 1),
'email': ['<EMAIL>'],
'email_on_fai... |
91395 | import argparse
import torch
def load_model(model_path):
try:
ckpt = torch.load(model_path)
except RuntimeError:
ckpt = torch.load(model_path, map_location="cpu")
if "model" in ckpt.keys():
return ckpt["model"]
return ckpt
def parse_args():
parser = argparse.ArgumentPar... |
91401 | import traceback
import pymel.core as pm
import mgear
from mgear.vendor.Qt import QtCore
from mgear.core.anim_utils import *
# =============================================================================
# constants
# =============================================================================
SYNOPTIC_WIDGET_... |
91404 | import torch.nn as nn
import torch.nn.functional as F
class PadLayer(nn.Module):
# E.g., (-1, 0) means this layer should crop the first and last rows of the feature map. And (0, -1) crops the first and last columns
def __init__(self, pad):
super(PadLayer, self).__init__()
self.pad = pad
... |
91409 | import socket
from sockets.broadcast_socket import BroadcastSocket
import logger
log = logger.getLogger(__name__)
class BroadcastDiscoverer(BroadcastSocket):
def __init__(self, port):
super(BroadcastDiscoverer, self).__init__()
self.socket.bind(('0.0.0.0', port))
def __del__(self):
"... |
91416 | answer1 = widget_inputs["radio1"]
answer2 = widget_inputs["radio2"]
answer3 = widget_inputs["radio3"]
answer4 = widget_inputs["radio4"]
is_correct = False
comments = []
def commentizer(new):
if new not in comments:
comments.append(new)
if answer2 == True:
is_correct = True
else:
is_correct = is_c... |
91417 | import logging
from typing import Any, List
from absl import flags
from injector import Module, inject, singleton
from rep0st.framework import app
from rep0st.framework.scheduler import Scheduler
from rep0st.service.tag_service import TagService, TagServiceModule
log = logging.getLogger(__name__)
FLAGS = flags.FLAGS... |
91435 | import sys
from hashlib import md5
from management_database import User
def hash_password(email, password):
return md5("%s:%s" % (email, password)).hexdigest()
def main(email, password):
try:
user = User.get_by_email(email)
user.passwd = hash_password(email, password)
user.save()
e... |
91440 | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
SAASU_ERRORS = {
'no_key': 'Please set your SAASU_WSACCESS_KEY setting.',
'no_uid': 'Please set your SAASU_FILE_UID setting.',
'disabled': 'Disabled in demo mode'
}
SAASU_WSACCESS_KEY = getattr(settings, 'SAASU_WSACCE... |
91443 | import traceback
def error_str(func_name, exception):
return func_name + " failed with exception: " + str(exception) + "\n" + str(traceback.print_exc())
def print_dict(dictn):
for elem in dictn:
print(elem, repr(dictn[elem]))
def dump_attrs(obj):
for attr in dir(obj):
print("obj.%s" % ... |
91459 | from django_messages.api import ReceivedMessageResource, SentMessageResource, TrashMessageResource
from friendship.api import FollowerResource, FollowingResource
from tastypie.api import Api
from plan.api import PlanResource
from traveller.api import TravellerResource
from notifications.api import AllNotificationResour... |
91467 | import tkinter as tk
from tkinter import ttk
from collections import deque
class Timer(ttk.Frame):
"""parent is the frame which contains the timer frame self is the object whose properties are being created
and controller is the class whose properties are inherited....tk.Frame properties are also inher... |
91556 | r"""
Utility functions for building Sage
"""
# ****************************************************************************
# Copyright (C) 2017 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the F... |
91581 | from datetime import datetime
import pytz
def convert_to_utc_date_time(date):
"""Convert date into utc date time."""
if date is None:
return
return datetime.combine(date, datetime.min.time(), tzinfo=pytz.UTC)
|
91590 | import pytest
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.datasets import load_diabetes
from tests.utils import resample_data
from deeprob.spn.structure.node import Sum, Product
from deeprob.spn.structure.leaf import Bernoulli, Gaussian
from deeprob.spn.learning.wrappers import learn_estim... |
91597 | from .dosed1 import DOSED1
from .dosed2 import DOSED2
from .dosed3 import DOSED3
__all__ = [
"DOSED1",
"DOSED2",
"DOSED3",
]
|
91634 | from sklearn.gaussian_process.kernels import Kernel, Hyperparameter
from sklearn.gaussian_process.kernels import GenericKernelMixin
from sklearn.gaussian_process.kernels import StationaryKernelMixin
import numpy as np
from sklearn.base import clone
class MiniSeqKernel(GenericKernelMixin, StationaryKernelMixin, Kernel... |
91685 | import json
import numpy as np
learning_map = {
0 : 0, # "unlabeled"
1 : 0, # "outlier" mapped to "unlabeled" --------------------------mapped
10: 1, # "car"
11: 2, # "bicycle"
13: 5, # "bus" mapped to "other-vehicle" --------------------------mapped
15: 3, # "motorcycle"
16: 5, ... |
91688 | import MinkowskiEngine as ME
import MinkowskiEngine.MinkowskiFunctional as MEF
import torch
import torch.nn as nn
from src.models.common import conv, conv_tr, get_nonlinearity, get_norm
class BasicBlockBase(nn.Module):
expansion = 1
NORM_TYPE = "BN"
def __init__(
self,
inplanes,
p... |
91714 | from pyradioconfig.calculator_model_framework.interfaces.icalculator import ICalculator
from enum import Enum
from pycalcmodel.core.variable import ModelVariableFormat, CreateModelVariableEnum
class Calc_AoX_Bobcat(ICalculator):
###AoX Calculations###
def buildVariables(self, model):
var = self._addMo... |
91717 | from typing import Union, Optional, Dict
import torch
from falkon import sparse
from falkon.kernels.diff_kernel import DiffKernel
from falkon.la_helpers.square_norm_fn import square_norm_diff
from falkon.options import FalkonOptions
from falkon.sparse import SparseTensor
SQRT3 = 1.7320508075688772
SQRT5 = 2.23606797... |
91755 | import factory
from user_accounts import models
from .organization_factory import FakeOrganizationFactory
from .user_factory import UserFactory, user_with_name_and_email_from_org_slug
class UserProfileFactory(factory.DjangoModelFactory):
name = factory.Sequence(lambda n: 'Fake User {}'.format(n))
user = facto... |
91759 | from __future__ import absolute_import, division, print_function
import cmath
import math
from six.moves import zip
class least_squares:
def __init__(self, obs, calc):
self.obs = obs
self.calc = calc
a, b = self.calc.real, self.calc.imag
self.abs_calc = math.sqrt(a**2 + b**2)
self.delta = self.o... |
91777 | import os
import requests
import tarfile
import urllib.request
import zipfile
from tqdm import tqdm
def maybe_download_from_url(url, download_dir):
"""
Download the data from url, unless it's already here.
Args:
download_dir: string, path to download directory
url: url to download from
... |
91791 | import sys
import unittest
from packaging import version
from unittest import mock
import tensorflow as tf
import larq_zoo as lqz
from tensorflow.python.eager import context
sys.modules["importlib.metadata"] = mock.MagicMock()
sys.modules["importlib_metadata"] = mock.MagicMock()
sys.modules["larq_compute_engine.mlir.... |
91824 | import CTL.funcs.xplib as xplib
def setXP(newXP):
'''
Set the *py(e.g. numpy, cupy) library for CTL
newXP : object, default numpy
The numpy-like library for numeric functions.
'''
xplib.xp = newXP |
91830 | import numpy as np
import random
from scipy.misc import imresize
from PIL import Image
import math
# from torchvision import transforms
import torch
class MultiRescale(object):
"""MultiScale the input image in a sample by given scales.
Args:
scales_list (tuple or int): Desired output scale list.
... |
91834 | from torch import nn
from rcnn.modeling import registry
from rcnn.core.config import cfg
@registry.MASKIOU_OUTPUTS.register("linear_output")
class MaskIoU_output(nn.Module):
def __init__(self, dim_in):
super(MaskIoU_output, self).__init__()
num_classes = cfg.MODEL.NUM_CLASSES
self.maskio... |
91840 | import torch
from tqdm import tqdm
import os
import numpy as np
train_features=torch.load('train_features.pt')
n = len(list(np.load('/facebook/data/images/train_imlist.npy')))
print(n)
os.makedirs('/siim/sim_pt_256', exist_ok=True)
for i in tqdm(range(n)):
a=torch.mm(train_features[i:i+1],train_features.t())
to... |
91848 | def kb_ids2known_facts(kb_ids):
"""
:param kb_ids: a knowledge base of facts that are already mapped to ids
:return: a set of all known facts (used later for negative sampling)
"""
facts = set()
for struct in kb_ids:
arrays = kb_ids[struct][0]
num_facts = len(arrays[0])
... |
91952 | from secret_sdk.core import Coins
from secret_sdk.client.localsecret import LocalSecret, main_net_chain_id
api = LocalSecret(chain_id=main_net_chain_id)
fee = api.tx.estimate_fee(
gas=250_000
)
print(fee)
fee = api.tx.estimate_fee(
gas=200_000,
gas_prices=Coins.from_data([{"amount": 0.25, "denom": "uscrt"... |
92009 | from fairing.backend.kubeflow import KubeflowBackend
from fairing.utils import get_image_full
class BasicArchitecture():
def add_jobs(self, svc, count, repository, image_name, image_tag, volumes, volume_mounts):
full_image_name = get_image_full(repository, image_name, image_tag)
tfjobs = []
... |
92011 | from collections import Counter
from collections import defaultdict
# [3] https://leetcode.com/problems/longest-substring-without-repeating-characters/
# Given a string, find the length of the longest substring without repeating characters.
#
# variation with no pattern
def lengthOfLongestSubstring(s):
# create a... |
92018 | from mltoolkit.mldp.pipeline import Pipeline
from mltoolkit.mldp.steps.readers import CsvReader
from mltoolkit.mldp.steps.transformers.nlp import TokenProcessor,\
VocabMapper, Padder
from mltoolkit.mldp.steps.transformers.field import FieldSelector
from mltoolkit.mldp.utils.helpers.nlp.token_cleaning import twitter... |
92020 | import unittest
from tginviter import generate_invite_link, get_random_token, \
generate_joinchat_link
class TestLinksGeneration(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.bot_name = "test_bot"
cls.token = get_random_token()
def test_keywords_param_only(self):
... |
92026 | import json
import os
import re
import subprocess
from functools import cached_property
import requests
import yaml
# Changelog types
PULL_REQUEST = 'pull_request'
COMMIT = 'commit_message'
class ChangelogCIBase:
"""Base Class for Changelog CI"""
github_api_url = 'https://api.github.com'
def __init__... |
92047 | from unittest import TestCase
from django_jsonform.utils import normalize_schema
class TestNormalizeSchemaFunction(TestCase):
"""Tests for utils.normalize_schema function"""
def test_normalized_schema_is_same(self):
"""Normalized schema must be the same as input schema
if there are no python ... |
92095 | import sys
import logging
def get_logger(name: str):
logger = logging.getLogger(name)
logformat = "[%(asctime)s] %(levelname)s:%(name)s: %(message)s"
logging.basicConfig(level=logging.INFO, stream=sys.stdout,
format=logformat, datefmt="%Y-%m-%d %H:%M:%S")
return logger
|
92135 | from __future__ import absolute_import, division, print_function
from iotbx.kriber import strudat
from cctbx import geometry_restraints
from cctbx import crystal
from cctbx.array_family import flex
import scitbx.math
from scitbx import matrix
from libtbx.test_utils import approx_equal, show_diff
from libtbx.utils impor... |
92181 | import struct
import time
import yaml
import yaml.resolver
from collections import OrderedDict
import data_types
from data_types import TypeID
def now_ns():
return int(time.time() * 10 ** 6)
class Schema:
""" The schema for the data in the atomic multilog.
"""
def __init__(self, columns):
... |
92205 | from cliche import cli
@cli
def exception_example():
raise ValueError("No panic! This is a known error")
|
92234 | from sqlalchemy import Column, func
from clickhouse_sqlalchemy import types, Table
from tests.testcase import CompilationTestCase
class CountTestCaseBase(CompilationTestCase):
table = Table(
't1', CompilationTestCase.metadata(),
Column('x', types.Int32, primary_key=True)
)
def test_count... |
92241 | import json
from adsimulator.templates.default_values import DEFAULT_VALUES
def print_all_parameters(parameters):
print("")
print("New Settings:")
print(json.dumps(parameters, indent=4, sort_keys=True))
def get_perc_param_value(node, key, parameters):
try:
if 0 <= parameters[node][key] <= 10... |
92248 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
from matplotlib.transforms import Bbox
import seaborn as sns
import utils
from utils import filters, maxima, segment, merge
import warnings
def pipeline(img, low, high, roi_percentile=85, focal_scope='global', maxima_are... |
92268 | import re
from functools import reduce
from operator import or_
from actstream.models import Follow
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
from django_filters import CharFilter, ChoiceFilter, FilterSet
from machina.apps.forum.models import Forum
from machina.... |
92281 | from django.shortcuts import render, get_object_or_404
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.views import redirect_to_login
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.core.exceptions import ImproperlyConfi... |
92290 | import json
import os
import shutil
import sys
from subprocess import CalledProcessError, check_output
import pytest
from click.testing import CliRunner
from deepcov.cli import File
from snapshottest.pytest import PyTestSnapshotTest
from tests.util import RESOURCES
from deepcov import cli # isort:skip
pytest_plugin... |
92296 | from __future__ import annotations
import sys
from argparse import ArgumentParser, Namespace
from pathlib import Path
import pytermgui as ptg
def _process_arguments(argv: list[str] | None = None) -> Namespace:
"""Processes command line arguments.
Note that you don't _have to_ use the bultin argparse module... |
92305 | r"""
Basic analysis of a MD simulation
=================================
In this example, we will analyze a trajectory of a *Gromacs* MD
simulation:
The trajectory contains simulation data of lysozyme over the course of
1 ns.
The data is the result of the famous *Gromacs*
'`Lysozyme in Water <http://www.mdtutorials.co... |
92313 | from itertools import cycle
from unittest.mock import patch
from django.utils import timezone as djangotime
from model_bakery import baker, seq
from tacticalrmm.test import TacticalTestCase
from logs.models import PendingAction
class TestAuditViews(TacticalTestCase):
def setUp(self):
self.authenticate()... |
92318 | from main import db
from sqlalchemy import Column, Integer, DateTime, Text, ForeignKey
class Mail(db.Model):
__tablename__ = "mail"
id = Column(Integer, primary_key=True)
# 发送者用户ID
from_id = Column(Integer, ForeignKey(
"user.id", ondelete="CASCADE"), index=True, nullable=False)
# 接收者用户ID
... |
92330 | import os
import warnings
from itertools import tee
from copy import copy
from collections import namedtuple
import numpy as np
import pybullet as p
from pybullet_planning.interfaces.env_manager.pose_transformation import get_distance
from pybullet_planning.utils import MAX_DISTANCE, EPS, INF
from pybullet_planning.in... |
92333 | import numpy as np
from torch.utils.data import DataLoader, SequentialSampler
HIDDEN_SIZE_BERT = 768
def flat_accuracy(preds, labels):
preds = preds.squeeze()
my_round = lambda x: 1 if x >= 0.5 else 0
pred_flat = np.fromiter(map(my_round, preds), dtype=np.int).flatten()
labels_flat = labels.flatten()
... |
92350 | import EasyGA
import random
# Create the Genetic algorithm
ga = EasyGA.GA()
ga.save_data = False
def is_it_5(chromosome):
"""A very simple case test function - If the chromosomes gene value is a 5 add one
to the chromosomes overall fitness value."""
# Overall fitness value
fitness = ... |
92352 | import tfnn
from tfnn.body.layer import Layer
class PoolingLayer(object):
def __init__(self, pooling='max', strides=(2, 2), ksize=(2, 2), padding='SAME', name=None):
self.pooling = pooling
self.strides = strides
self.ksize = ksize
self.padding = padding
self.name = name
... |
92364 | import numpy as np
import sys
import tensorflow as tf
import cv2
import time
import sys
from .utils import cv2_letterbox_resize, download_from_url
import zipfile
import os
@tf.function
def transform_targets_for_output(y_true, grid_y, grid_x, anchor_idxs, classes):
# y_true: (N, boxes, (x1, y1, x2, y2, class, best... |
92406 | import timeit
class TimingsEntry(object):
"""A log of the runtime for an operation.
"""
def __init__(self, op):
self.op = op
self.evals = 0
self.total_time = 0
self.lastticstamp = None
@property
def avg_time(self):
if self.evals == 0:
return 0
... |
92471 | import os
import yaml
import time
import shutil
import torch
import random
import argparse
import numpy as np
import copy
import timeit
import statistics
import datetime
from torch.utils import data
from tqdm import tqdm
import cv2
from ptsemseg.process_img import generate_noise
from ptsemseg.models import get_model
f... |
92482 | import numpy as np
from .. import inf
from ... import blm
from . import learning
from .prior import prior
class model:
def __init__(self, lik, mean, cov, inf='exact'):
self.lik = lik
self.prior = prior(mean=mean, cov=cov)
self.inf = inf
self.num_params = self.lik.num_params + self.... |
92485 | import numpy as np
import labels as L
import sys
import tensorflow.contrib.keras as keras
import tensorflow as tf
from keras import backend as K
K.set_learning_phase(0)
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
from... |
92529 | from unittest import TestCase
import numpy as np
from source.analysis.performance.curve_performance import ROCPerformance, PrecisionRecallPerformance
class TestROCPerformance(TestCase):
def test_properties(self):
true_positive_rates = np.array([1, 2])
false_positive_rates = np.array([3, 4])
... |
92538 | from tg_bot.handlers import (
start,
registration,
info,
main_menu,
schedule,
attestation,
suburbans,
editor,
rate,
other_text,
inline_handlers
)
|
92556 | from __future__ import print_function
import numpy as np
import pandas as pd
import inspect
import os
import time
from . import Model
from . import Utils as U
#------------------------------
#FINDING NEAREST NEIGHBOR
#------------------------------
def mindistance(x,xma,Nx):
distx = 0
mindist = 1000000 * U.P... |
92614 | pkgname = "python-sphinxcontrib-serializinghtml"
pkgver = "1.1.5"
pkgrel = 0
build_style = "python_module"
hostmakedepends = ["python-setuptools"]
checkdepends = ["python-sphinx"]
depends = ["python"]
pkgdesc = "Sphinx extension which outputs serialized HTML document"
maintainer = "q66 <<EMAIL>>"
license = "BSD-2-Claus... |
92629 | import enum
from typing import Union
@enum.unique
class PriorityStatus(enum.Enum):
HIGHEST = 0
HIGHER = 10
HIGH = 20
NORMAL = 30
LOW = 40
LOWER = 50
LOWEST = 60
class HookBase:
"""HookBase is the base class of all hook and is registered in EngineBase class.
The subclasses of Hook... |
92632 | from typing import *
import pprint
from onmt.utils.report_manager import ReportMgrBase
from onmt.utils.statistics import Statistics
from seutil import LoggingUtils
class CustomReportMgr(ReportMgrBase):
logger = LoggingUtils.get_logger(__name__)
def __init__(self, report_every, start_time=-1.):
su... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.