id
stringlengths
3
8
content
stringlengths
100
981k
1795870
import paddle import paddle.nn as nn import paddle.nn.functional as F from paddle.vision.models import vgg16 from ppcd.models.layers import CAM, SAM class Vgg16Base(nn.Layer): # Vgg16 feature extraction backbone def __init__(self, in_channels=3): super(Vgg16Base, self).__init__() features = vg...
1795930
from config import * from os.path import join, dirname from tensorflow.keras.utils import get_file def download_existing_dataset(dataset_url, dataset_name): '''Download Dataset Params: dataset_url -> Url to the dataset dataset_name -> Name of the dataset ''' file_name = dataset_...
1795969
import json import boto3 import time import os def lambda_handler(event, context): empvod = boto3.client('mediapackage-vod') packaging_group_id = os.environ['PACKAGING_GROUP_ID'] hls_playlist_paths = [] for output_detail in event['detail']['outputGroupDetails']: if output_detail['type'] == 'H...
1796066
import numpy as np import scipy.stats as stats _future_warn = """\ Passing `None` as the seed currently return the NumPy singleton RandomState (np.random.mtrand._rand). After release 0.13 this will change to using the default generator provided by NumPy (np.random.default_rng()). If you need reproducible draws, you sh...
1796072
from typing import List from backend.common.consts import comp_level from backend.common.helpers.match_helper import TOrganizedMatches class PlaylistHelper(object): @classmethod def generate_playlist_link( cls, title: str, matches_organized: TOrganizedMatches, allow_levels: Li...
1796094
import numpy as np import tensorflow as tf import tensorflow_probability as tfp def gaussian_likelihood(mean: tf.Tensor, logsd: tf.Tensor, x: tf.Tensor): r"""calculate negative log likelihood of Gaussian Distribution. Args: mean (tf.Tensor): mean [B, ...] logsd (tf.Tensor): log standard devi...
1796112
from enum import Enum ROWS = 6 COLS = 7 class Color(Enum): RED = 1 BLACK = 2 class Board: def __init__(self): self.grid = list() for _ in range(COLS): col = list() for _ in range(ROWS): col.append(None) self.grid.append(col) se...
1796118
import urllib.request # 构建一个HTTPHandler处理器对象,支持处理HTTP请求,带有的参数debuglevel可用于调试 # http_handler = urllib.request.HTTPHandler() http_handler = urllib.request.HTTPHandler(debuglevel=1) # 构建一个自定义的opener,用于发起请求 opener = urllib.request.build_opener(http_handler) # 构建Request请求 request = urllib.request.Request("http://www.baid...
1796124
import inspect import random import re from typing import Set, cast, get_args, get_origin from devtools import debug from pepperbot.exceptions import EventHandlerDefineError from pepperbot.globals import * from pepperbot.parse import ( GROUP_EVENTS, GROUP_EVENTS_T, GroupEvent, is_valid_friend_method, ...
1796151
import os import PIL.Image import numpy as np import tensorflow as tf import tensorflow_hub as hub from keras.applications import resnet50 from keras.applications.resnet50 import ResNet50 from keras.backend import set_session from scipy.stats import truncnorm # Initialize the module module_path = 'https://tfhub.dev/d...
1796180
import re import os import development totaltime = re.compile("Total Time: ([0-9]*)ms ([0-9]*) iterations.*") def get_bta_cmd(): if development.get_development(): cmdline = "sicstus -r run_bta.sav --goal \"runtime_entry(start),halt.\" -a" else: cmdline = os.path.join(".","bta") return...
1796187
from io import StringIO import sys import unittest from pbhhg_py.main import main class TestBase(unittest.TestCase): def _assert_execute(self, program, py_value, stdin='', stdout=''): sys.stdin, sys.stdout = StringIO(stdin), StringIO() result = main(program, False) self.assertEqual(len(re...
1796202
from django.shortcuts import render, HttpResponse, redirect, \ get_object_or_404, reverse from django.contrib.auth.decorators import login_required from django.contrib import messages from django.conf import settings from decimal import Decimal from paypal.standard.forms import PayPalPaymentsForm from django.views....
1796217
from typing import Dict from dataclasses import dataclass, field from dnn_cool.visitors import LeafVisitor, VisitorOut, RootCompositeVisitor class TuningVisitor(LeafVisitor): def __init__(self, task, prefix): super().__init__(task, prefix) def empty_result(self): return TunedParams({self.p...
1796272
import codecs import re from codecs import StreamReaderWriter from typing import Optional from logging2.handlers.abc import Handler from logging2.levels import LogLevel # NOTE: This module does not provide handlers for rotating log files. The rationale behind that is that all *NIX systems # have software specificall...
1796334
from models import User count = User.count() max_id = User.max(User.id) min_id = User.min(User.id) sum_of_ids = User.sum(User.id) avg_of_ids = User.avg(User.id)
1796341
import torch import torch.nn as nn from neuroir.inputters import BOS, PAD from neuroir.modules.embeddings import Embeddings from neuroir.encoders.rnn_encoder import RNNEncoder from neuroir.decoders.rnn_decoder import RNNDecoder class Embedder(nn.Module): def __init__(self, emsize, ...
1796350
from .models import Foo, Bar from .serializers import FooSerializer, BarSerializer from rest_framework import viewsets from rest_framework.decorators import api_view from rest_framework.views import APIView from rest_framework.request import Request from rest_framework.response import Response from rest_framework.exce...
1796354
import torch import torch.nn as nn from transformers import BertTokenizer, BertModel class Bert(nn.Module): def __init__(self,cfg=None): super().__init__() self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') self.model = BertModel.from_pretrained('bert-base-uncased') d...
1796355
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence from typing import Tuple, Union, Callable class Embedding(nn.Module): """Embedding class""" def __init__(self, num_embeddings: int, embedding_dim: int, p...
1796372
def dfs(graph, start=0): n = len(graph) dp = [0] * n visited, finished = [False] * n, [False] * n stack = [start] while stack: start = stack[-1] # push unvisited children into stack if not visited[start]: visited[start] = True for child in graph[sta...
1796434
from .accuracy_validator import AccuracyValidator from .base_validator import BaseValidator from .class_cluster_validator import ClassClusterValidator from .deep_embedded_validator import DeepEmbeddedValidator from .diversity_validator import DiversityValidator from .entropy_validator import EntropyValidator from .erro...
1796462
class BaseKeyMapper(object): def leader_mapping(self, item) -> dict: raise NotImplementedError def follower_mapping(self, item) -> dict: raise NotImplementedError @classmethod def name(cls): return "BASE_KEY_MAPPER"
1796492
from app import socketio from config import * from .spi import * from ..socketio_queue import EmitQueue from flask_socketio import Namespace import logging logger = logging.getLogger("SIO_Server") class XApiNamespace(Namespace): md = None td = None mq = None spi = None orders_map = {} def ...
1796497
from typing import Iterable, Mapping, Union, Optional, Tuple import pathlib import json from abc import abstractmethod from enum import Enum, auto import torch from torch import nn from .codemaps_helpers import (CodemapsHelper, SimpleCodemapsHelper, ZigZagCodemapsHelper) from VQCPCB.tra...
1796509
port = 8000 user_dir = '' pretty_print = False socket_ip = 'localhost' socket_port = 1234 upload_dir = 'downloads'
1796573
import xml.etree.ElementTree as ET import gzip from collections import defaultdict import numpy as np class EvalNode(object): def __init__(self, fid, value): self.yes = None self.no = None self.weight = 1.0 self.fid = fid self.value = value def eval(self, arr): ...
1796580
import sys from heapq import heappush, heappop, heapify BEFORE = True AFTER = False def load_num(): line = sys.stdin.readline() if line == ' ' or line == '\n': return None return int(line) def load_case(): npeople = load_num() people = [] for p in range(npeople): people.app...
1796600
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import tensorflow as tf class SearchableKernelMaker: def make_searchable_kernel_w_and_conds(self, kernel_w, tf_masks, thresholds, is_supergraph_training_tensor, ...
1796609
from typing import cast, TYPE_CHECKING from ...constants import unpack_derivation_path from ...wallet import AbstractAccount from ...wallet_database.types import KeyListRow from ..hw_wallet.qt import QtHandlerBase, QtPluginBase from .digitalbitbox import DigitalBitboxPlugin, DigitalBitbox_KeyStore if TYPE_CHECKING:...
1796614
import dash_html_components as html import dash_bootstrap_components as dbc import yaml from navbar import Navbar from footer import Footer def Users(): """Builds the AboutUs->Model Users using assets/users/organizations.yml""" with open("assets/users/organizations.yml") as f: collaborators = yaml.l...
1796689
import sys sys.path.append('..') import matplotlib.pyplot as plt from bijou.datasets import mnist from bijou.data import DataProcess as dp, Dataset, DataLoader, DataBunch from bijou.modules import Lambda from bijou.metrics import accuracy from bijou.learner import Learner from torch import optim import torch.nn as nn ...
1796723
from datetime import datetime from sepal.drive import get_service from sepal.drive.rx.observables import execute def touch(credentials, file): def action(): get_service(credentials).files().update( fileId=file['id'], body={'modifiedTime': datetime.utcnow().strftime("%Y-%m-%dT%H:%M...
1796730
from schafkopf.players.player import Player class HumanConsolePlayer(Player): """Player for playing on console""" def choose_game_mode(self, public_info, options): options = list(options) while True: mode_index = input("Hand : {} \n" "Previous Proposals: {}...
1796814
import _nx import warnings from .utils import bit, cached_property AUTO_PLAYER_1_ID = 10 def refresh_inputs(): """Refreshes inputs. Should normally be called at least once within every iteration of your main loop. """ _nx.hid_scan_input() def _determine_controller_type(player): # TODO det...
1796817
import os from biicode.client.dev.cmake.cmaketool import CMakeTool from biicode.common.model.blob import Blob from biicode.common.utils.file_utils import save_blob_if_modified, save, load_resource from biicode.client.dev.cpp import DEV_CPP_DIR default_cmake = """ ADD_BII_TARGETS() ###################################...
1796834
import torch import numpy as np import torch.nn as nn from pruner.filter_pruner import FilterPruner from model.MobileNetV2 import InvertedResidual class FilterPrunerMBNetV2(FilterPruner): def parse_dependency(self): pass def forward(self, x): if isinstance(self.model, nn.DataParallel): ...
1796859
from typing import List from pydantic import BaseModel from tortoise.contrib.pydantic import pydantic_model_creator, pydantic_queryset_creator from rearq.server.models import Job, JobResult class JobListOut(BaseModel): rows: pydantic_queryset_creator(Job) total: int JobOut = pydantic_model_creator(Job) ...
1796864
from dataclasses import dataclass import numpy as np @dataclass class UniformInitialConditions: def make_initial_conditions(self, environments: tuple, environment_names_to_state: tuple): n_total_place_bins = 0 initial_conditions = []...
1796936
import json import jsonpatch from tomviz import operators, modules from ._pipeline import PipelineStateManager from ._utils import to_namespaces op_class_attrs = ['description', 'label', 'script', 'type'] class InvalidStateError(RuntimeError): pass class Base(object): def __init__(self, **kwargs): ...
1797010
import requests from settings import base_url, client_id, robinhood_version, oauth_url from credentials import username, password, device_id # from utils.device_token import generate_device_token from sql.operations.authorization import\ get_auth_tokens,\ create_authorization,\ update_auth_tokens # from s...
1797022
from __future__ import absolute_import from __future__ import division from __future__ import print_function import inspect import math import os import uuid from collections import * from collections import deque from copy import copy, deepcopy from functools import partial from itertools import repeat import numpy...
1797025
from nautobot.core.apps import NautobotConfig class VirtualizationConfig(NautobotConfig): name = "nautobot.virtualization"
1797071
import math from time import perf_counter from numba import njit @njit(fastmath=True) def is_prime(num): if num == 2: return True if num == 1 or not num % 2: return False for div in range(3, int(math.sqrt(num)) + 1, 2): if not num % div: return False return True ...
1797078
from typing import Dict from torch import Tensor from label_converter import CTCLabelConverter class RecMetric(object): def __init__(self, converter: CTCLabelConverter): """ 文本识别相关指标计算类 :param converter: 用于label转换的转换器 """ self.converter = converter def __call__(self,...
1797094
import unittest from katas.kyu_6.custom_array_filters import MyList class MyListTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(MyList([1, 2, 3, 4, 5]).even(), [2, 4]) def test_equal_2(self): self.assertEqual(MyList([1, 2, 3, 4, 5]).odd(), [1, 3, 5]) def test_equal...
1797116
from tool.darknet2pytorch import Darknet import struct import sys def convert_layer_name(name): parts = name.split(".") parts[0] = "model" parts[2] = ''.join([i for i in parts[2] if not i.isdigit()]) return '.'.join(parts) config = sys.argv[1] model = Darknet(config) weights = sys.argv[2] model.load_w...
1797164
from rest_framework import serializers from rest_framework.reverse import reverse from onadata.libs.utils.decorators import check_obj class FSXFormManifestSerializer(serializers.Serializer): filename = serializers.ReadOnlyField(source='data_value') hash = serializers.SerializerMethodField() downloadUrl =...
1797176
import os import cupy import numpy as np import pytest import skimage.data from PIL import Image import cucim.core.operations.spatial as spt def get_input_arr(): img = skimage.data.astronaut() arr = np.asarray(img) arr = np.transpose(arr) return arr def get_flipped_data(): dirname = os.path.di...
1797206
import json from datetime import datetime import pytest from pydantic.error_wrappers import ValidationError as PydanticValidationError from node.blockchain.facade import BlockchainFacade from node.blockchain.inner_models import ( AccountState, Block, BlockMessageUpdate, GenesisBlockMessage, GenesisSignedChangeReq...
1797215
import shutil import unittest from malcolm.core import Process from malcolm.modules.builtin.defines import tmp_dir from malcolm.modules.demo.blocks import motion_block class TestMotionBlock(unittest.TestCase): def setUp(self): self.p = Process("proc") self.config_dir = tmp_dir("config_dir") ...
1797221
import json import pytest from django.contrib.admin.sites import AdminSite from django.urls import reverse from wazimap_ng.profile.models import ProfileHighlight from wazimap_ng.profile.admin import ProfileHighlightAdmin @pytest.mark.django_db class TestProfileHighlightAdminHistory: def test_change_reason_fiel...
1797232
import binascii from lrp import AuthenticateLRP def test_auth1_lrp(): auth = AuthenticateLRP(b"\x00" * 16) # ------------------------------------------------------------------------- # we patch generate_rnda to ensure predictable output for this test case # DON'T DO THIS WHEN USING ON PRODUCTION, RN...
1797265
from .base import AbstractPositionSizer class NaivePositionSizer(AbstractPositionSizer): def __init__(self, default_quantity=100): self.default_quantity = default_quantity def size_order(self, portfolio, initial_order): """ This NaivePositionSizer object follows all suggestion...
1797268
from .tox_modernizer import ConfigReader, ToxModernizer from .travis_modernizer import TravisModernizer from .travis_modernizer import DJANGO_PATTERN from .github_actions_modernizer import GithubCIModernizer from .github_actions_modernizer_django import GithubCIDjangoModernizer
1797317
import random import logging import re from lore.io.connection import Connection from lore.util import scrub_url logger = logging.getLogger(__name__) class MultiConnectionProxy(object): SQL_RUNNING_METHODS = ['dataframe', 'unload', 'select', 'execute', 'temp_table'] def __init__(self, urls, name='connecti...
1797319
import copy import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.distributions as dist from core.models.common_layers import get_nddr from core.utils import AttrDict from core.tasks import get_tasks from core.utils.losses import poly, entropy_loss, l1_loss class General...
1797325
import functools import time import torch import torch.autograd as autograd import torch.cuda.comm as comm import torch.nn as nn import torch.nn.functional as F from torch.autograd.function import once_differentiable class CA_Weight(autograd.Function): @staticmethod def forward(ctx, t, f): # Save con...
1797366
from functools import partial from collections import defaultdict from .models import UNTITLED_ARTIST, UNTITLED_ALBUM FIELDS_ORDER = [ 'id', 'source', 'source_id', 'title', 'number', 'mbid', 'artist_mbid', 'album_mbid' ] def compress_tracks_to_json(tracks): """ Serialize tra...
1797376
class HttpNegotiateAuth: def __call__(self, r): r.headers["Authorization"] = "HttpNegotiateAuth fake"
1797417
import os import numpy as np import csv import unittest from cave.utils.hpbandster2smac import HpBandSter2SMAC class TestHpbandster2Smac(unittest.TestCase): def setUp(self): rng = np.random.RandomState(42) self.path_to_result_mixed_categorical_pcs = "test/test_utils/hpbandster2smac_files/mixed_ca...
1797469
import os import bz2 import MySQLdb import pandas as pd import numpy as np from collections import defaultdict ''' Connect to DB ''' db = MySQLdb.connect(host=os.environ.get("DATAVIVA_DB_HOST", "localhost"), user=os.environ[ "DATAVIVA_DB_USER"], passwd=os.environ["DATAVIVA_DB_PW"], db=os.environ["...
1797488
from pathlib import Path from timeit import default_timer as timer import h5py import numpy as np import torch from methods.utils.data_utilities import (_segment_index, load_dcase_format, to_metrics2020_format) from torch.utils.data import Dataset, Sampler from tqdm import tqd...
1797515
import math from .searcher import Searcher from pychemia import pcm_log class ParticleSwarm(Searcher): def __init__(self, population, params=None, generation_size=32, stabilization_limit=10): """ Implementation fo the Firefly algorithm for global minimization This searcher uses a metric t...
1797522
import os.path import os import mimetypes import logging from .wsgi import app_with_config def serve_wsgi_app_with_cli_args(args, config): application = app_with_config(config) application.run(host=args.addr, port=int(args.port))
1797524
import sys sys.path.append("../svg") from geometry import GeometryLoss import numpy as np import pygame as pg import torch import pydiffvg import tkinter as tk from tkinter import filedialog def box_kernel(val): return np.heaviside(-val+1,0) def cone_kernel(val): return np.maximum(0,1-val) de...
1797562
import numpy as np class PairPotential: def u(self, r): raise NotImplemented() def f(self, r): raise NotImplemented() def a(self, r): raise NotImplemented() class BuckinghamPotential(PairPotential): def __init__(self, params): self.a, self.rho, self.c = params d...
1797563
import sys if '.' not in sys.path: sys.path.insert(0, '.') # so that we can find ptvsd if 'ptvsd' not in sys.modules: import ptvsd eval('ptvsd.enable_attach(' + sys.argv[1] + ')') ptvsd.wait_for_attach() sys.stdout.write('stdout') sys.stderr.write('stderr') x = 1
1797572
SQL_SETUP = """ create table person( id serial primary key, email text, dob date, created_at timestamp ); comment on column person.created_at is E'@exclude create, update'; comment on column person.email is E'@exclude update'; comment on column person.dob is E'@exclude read'; """ def test_reflect_fun...
1797751
from typing import Optional, List from pydantic import PrivateAttr from pydantic.main import BaseModel from inoft_vocal_framework.skill_settings.skill_settings import INFRASTRUCTURE_TO_BASE_URL from inoft_vocal_framework.platforms_handlers.alexa.audioplayer.audioplayer_directives import AudioPlayerWrapper from inoft_...
1797760
import math import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import resnet12 ###### --- Conv4-64 --- ###### # This arch is the same as Spyros's works: https://github.com/gidariss/FewShotWithoutForgetting/blob/master/architectures/ConvNet.py ###### --- ResNet12 --- ###### # ResNet1...
1797773
from .vertex import Vertex from .object_manager import Manager class Polygon: def __init__(self): self.id = -1 # store the actual vertices, vertices are ordered in sequence! self.vertices = [] self.vertex_ids = set() self.edge_ids = set() self.obstacle_ids = set() ...
1797774
import Registry from fixtures import * def test_file_type(hive): assert hive._regf.file_type() == Registry.RegistryParse.FileType.FILE_TYPE_PRIMARY
1797781
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.stats import gaussian_kde import seaborn as sns from sklearn.metrics import classification_report, roc_auc_score, roc_curve import matplotlib matplotlib.rc('font', family='Arial') flu = pd.read_csv('flu_mcpas_val.csv') ebv = pd.read_csv(...
1797801
import ray import numpy as np import tensorflow as tf def get_batch(data, batch_index, batch_size): # This method currently drops data when num_data is not divisible by # batch_size. num_data = data.shape[0] num_batches = num_data / batch_size batch_index %= num_batches return data[(batch_index * batch_siz...
1797806
import math from urllib.request import urlretrieve import torch from PIL import Image from tqdm import tqdm import numpy as np import random import torch.nn.functional as F '''gen_A: co-occur matrix generation''' def gen_A(num_classes, t, adj_file): import pickle result = pickle.load(open(adj_file, 'rb')) ...
1797832
import numpy as np def get_tree_slow(sorted_indices, adj): block = [] treeNumber = {} nTrees = 0 for coordinate in sorted_indices: neighbors = np.nonzero(adj[coordinate])[0] nn = np.intersect1d(neighbors, block) neighTrees = set() continueFlag = False for neigh in...
1797843
from matplotlib import cm import matplotlib.pyplot as plt import numpy as np import random import itertools import torch from torchvision.utils import make_grid from tensorboardX import SummaryWriter from data.utils import get_coord from tools.utils import create_colormap, color_transfer, color_spread ...
1797848
class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: maxNum = count = 0 for i, a in enumerate(arr): maxNum = max(maxNum, a) if maxNum == i: count += 1 return count
1797853
from optimus.engines.base.dataframe.dataframe import DataFrameBaseDataFrame class DistributedBaseDataFrame(DataFrameBaseDataFrame): pass
1797862
import doctest from insights.parsers import avc_hash_stats from insights.parsers.avc_hash_stats import AvcHashStats from insights.tests import context_wrap AVC_HASH_STATS = """ entries: 509 buckets used: 290/512 longest chain: 7 """.strip() def test_avc_hash_stats(): hash_stats = avc_hash_stats.AvcHashStats(cont...
1797893
import pandas as pd import os from plot_keras_history import plot_history import matplotlib.pyplot as plt import matplotlib matplotlib.use("Agg") def test_plot_multi_history(): plot_history([ pd.read_csv("tests/history1.csv"), pd.read_csv("tests/history2.csv"), pd.read_csv("tests/history4....
1797926
import bl2sdk import datetime class DPS(bl2sdk.BL2MOD): Name = "DPS/TTK Calculator" Description = "Upon damaging an enemy a counter will start in the background. On kill it will then calculate the " \ "DPS in that amount of time, from dealing damage to the kill. The longer you need to kill an enemy " \ ...
1797981
from django.views.generic import RedirectView, FormView from django.contrib.auth import authenticate, login from django.shortcuts import Http404, redirect from django.core.urlresolvers import reverse from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django.contrib.auth.models import User f...
1797982
import requests from kibitzr.checker import Checker def test_server_is_alive(target): """Sanity check, that test environment is properly setup""" response = requests.get("http://{0}:{1}/index.html".format(*target)) assert response.status_code == 200 def test_simple_fetcher_with_pretty_json(target, json_...
1798007
import six if six.PY3: import unittest else: import unittest2 as unittest import collections from depsolver.compat \ import \ OrderedDict, sorted_with_cmp from depsolver.package \ import \ PackageInfo from depsolver.pool \ import \ Pool from depsolver.repository \ impo...
1798029
import unittest import sys from fudge import reactionSuite from brownies.BNL.inter.report import * from xData.unittest import TestCaseWithIsClose as TestCaseWithExtras TEST_DATA_PATH, this_filename = os.path.split(os.path.realpath(__file__)) VERBOSE = '-v' in sys.argv or '--verbose' in sys.argv DOPLOTS = '-p' in sys.a...
1798049
import argparse from generator import Generator from parse_dataset import comment_to_tokens import os import re def main(): sequences = [] files = os.listdir(OPTS.test_data_dir) files.sort() for i in range(len(files)): file = files[i] if not re.match('\d+\.txt', file): continue with open(os.path.join(OP...
1798090
def write_cg_itp_file(itp_obj, out_path_itp, print_sections=["constraint", "bond", "angle", "dihedral", "exclusion"]): """Print coarse-grain ITP. Here we have a switch for print_sections because we might want to optimize constraints/bonds/angles/dihedrals separately, so we can leave some out with the switch...
1798136
from beem.utils import formatTimeString, resolve_authorperm, construct_authorperm, addTzInfo from beem.nodelist import NodeList from beem.comment import Comment from beem import Steem from beem.account import Account from beem.instance import set_shared_steem_instance from beem.blockchain import Blockchain import time ...
1798145
from .lofo_importance import LOFOImportance from .flofo_importance import FLOFOImportance from .dataset import Dataset from .plotting import plot_importance
1798220
def test_categories(wikigraph): categories = wikigraph.get_categories("Category:Apples") assert categories == ["Category:Fruits", "Category:Amygdaloideae"] def test_neighbors(wikigraph): neighbors = wikigraph.get_neighbors("Category:Apples") assert neighbors == [ "McIntosh_(apple)", "J...
1798226
import sys """ Extend the twx namespace """ if sys.version_info[0] == 3 and sys.version_info[1] >= 2: from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
1798270
from factory import Faker from thenewboston.constants.network import VERIFY_KEY_LENGTH from thenewboston.factories.created_modified import CreatedModifiedFactory from ..models.account import Account class AccountFactory(CreatedModifiedFactory): account_number = Faker('pystr', max_chars=VERIFY_KEY_LENGTH) tr...
1798302
import pytest import numpy as np import pandas as pd from .context import fitgrid from fitgrid import fake_data, defaults from fitgrid.errors import FitGridError from fitgrid.epochs import Epochs def test_epochs_unequal_snapshots(): epochs_table, channels = fake_data._generate( n_epochs=10, n_sam...
1798305
from collections import Counter from functools import partial import numpy as np import pandas as pd from sklearn.metrics import roc_auc_score, roc_curve from sklearn.utils.multiclass import unique_labels from responsibly.fairness.metrics.utils import ( _assert_binary, _groupby_y_x_sens, ) def _proportion(data,...
1798313
from __future__ import division import sys import time import torch from tqdm import tqdm tqdm.monitor_interval = 0 from tensorboardX import SummaryWriter from pytorch_utils import CheckpointDataLoader, CheckpointSaver class BaseTrainer(object): """ BaseTrainer class to be inherited options - time_to_ru...
1798325
import re def count_words_in_markdown(markdown): text = markdown # Comments text = re.sub(r'<!--(.*?)-->', '', text, flags=re.MULTILINE) # Tabs to spaces text = text.replace('\t', ' ') # More than 1 space to 4 spaces text = re.sub(r'[ ]{2,}', ' ', text) # Footnotes text = re...
1798429
import igraph import numpy as np def community_ecg(self, weights=None, ens_size = 16, min_weight = 0.05): """ Runs an ensemble of single-level randomized Louvain; each member of the ensemble gets a "vote" to determine if the edges are intra-community or not; the votes are aggregated into an "ECG ...
1798435
import bpy from bpy.props import * from ...nodes.BASE.node_base import RenderNodeBase class RenderNodeSetEeveeAmbientOcclusion(RenderNodeBase): """A simple input node""" bl_idname = 'RenderNodeSetEeveeAmbientOcclusion' bl_label = 'Set Eevee Ambient Occlusion' def init(self, context): self.cre...