text stringlengths 3.07k 12.6k |
|---|
DAY = 9
from collections import defaultdict as dd
from functools import lru_cache
def solve(data, wall=False):
graph = dd(dict)
for line in data:
fro, would, gain, change, *_ , to = line.split()
change = ([-1,1][gain=="gain"]) * int(change)
to = to.strip(".")
graph[fro... |
import sys
import logging
from log import logging_conf
import time
import numpy as np
import matplotlib.pyplot as plt
from brica import VirtualTimeScheduler, Timing
from matchernet.ekf import BundleEKFContinuousTime, MatcherEKF
from matchernet import fn
from matchernet.observer import Observer
from matchernet.state_sp... |
import enum
import pandas as pd
import copy
from . import Parser
from .rule import Rule
class NormType(enum.Enum):
RAW = 0
NORM = 1
BASE = 2
class Path:
def __init__(self, word, base, rule):
self.word = word
self.base = base
self.rule = rule
def __repr__(self):
... |
"""
This Module provides semantic sensors. These artificial sensors return semantic information about the detected entities.
They return the actual instance of the entity detected, which allow to access their attributes.
E.g. position, velocity, mass, shape can be accessed.
"""
import math
import numpy as np
import cv... |
import datetime
import sys
import threading
import time
import serial.threaded
from redis import Redis
from config.settings.base import env
import random
from .models import Node
from .models import Message as MessageModel
class Message(object):
"""
Messages Object
"""
def __init__(self, address: s... |
from collections import defaultdict
import numpy as np
import random
import tokenization
class Example(object):
def __init__(self, doc_key, tokens, sentence_tokens, gold_starts, gold_ends, speaker_ids, cluster_ids, genre, document_index,
offset=0, bert_to_orig_map=None):
assert len(toke... |
import warnings
import math
import numpy as np
import pandas as pd
from scipy.stats import norm
# Create custom warning: Value
class ValueWarning(UserWarning):
pass
# Create custom warning: Convergence
class ConvergenceWarning(UserWarning):
pass
def get_significance(proba):
if proba < 0.001:
ret... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... |
# dijkstra.py
# From Classic Computer Science Problems in Python Chapter 4
# Copyright 2018 <NAME>
#
# 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... |
# Copyright 2018-2021 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... |
#!/usr/bin/env python3
import fiolib.supporting as supporting
def get_dataset_types(dataset):
dataset_types = {'rw': set(), 'iodepth': set(), 'numjobs': set()}
operation = {'rw': str, 'iodepth': int, 'numjobs': int}
for x in dataset_types.keys():
for y in dataset:
dataset_types[x].add... |
from io import StringIO
import tensorflow as tf
from tensorflow.contrib.learn.python import learn
def conv_layer(x, filters, size, activation,
name=None, bias=True, reg_scale=None, board=None):
reg = None if reg_scale is None else tf.contrib.layers.l2_regularizer(scale=reg_scale)
conv = tf.la... |
# Copyright 2018 AT&T Intellectual Property. All other 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... |
import hashlib
from sawtooth_sdk.processor.exceptions import InternalError
import json
import ast
SOCE_NAMESPACE = hashlib.sha512("soce".encode("utf-8")).hexdigest()[0:6]
def _make_soce_address(name):
return SOCE_NAMESPACE + \
hashlib.sha512(name.encode('utf-8')).hexdigest()[:64]
class Voter:
def _... |
"""
Methods used to convert/handle raw input data
"""
import os
import json
import h5py
import numpy as np
import csv
import execnet
def init_obj_catalogue(path_to_data):
obj_dict = {}
subfols = sorted(os.listdir(os.path.join(path_to_data, 'test-item-data')))
known_classes = sorted(os.listdir(os.path.joi... |
from gevent import monkey
# need to patch sockets to make requests async
monkey.patch_all(subprocess=False)
from jumpscale import j
import click
import logging
from Jumpscale.logging.Handlers import TelegramHandler
from Jumpscale.logging.Handlers import TelegramFormatter
from zerorobot.robot import Robot
telegram_... |
from collections import namedtuple
import numpy as np
Coord = namedtuple('Coord', ['y', 'x'])
INPUT_DEPTH = 8103
INPUT_TARGET = Coord(x=9, y=758)
TEST_DEPTH = 510
TEST_TARGET = Coord(x=10, y=10)
ROCKY = 0
WET = 1
NARROW = 2
NEITHER = 0
TORCH = 1
CLIMBGEAR = 2
SWITCH_COST = 7
def output_field(e_field):
def _... |
import tkinter
import random
def load_cards(card_images):
suits = ['heart', 'diamond', 'spade', 'club']
faces = ['jack', 'queen', 'king']
for suit in suits:
for card in range(1, 11):
name = f'cards/{str(card)}_{suit}.png'
image = tkinter.PhotoImage(file=name)
... |
import locale
import logging
import pathlib
import random
import re
from bs4 import BeautifulSoup
class ScrapeResult:
def __init__(self, r):
self.alert_subject = None
self.alert_content = None
self.price = None
self.soup = BeautifulSoup(r.text, 'lxml')
self.content = self.... |
import utils
from utils import digitutils as dutils
import ANN as ann
import os
import numpy as np
import matplotlib.pyplot as plt
from multiprocessing import Pool
import cv2
network_model = """
{
"input_shape" : [28,28,1],
"layers" : [
{
"type" : "Conv2D",
"units" : 16,
... |
# Import the libraries we need to use in this lab
# Using the following line code to install the torchvision library
# !conda install -y torchvision
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as dsets
import matplotlib.pylab as plt
import numpy as np
de... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
###
# Copyright (2016-2019) Hewlett Packard Enterprise Development LP
#
# 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/licen... |
#!/usr/bin/env python3
from __future__ import print_function
import json
from bidi.algorithm import get_display
import time
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
... |
import numpy as np
import numpy.linalg as la
import subprocess as sub
import itertools as itt
import sys
import time
import uuid
from pathlib import Path
from .Fragments import Fragments
from .Potential import *
from .MBE_Potential import MBE_Potential
from .read_geometries import read_geoms
class Constants:
"""He... |
#!/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... |
# https://github.com/scikit-learn/scikit-learn/blob/ab93d65/sklearn/metrics/classification.py # NOQA
# slightly modified to report weighted, macro, and micro averages in one go.
def classification_report(
y_true, y_pred, labels=None, target_names=None,
sample_weight=None, digits=2):
"""Build a te... |
import sys
import re
import logging
# Hold information about a single instruction.
# Also store additional information about allowed kinds of instructions.
class instruction:
def __init__ (self, instr_number, inst, op0, op1, op2):
self.instr_number = instr_number
self.inst = inst
# self.... |
from collections import Counter
import numpy as np
import torch
from scipy.spatial.distance import cosine
from torch import optim
from torch.utils.data import DataLoader
from WordEmbeddingDataset import WordEmbeddingDataset
from torchsummary import summary
def find_train_nearest(word):
if word not in train_voc... |
from spikeinterface.core import BinaryRecordingExtractor, BaseRecordingSegment, BaseSorting, BaseSortingSegment
from spikeinterface.core.core_tools import write_binary_recording
from probeinterface import read_prb, write_prb
import json
import numpy as np
from pathlib import Path
try:
import pandas as pd
HAV... |
# Copyright 2020 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... |
#!/usr/bin/env python3
import os
import re
import sys
import glob
import subprocess
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt
def prepare(args):
'''Generates input files used to evaluate the Count-Min Sketch.
By default creates `20` input files with `10M` value... |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from __future__ import print_function # For printing no newline
import sympy
from sympy import Rational
from sympy import factorial
import numpy as np
def Taylor( n, dx ):
"""Compyute n terms in the Taylor expansion for a function centered 'dx'
away from where the terms will be evaluated."""
return [ (d... |
###############################
# Import Python modules
###############################
import os, sys, datetime, inspect
###############################
# Import SCAPY and ASN1 modules
###############################
from pyasn1.codec.ber import decoder
from pyasn1.codec.ber import encoder
from pyasn1.type import cha... |
# encoding: utf-8
from __future__ import annotations
import datetime as _datetime
from typing import Generic, Optional, Type, TypeVar
import sqlalchemy
from typing_extensions import Self
import ckan.model
import ckan.model.meta as meta
import ckan.model.core as core
import ckan.model.domain_object as domain_object
... |
# -*- coding: utf-8 -*-
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# 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 require... |
import functools
from dataclasses import dataclass
from datetime import datetime
from typing import (
Dict,
List,
)
from tri_token import (
Token,
TokenAttribute,
TokenContainer,
)
DEFAULT_TIME = datetime(2001, 1, 1)
def get_time(*, identifier: str):
from .models import SystemTime
try:
... |
import weakref
from abc import ABCMeta, abstractmethod
from .progress import ProgressManager, ProcessorProgressLogger
from ..pagination import PaginationEventHandler
class BulkProcessingFailed(Exception):
pass
class BaseDocProcessor(metaclass=ABCMeta):
"""Base class for processors that get passed"""
... |
import datetime
from django.conf import settings
from django.core.cache import cache
from django.utils.cache import cc_delim_re, _i18n_cache_key_suffix
from django.utils.encoding import iri_to_uri
from django.utils.hashcompat import md5_constructor
from email.Utils import parsedate
def _generate_cache_he... |
import requests
import base64
import re
import os
import datetime
import random
import tensorflow as tf
import tensorflow_text
import numpy as np
import pandas as pd
import tweepy
import plotly.graph_objects as go
print("Imports done")
auth = tweepy.OAuthHandler(os.environ.get('API_KEY'), os.environ.get('API_SECRET... |
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
import re
import argparse
from typing import NamedTuple
from subprocess import TimeoutExpired
import logging
from monitor_job import monitor_job, JobFailedError
BaseHeapSize = NamedTuple('JavaHeapSize', [('value', int), ('suffix', str)])
class HeapSize(Bas... |
# ----- Imports ----- #
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
import shutil
import os
# ----- Functions and procedures ----- #
def get_dir_name(entry):
dir_name = filedialog.askdirectory(initialdir=os.getcwd(), title='Please select a director... |
from pytermfx.constants import *
from pytermfx.color import Color, ColorMode
from pytermfx.adaptors.base import BaseAdaptor
from pytermfx.adaptors.input import InputAdaptor
from pytermfx.adaptors.vt100 import VT100Adaptor
from threading import Thread
from time import sleep
from ctypes import windll, Structure, byref
fr... |
"""
The MIT License (MIT)
Copyright (c) 2016 https://github.com/gradescope/gradescope-utils
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the ri... |
r"""UUID draft version objects (universally unique identifiers).
This module provides the functions uuid6() and uuid7() for
generating version 6 and 7 UUIDs as specified in
https://github.com/uuid6/uuid6-ietf-draft.
"""
import secrets
import time
from typing import Tuple
from uuid import UUID
class DraftUUID(UUID):
... |
# Classes and Objects - Basics
print ("Basic Class")
class MyClass:
pass
obj = MyClass() # creating a MyClass object
print (obj)
print ("\nEmployee Class")
class Employee:
Id = None
salary = None
department = None # compile errors without None
Steve = Employee()
print ("\nProperty outside the Class ... |
import math
import torch
from torch.nn import Module, Parameter
import torch.nn.init as init
import torch.nn.functional as F
class _BayesBatchNorm(Module):
r"""
Applies Bayesian Batch Normalization over a 2D or 3D input
Arguments:
prior_mu (Float): mean of prior normal distribution.
prio... |
from __future__ import print_function
from operator import mul as mul_op
from functools import reduce
from random import choice
import pandas as pd
def random_chooser():
while True:
values = yield
yield choice(values)
def random_grid(params, n=60, grid_cache=None, skip_config=None):
if not ... |
import os.path
from datetime import datetime
from .context import hwinfo_grapher as grapher
def test_parse_csv():
json = grapher.parse_csv(os.path.join(
os.path.dirname(__file__), 'data.csv'))
assert len(json) == 10
assert list(json[0].keys()) == ['Date', 'Time',
... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import time_utils
from datetime import datetime
import uuid
import json
import cassandra_types
from cassandra_types import CqlType
from decimal import Decimal
def get_cql_type_from_validator(validator):
if validator.startswith('frozen<tuple<'):
types = validator[13:-2].split(',')
sub_types = []
... |
import ply.lex as lex
# resultado del analisis
resultado_lexema = []
reservada = (
# Palabras Reservadas
'PALABRA_RESERVADA',
'PALABRA_RESERVADA_VARI',
'INCLUDE',
'USING',
'NAMESPACE',
'STD',
'COUT',
'CIN',
'GET',
'CADENA',
'RETURN',
'VOID',
'INT',
'ENDL',
)
toke... |
# This source code is part of the Biotite package and is distributed
# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further
# information.
__name__ = "biotite.structure.info"
__author__ = "<NAME>"
__all__ = ["vdw_radius_protor", "vdw_radius_single"]
from .bonds import bonds_in_residue
# Contains tup... |
"""
Various utilities used by the rest of the package.
"""
from collections import Counter, defaultdict
import datetime
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, List, Mapping, Optional, Set, Tuple
class FilePosition:
"""
A position within the file which can be upd... |
# -*- coding: utf-8 -*-
###############################################################################
# This source file is part of the Tomviz project, https://tomviz.org/.
# It is released under the 3-Clause BSD License, see "LICENSE".
###############################################################################
... |
import numpy as np
def imresize(img, height, width, inter='nn'):
"""
Function which resizes image.
Args:
image
height
width
inter
Ret:
Resized image.
"""
assert inter in ['nn', 'bilinear', 'bicubic'], 'Invalid interpolation'
# extract old image dim... |
import numpy as np
import pandas as pd
import os
import multiprocessing
from multiprocessing import Pool, Manager
import time
from maxatac.utilities.genome_tools import build_chrom_sizes_dict, get_bigwig_stats
from maxatac.utilities.system_tools import get_dir
from maxatac.utilities.threshold_tools import import_blackl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from codegen.mir import *
from codegen.passes import *
def iter_inst_range(begin: MachineInstruction, end: MachineInstruction):
bb = begin.mbb
idx = bb.insts.index(begin)
while idx < len(bb.insts) and bb.insts[idx] != end:
yield bb.insts[idx]
... |
"""
*****
Pajek
*****
Read graphs in Pajek format.
This implementation handles directed and undirected graphs including
those with self loops and parallel edges.
Format
------
See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
for format information.
"""
# Copyright (C) 2008-2011 by ... |
from typing import TYPE_CHECKING, Any, Dict, Optional, Union
from bson import Code
if TYPE_CHECKING:
from pydantic.typing import DictStrAny
__all__ = ["Query", "q"]
def q(*args: Any, **kwargs: Any) -> "Query":
"""Creates a MongoDB query from the specified arguments.
The query can be used to filter doc... |
# -*- coding: utf-8 -*-
import base64
import urlparse
import uuid
from datetime import datetime
from flask import render_template, url_for, make_response, session, request, jsonify
from flask.ext.login import current_user, login_user
from flask.ext.restful import abort
from werkzeug.security import generate_password_h... |
import os
from typing import Tuple, Union
import urllib.parse
import boto3
import botocore
from astromech.logging import logger
_client = None
"""A boto S3 client, initialized lazily by `client()`.
The client object is global, so that it gets reused between invocations by the lambda
function container.
Do not use ... |
#!/usr/bin/python
"""
Author: <NAME>
Date: 2018-01-02
Purpose: Create a tar of the specified folder and store it in the specified location. Retain the specified number of
records.
"""
import argparse
import datetime
import glob
import os
import pathlib
import pwd
import subprocess
def log(path_log, message):
""... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import re
import math
from indicators import *
from functions import *
result_count = 0
result_files = 0
# Compute a Shannon entropy for a string based on an iterator
def shannon_entropy(data, iterator):
"""
Borrowed from http://blog.dkbza.org/2007/05/scanni... |
import torch
import torch.nn as nn
import pytorch_lightning as pl
import torchmetrics
from torch.functional import F
from torch.utils.data import Dataset, DataLoader
from transformers import MT5EncoderModel, MT5Tokenizer
class CustomDataset(Dataset):
def __init__(self, first_cul: list, targets: list, tokenizer, ... |
# -*- coding: utf-8 -*- #
"""*********************************************************************************************"""
# FileName [ pretrain/mockingjay/task.py ]
# Synopsis [ Masked Acoustic Model data processing for pre-training the transformer model ]
# Author [ <NAME> (https://github.com/a... |
# Copyright 2021 The HuggingFace Team, Amazon.com, Inc. or its affiliates. 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-... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
class Tests:
creation_undo = (
"UNDO Entity creation success",
"UNDO Entity creation failed... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import re
import time
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile
import collections
def create_image_lists(image_dir):
if not tf.comp... |
import torch
import argparse
import numpy as np
from train import train
from pdb import set_trace
import dataset
import tensorflow as tf
from run_test import *
def normalize_state(obs):
obs_highs = env.observation_space.high
obs_lows = env.observation_space.low
#print(obs_highs)
#print(obs_lows)
#... |
#!/usr/bin/env python
import json
import shutil
import tempfile
from pathlib import Path
from extractor import SupportMatrixExtractor, managed_container
import docker
IMG = "python:3.8-buster@sha256:ccc66c06817c2e5b7ecd40db1c4305dea3cd9e48ec29151a593e0dbd76af365e"
DATAJSON = Path(__file__).parent / "fixtures" / "d... |
# -*- coding: utf-8
from __future__ import unicode_literals
import six
import unittest
from nose.tools import eq_, raises
from slugify import slugify, smart_text, SLUG_OK
u = 'Ελληνικά'
def test_slugify():
x = '-'.join([u, u])
y = ' - '.join([u, u])
@raises(ValueError)
def test_incoherent_ok_and_on... |
from django.db import models
from datasets.models import Dataset, Document, Term
from models.models import ArtmModel, Topic
from django.contrib.auth.models import User
from datetime import datetime, timedelta
import json
from random import randint
from django.conf import settings
import importlib
import algo.assessmen... |
import numpy as np
from copy import deepcopy
from models.linear_model import LinearModel
from models.simplex_solver import SimplexSolver
from models.function import ObjectiveFunction, Constraint
from models.variable import SlackVariable, ArtificialVariable, Variable
class InfeasibleError(Exception):
pass
class ... |
# (c) <NAME>. GPL licensed, see LICENSE.rst.
# -*- coding: utf-8 -*-
from pathlib import Path
import logging
from configparser import ConfigParser
from typing import Dict, List
import sqlite3
from threedi_settings.mappings import get_sqlite_table_schemas, SettingsTables
logger = logging.getLogger(__name__)
class T... |
import warnings
from ctypes import cdll, c_int, POINTER, c_float, create_string_buffer, c_double
import numpy as np
from kheppy.core.constants import KHEPERA_LIB
class Simulation:
"""
Python wrapper for shared object/DLL interface of simulation engine available at
https://github.com/Ewande/khepera
... |
from datetime import datetime
import os
import glob
import re
from hotsos.core.log import log
from hotsos.core.config import HotSOSConfig
from hotsos.core.host_helpers import CLIHelper
from hotsos.core.utils import sorted_dict
SVC_EXPR_TEMPLATES = {
"absolute": r".+\S+bin/({})(?:\s+.+|$)",
"snap": r".+\S+\d+... |
#!/usr/bin/env python3
import gi
import os
import re
gi.require_version("Gtk", "3.0")
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk, AppIndicator3
SHOW_GRUB_MENU_SUB_MENUS = True
DEVELOPMENT_MODE = False
icon_name = "un-reboot"
def get_grub_entries():
"""
Builds JSON from grub me... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-,
from __future__ import absolute_import
from __future__ import print_function
import logging
logger = logging.getLogger("xAH.utils")
import json
import os
import random
import re
import ROOT
class NameGenerator(object):
adjectives = None
animals = None
def __init__(... |
import argparse
import datetime
import internal.gni.py2bridge as py2bridge
from internal.util.printer import *
import internal.util.fs as fs
import internal.util.location as loc
import internal.util.ui as ui
from reservation import GENINode, GENIReservationProfile, GENIReservationRequest
'''CLI module to start a clu... |
# Copyright 2019-2022 The ASReview 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 appl... |
import json
import os
from pathlib import Path
import subprocess
import sys
import pytest
import requests
import ray
from ray import serve
from ray.tests.conftest import tmp_working_dir # noqa: F401, E501
from ray.dashboard.optional_utils import RAY_INTERNAL_DASHBOARD_NAMESPACE
@pytest.fixture
def ray_start_stop()... |
import pandas as pd
import numpy as np
import colorama
from colorama import Fore, Style
from tabulate import tabulate
def meta(train,test,missing_values = -1,cols_ignore_missing = []):
df = pd.concat([train,test]).reset_index(drop=True).fillna('未知')
data = []
for col in df.columns:
# 定义role
... |
# -*- coding: utf-8 -*-
import wx.lib.masked.timectrl
from datetime import datetime
from src.ui import MedFont, DatetimeWxToPy, DatetimePyToWx
class Field(object):
def __init__(self, default):
self._setup = False
self._Default = default
def Setup(self, parent, sizer, column, label, entryWidget):
self._entr... |
import multiprocessing as mp
import time
import numpy as np
from functools import wraps
from hyperopt import fmin, tpe, STATUS_OK, STATUS_FAIL, hp
from hyperopt.mongoexp import MongoTrials
from tqdm import tqdm
from script.sklearn_like_toolkit.param_search.HyperOpt.FreeTrials import FreeTrials
from script.util.... |
#!/usr/bin/env python3
"""Run the addon."""
import asyncio
import logging
import sys
from asyncio.events import AbstractEventLoop
from json import loads
from math import modf
from pathlib import Path
from typing import Dict, List
import attr
from filter import Filter, getfilter, suggested_filter
from mqtt import MQTTC... |
#!/usr/bin/python3
# Usage: ./comps-sync.py /path/to/comps-f37.xml.in
#
# Can both remove packages from the manifest
# which are not mentioned in comps, and add packages from
# comps.
import os, sys, subprocess, argparse, shlex, json, yaml, re
import libcomps
def fatal(msg):
print >>sys.stderr, msg
sys.exit(1... |
# Copyright (c) ZenML GmbH 2022. 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... |
# Copyright (c) 2015 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to the S... |
from grapheneapi.graphenewsrpc import GrapheneWebsocketRPC
import threading
from websocket import create_connection
import json
import time
import logging
log = logging.getLogger("grapheneapi.steemnoderpc")
class RPCError(Exception):
pass
class NoAccessApi(Exception):
pass
class SteemNodeRPC(GrapheneWebso... |
import numpy as np
import scipy as sp
import os, sys
import gzip, pickle
def wrap_coords(path,params):
"""
inputs:
path: path to save input files
params : dictionary with parameters, including:
topo: topography case
ncol: across slope number of cells
nrow: along slop... |
#!/usr/bin/env python3
# coding: utf-8
# vim: set ts=4 sts=4 sw=4 expandtab cc=80:
# Copyright (c) 2014, 2016, chys <<EMAIL>>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions... |
import logging
import os
import threading
import time
import traceback
from . import rate_limit
NUM_TWEETS_PER_CHECK = 10 # How many tweets are retrieved in a single check
class TweetListenerThread(threading.Thread):
def __init__(self, bot, rate_limit_manager, storage):
threading.Thread.__init__(self)
... |
from typing import Union
import numpy as np
import pandas as pd
import scipy.stats as stats
from sklearn.ensemble import IsolationForest
from sklearn.svm import OneClassSVM
from sklearn.preprocessing import StandardScaler
from src.decomposition.seasonal import BaseDecomposition
def detect_outlier_sd(ts, sd_multiple=2... |
import numpy as np
class AdditiveLoss:
def valid_stats(self, stats):
pass
def leaf_predicts(self, stats):
pass
def node_weight(self, stats):
return stats[0]
def score(self, left_stats, right_stats):
pass
def pretty_str(self, stats) -> str:
pass
class M... |
# -*- coding: utf-8 -*-
import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from rllite.common import ReplayBuffer4
from tensorboardX import SummaryWriter
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
clas... |
import os
import time
from tricks import *
from ai import *
from config import *
if productive:
from gevent import monkey
monkey.patch_all()
from bottle import route, run, static_file, request, BaseRequest
import base64
import re
import cv2
import datetime
BaseRequest.MEMFILE_MAX = 10000 * 1000
pather_text = o... |
import pytorch_lightning as pl
import torch
from torch import nn as nn
from torch.nn import functional as F
from dltranz.lightning_modules.AbsModule import ABSModule
from dltranz.seq_encoder.rnn_encoder import RnnSeqEncoder
from dltranz.trx_encoder import PaddedBatch
class CPC_Loss(nn.Module):
def __init__(self,... |
from discord.ext import commands
import os
import sqlite3
from pretty_help import PrettyHelp
import discord
import random
intents = discord.Intents.default()
intents.members = True
db = sqlite3.connect('database.db')
bot = commands.Bot(command_prefix='-!', help_command=PrettyHelp(), intents=intents)
blacklist = [" nig... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.