id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3335108 | import os
import re
import ftfy
import numpy as np
from more_itertools import unique_everseen
def preprocess(text: str):
# normalize non UTF-8 characters to their matching UTF-8 ones
text = ftfy.fix_text(text)
text = text.replace("\n", " ")
# remove redundant whitespaces
text = re.sub(r" +", "... |
3335148 | from keras.layers import Conv2D, AveragePooling2D, UpSampling2D
from keras.layers import add
def initial_octconv(ip, filters, kernel_size=(3, 3), strides=(1, 1),
alpha=0.5, padding='same', dilation=None, bias=False):
"""
Initializes the Octave Convolution architecture.
Accepts a singl... |
3335173 | import random as r
characters = [str(el) for el in list(range(100))]
def gen_el():
return r.choice(characters)
def gen_op():
operators = ['+','-','\\cdot']
return ' '+r.choice(operators)+' '
def gen_power():
return r.choice(characters)+'^'+r.choice(characters)
def gen_frac():
args_top = r.randi... |
3335240 | from .skill_builder.inoft_skill_builder import InoftSkill, InoftCondition, InoftHandler, \
InoftRequestHandler, InoftStateHandler, InoftDefaultFallback, InoftHandlersGroup, canProcessIntentNames
from .platforms_handlers.simulator.simulator_core import Simulator
from .speechs.ssml_builder_core import Speech, Speech... |
3335267 | from setup import *
from pyglet_gui.manager import Manager
from pyglet_gui.document import Document
from pyglet_gui.theme import Theme
theme = Theme({"font": "Lucida Grande",
"font_size": 12,
"text_color": [255, 255, 255, 255],
"gui_color": [64, 64, 64, 255],
... |
3335285 | import random, sys, string
import simplejson as json
filename = sys.argv[1]
key = sys.argv[2]
def randstring(n):
return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(n))
jsonlist = []
with open(filename, "r") as f:
jsonlist = json.loads(f.read())
## create list of unique value... |
3335305 | from django.db import models
# Create your models here.
# 用户表
class UseInfo(models.Model):
name = models.CharField(max_length=128, unique=True, verbose_name='用户名')
password = models.CharField(max_length=128, verbose_name='密码')
email = models.CharField(max_length=128, verbose_name='邮箱')
def __str__(sel... |
3335314 | from __future__ import (
annotations,
)
from typing import (
Any,
Iterable,
Optional,
Union,
)
from minos.common import (
classname,
)
from ...context import (
SagaContext,
)
from ...exceptions import (
EmptySagaStepException,
MultipleOnErrorException,
MultipleOnExecuteExcepti... |
3335320 | import json
def sanitize_json(json_dict, max_item_length=100):
"""Sanitizes json objects for safe storage in Postgres
"""
if json_dict is None:
return None
returned = json.dumps(json_dict)
returned = returned.replace('\\u0000', '\\\\x00')
returned = json.loads(returned)
for key, v... |
3335341 | import argparse
import ast
from design_search import make_graph, build_normalized_robot
from matplotlib.patches import ConnectionPatch
import matplotlib.pyplot as plt
import pandas as pd
import pyrobotdesign as rd
from results import get_robot_image
import seaborn as sns
import tasks
def main():
parser = argparse.Ar... |
3335388 | import datetime
from django.db import models
from django.conf import settings
#from django.contrib.auth.models import User
from django import forms
from urlweb.shortener.baseconv import base62
class Link(models.Model):
"""
Model that represents a shortened URL
# Initialize by deleting all Link objects
... |
3335451 | import os
import tempfile
import unittest
from AnyQt.QtWidgets import QGraphicsScene, QGraphicsRectItem
from Orange.widgets.tests.base import GuiTest
from Orange.widgets import io as imgio
@unittest.skipUnless(hasattr(imgio, "PdfFormat"), "QPdfWriter not available")
class TestIO(GuiTest):
def test_pdf(self):
... |
3335453 | import pytest
import inspect
from ipaddress import IPv4Address, IPv4Network
from prettytable import PrettyTable
import numpy as np
from CybORG import CybORG
from CybORG.Shared.Actions import Remove
from CybORG.Shared.Enums import TrinaryEnum
from CybORG.Agents.SimpleAgents.B_line import B_lineAgent
from CybORG.Agents... |
3335491 | import math
import numpy as np
import multiprocessing
"""
Stochastic bit-streams are represented as NumPy arrays. Multi-dimensional arrays
are used to encode numerical vectors and matrices.
"""
def scalar_next_int_power_of_2(x):
"""
Return the next integer power of 2 of x
"""
# return 1<<(int(math.... |
3335493 | import os
import sys
from pathlib import Path
from taskit.application.coordinators.admin_coordinator import (
AdminCoordinator)
from taskit.application.coordinators.agenda_coordinator import (
AgendaCoordinator)
from taskit.infrastructure.data.json.repositories.project_repository import (
JsonProjectReposit... |
3335495 | import pandas as __pd
import datetime as __dt
from multiprocessing import Pool as __Pool
import multiprocessing as __mp
from functools import reduce as __red
import logging as __logging
from seffaflik.__ortak.__araclar import make_requests as __make_requests
from seffaflik.__ortak import __dogrulama as __dogrulama
fro... |
3335505 | series = [0,1]
for i in range(2, 50):
x = series[i-1] + series[i-2]
series.append(x)
print(str(series).lstrip("[").rstrip(']'))
|
3335524 | from subprocess import Popen
from typing import List
from typing import Optional
from typing import Union
import itertools
import os
import os.path
import pytest
import unittest
import sys
IBCOMM_INVALID_ARGUMENT = 1
IBCOMM_IBVERBS_ERROR = 2
IBCOMM_CUDA_ERROR = 3
IBCOMM_NOT_SUPPORTED = 4
ALGO_RING = "ring"
ALGO_RABE... |
3335584 | import torch
from torch import optim
import math
class LambdaBatch(object):
"""Sets the learning rate of each parameter group to the initial lr
times a given function. When last_epoch=-1, sets initial lr as lr.
Args:
optimizer (Optimizer): Wrapped optimizer.
lr_lambda (function or list): ... |
3335599 | from setuptools import setup, find_packages
packages = ['pbgpp.' + pkg for pkg in find_packages('pbgpp')]
packages.append('pbgpp')
setup(
name='pbgpp',
version='0.2.22',
description='PCAP BGP Parser',
author='DE-CIX Management GmbH',
author_email='<EMAIL>',
url='https://github.com/de-cix/pbgp-... |
3335617 | from os.path import join, realpath
import sys; sys.path.insert(0, realpath(join(__file__, "../../")))
import logging; logging.basicConfig(level=logging.ERROR)
import unittest
from unittest.mock import MagicMock
from decimal import Decimal
from hummingbot.strategy.spot_perpetual_arbitrage.arb_proposal import ArbProposa... |
3335665 | import os
if "PYCTDEV_ECOSYSTEM" not in os.environ:
os.environ["PYCTDEV_ECOSYSTEM"] = "pip"
from pyctdev import * # noqa: api
########## DOCS ##########
def task_build_docs():
"""build docs"""
return {
'actions': [
'nbsite generate-rst --org pyviz-dev --repo nbsite --skip ".*sites.*... |
3335678 | from setuptools import setup, find_packages
setup(
name = 'feelvos',
version = '0.5',
description = 'FEELVOS implementation in PyTorch; FEELVOS: Fast End-to-End Embedding Learning for Video Object Segmentation',
author = '<NAME>',
author_email = '<EMAIL>',
ins... |
3335691 | import os
import time
import copy
import random
import logging
import itertools
import ipdb as pdb
import numpy as np
import torch
import torch.optim.lr_scheduler
from torch.nn.utils.clip_grad import clip_grad_norm
from allennlp.common import Params
from allennlp.common.checks import ConfigurationError
from allennlp.... |
3335695 | from io import BytesIO
from scapy.all import Ether, PcapWriter, Packet, IP, UDP, TCP, DNS, DNSQR, DNSRR
from scapy.layers.http import HTTPRequest, HTTP
from typing import List
from beagle.datasources.pcap import PCAP
def packets_to_datasource_events(packets: List[Packet]) -> PCAP:
f = BytesIO()
PcapWriter(f).... |
3335726 | import warnings
warnings.warn("the icekit.utils.admin module is deprecated. Use icekit.admin_tools.* instead.", DeprecationWarning,
stacklevel=2)
|
3335759 | from itertools import cycle
import numpy as np
from adapt.strategy.strategy import Strategy
class DLFuzzRoundRobin(Strategy):
'''A round-robin strategy that cycles 3 strategies that suggested by DLFuzz.
DLFuzz suggest 4 different strategy as follows:
* Select neurons that are most covered.
* Select neurons... |
3335785 | import pyOcean_cpu as ocean
import pyOceanNumpy
import numpy as np
a = np.asarray(range(24)).reshape(4,6)
print(a)
b = a[0:3,:]
c = a[1:4,:]
print(b)
print(c)
s = ocean.asTensor(b)
t = ocean.asTensor(c)
print(s)
print(t)
t.storage.copy(s.storage)
print(t)
|
3335794 | import requests
import random
import time
import gzip
import utils.config_handler
import api_modules.utils
def test_curl(request):
if not(request.json): return "NO JSON Post !", 400
mydata = request.json
if not('url' in mydata): return "Must specify url", 400
if not('method' i... |
3335827 | import re
from scipy.spatial import distance as ssd
from decibel.music_objects.chord import Chord
from decibel.music_objects.chord_vocabulary import ChordVocabulary
from decibel.music_objects.fingering import Fingering
from decibel.music_objects.interval import Interval
from decibel.music_objects.pitch_class import P... |
3335832 | from datetime import datetime
from modules import compare
from modules import file_io
from modules import stats
from modules.scraper import Scraper
from modules.utils import ask_input, ask_multiple_option
groups = ['followers', 'following']
# Ask for input
target = ask_input('Enter the target username: ')
group = a... |
3335869 | from canvas.core.courses import get_courses
import canvas.core.api as api
terms = ['2017-2SU']
programs = ['NFNPO', 'NCMO']
synergis = True
for course in get_courses(terms, programs, synergis, []):
print(course['sis_course_id'])
req_data = {'course[end_at]': '2017-08-21T23:59:59-07:00', 'course[res... |
3335881 | from astLib import astWCS, astCoords
import liteMap as lm
import time
import sys
def downWriteMap(fname):
nowMap = lm.liteMapFromFits(fname)
lowTemp = lm.getEmptyMapWithDifferentDims(nowMap,int(nowMap.Ny/2.),int(nowMap.Nx/2.))
lowMap = lm.resampleFromHiResMap(nowMap, lowTemp)
lowMap.writeFits(fname[:-... |
3335908 | import os, shutil, tarfile
import json
from google.cloud.storage import Blob
# delete directory
def remove_dir(path):
for the_file in os.listdir(path):
file_path = os.path.join(path, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.... |
3335932 | from .parameters import Parameters
class ParametersDomainAncillaries(Parameters):
"""Mixin to collect named parameters and domain ancillaries.
.. versionadded:: (cfdm) 1.7.0
"""
def __init__(
self, parameters=None, domain_ancillaries=None, source=None, copy=True
):
"""**Initiali... |
3335955 | import sys
from helpfuncs import translateR
from inverse import inv
# parse spatial CSP and fill in the constraint matrix
def parsecsp(ConMatrix):
while True:
# assure not interrupted parsing
try:
line = sys.stdin.readline()
except KeyboardInterrupt:
break
if n... |
3335964 | class Node :
def __init__ (self, data ) :
self.data = data
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
# Insert a node at the beginning
def InsertAtBeg(self , value):
newNode = Node(data = value)
newN... |
3335972 | import zmq
from zmq.eventloop import ioloop, zmqstream
import urwid
from gviewer import AsyncDataStore, GViewer, BaseDisplayer, DisplayerContext, Config
from gviewer import Text, Group, View
ioloop.install()
CHANNEL = "tcp://127.0.0.1:5581"
class Displayer(BaseDisplayer):
def summary(self, message):
re... |
3335973 | import os
from unittest.mock import patch, call
import pytest
from dev.tasks.pypi import Pypi
@patch('dev.tasks.pypi.os.environ')
@patch('dev.tasks.pypi.run_command')
def test_up(run_command_mock, environ_mock):
environ_mock.get.return_value = 'abc'
Pypi('upload', extra_args=[])
run_command_mock.asser... |
3336023 | from aiohttp_admin2.views import ControllerView
from .controllers import MoviesController
class MoviesPage(ControllerView):
controller = MoviesController
|
3336062 | from . import architectures
from . import annotation_setters
from . import span_getters
from .layers import TransformerModel
from .pipeline_component import Transformer, install_extensions
from .data_classes import TransformerData, FullTransformerBatch
from .util import registry
__all__ = [
"install_extensions",
... |
3336088 | from director import task
@task(name="TASK_A")
def task_a(*args, **kwargs):
return "task_a"
@task(name="TASK_B")
def task_b(*args, **kwargs):
return "task_b"
@task(name="TASK_C")
def task_c(*args, **kwargs):
return "task_c"
|
3336104 | import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.nn.functional as F
from config import configurations
from backbone.model_resnet import ResNet_50, ResNet_101, ResNet_152
from backbone.model_irse import IR_50,... |
3336122 | import sys
fn_doc = sys.argv[1]
fn_sum = sys.argv[2]
fn_ref = sys.argv[3]
opt = sys.argv[4]
def truncate(ldoc, lref, lsum, special_tokens=4):
ndoc = len(ldoc.strip().split())
nref = len(lref.strip().split())
nsum = len(lsum.strip().split())
if special_tokens == 4:
final = min(512 - nsum - s... |
3336132 | import numpy as np
import torch
from diffusion_model import DiffusionModel
import torch.nn.functional as F
import torch.optim
from torch.utils.tensorboard import SummaryWriter
import os
import matplotlib.pyplot as plt
import configargparse
torch.set_num_threads(2)
device = torch.device('cpu')
torch.set_default_dtype(t... |
3336139 | import string
from sklearn.feature_extraction import stop_words
from nltk.stem import WordNetLemmatizer
def lem(words):
"""Returns list of lemmas from argument list of words."""
wordnet_lemmatizer = WordNetLemmatizer()
lem_sentence = []
for word in words:
lem_sentence.append(wordnet_lemmatizer... |
3336217 | from setuptools import setup
version = {}
with open("src/datadog_cloudformation_common/version.py") as fp:
exec(fp.read(), version)
setup(
version=version["__version__"]
)
|
3336238 | import discord
async def help(ctx):
embed = discord.Embed()
embed.set_author(name="Help")
embed.add_field(name="Slash Commands",
value="Press / to view all the available commands", inline=False)
embed.add_field(name="Bot not muting everyone?",
value="Ask ever... |
3336272 | import shutil
import pandas as pd
from tabulate import tabulate
def get_terminal_size():
return shutil.get_terminal_size().columns
def show_pos_merge_position(self, df, first_df):
if "Strand" in df:
pos = df.Chromosome.astype(str) + " " + df.Start.astype(
str) + "-" + df.End.astype(s... |
3336280 | import re
from typing import Iterable, List
# delimters mostly copied from:
# https://github.com/kermitt2/delft/blob/v0.2.6/delft/utilities/Tokenizer.py
# and:
# https://github.com/kermitt2/grobid/blob/0.6.2/grobid-core/src/main/java/org/grobid/core/utilities/TextUtilities.java#L773-L948
# added: `@`, `#`, `\u2020`, ... |
3336312 | from lupin.fields.compatibility import merge_validator
from lupin.validators import Equal
from lupin.errors import ValidationError
import pytest
@pytest.fixture
def invalid():
return Equal("sernine")
@pytest.fixture
def valid():
return Equal("lupin")
class TestMergeValidator(object):
def test_add_vali... |
3336319 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from yacs.config import CfgNode as CN
__C = CN()
cfg = __C
__C.META_ARC = "hdn_r50_l234"
__C.CUDA = True
#-----------------------------------------------------------... |
3336320 | import requests
from bs4 import BeautifulSoup
import os
import re
def get_mt_samples(medical_speciality="", path = ".", n = None):
"""
Download Transcribed Medical Transcription Sample Reports and Examples from
'www.mtsamples.com'.
## Parameters
Medical_Speciality: str
One of the followin... |
3336364 | import pymysql
from pymysql import OperationalError
def test_pymysql_connect_returns_error():
try:
connection = pymysql.connect()
except OperationalError as err:
pass
except BaseException as err:
pass
|
3336373 | import os
import sys
import shutil
import requests
import zipfile
import tarfile
def downloader(save_dir='', url=''):
"""
Function to download file from
url to specified destination file.
If file already exists, or the url
is a path to a valid local file,
then simply returns path to local file... |
3336388 | import os
from abc import ABCMeta, abstractmethod
from six import add_metaclass
class LockfilePackageMeta(object):
"""
Basic struct representing package meta from lockfile.
"""
__slots__ = ("name", "version", "sky_id", "integrity", "integrity_algorithm", "tarball_path")
@staticmethod
def fro... |
3336395 | import ee
from landcoverPackage import landsat
from ..aoi import Aoi
from ..export.image_to_asset import ImageToAsset
from ..gee import create_asset_image_collection, to_asset_id
from ..task.task import ThreadTask, Task
def create(spec, context):
return CreateComposites(context.credentials, spec)
class CreateC... |
3336396 | import os, sys
path = os.getcwd()
polars = os.listdir(path + '/savedpolars/')
logpath = path + '/logs/'
polarpath = path + '/savedpolars/'
os.chdir(logpath)
def get_last_point(filename, filepath=polarpath):
polar = open(filepath + filename, "r")
lines = polar.readlines()
return lines[-1].rstrip().split()[... |
3336442 | from django import forms
OPERATOR_CHOICES = (
('>', '>'),
('>=', '>='),
('<=', '<='),
('<', '<'),
('!=', '!='),
)
AGGREGATOR_CHOICES = (
('avg', 'average'),
('max', 'maximum'),
)
class ScaleForm(forms.Form):
metric = forms.ChoiceField()
aggregator = forms.ChoiceField(AGGREGATOR... |
3336490 | from abc import ABCMeta, abstractmethod
class Channel(metaclass=ABCMeta):
def __init__(self):
pass
@abstractmethod
def get_suffix(self):
pass
@abstractmethod
def get_erasure_prob(self):
pass
@abstractmethod
def get_llr(self, out_symbol):
pass
@abstra... |
3336518 | import pytest
from decimal import Decimal
from schematics.exceptions import DataError
from cupping.handlers.helpers import prettify_schematics_errors
from cupping.models import CuppingModel
def test_cupping_invalid_cupping_score():
with pytest.raises(DataError) as e:
CuppingModel({
'name': ... |
3336545 | import os
import torch
from torch.nn import functional as F
from stft_core.modeling.utils import cat
from stft_core.structures.bounding_box import BoxList #infer
from stft_core.structures.boxlist_ops import boxlist_iou
INF = 100000000
def get_num_gpus():
return int(os.environ["WORLD_SIZE"]) if "WORLD_SIZE" in... |
3336576 | import time
import math
from helpers import *
from modules import Module
from noise import snoise2
class PaletteStop:
def __init__(self, pos, color):
self.pos = pos
self.color = color
palette = [
PaletteStop(0.0, [0, 0, 0]),
PaletteStop(0.1, [0, 0, 0]),
PaletteStop(0.15, [198, 101, 0]),
PaletteStop(0.4, [255... |
3336598 | from unittest import TestCase
from test_functions import compare_get_request, compare_post_request
from test_arguments import test_print
class TestBeforeLogin(TestCase):
def test_before_login(self):
# test_get_main_page(self):
test_print("test_get_main_page starting")
compare_get_request... |
3336633 | from netpyne import sim
cfg, netParams = sim.readCmdLineArgs(
simConfigDefault='saving_normal_cfg.py',
netParamsDefault='saving_netParams.py')
sim.initialize(simConfig=cfg, netParams=netParams)
sim.net.createPops()
sim.net.createCells()
sim.net.connectCells()
sim.net.addStims()
sim.setupRecording()
sim.runSim... |
3336673 | from pygbif import species
from .format_helpers import _make_id
def gbif_query_for_single_name(name, rank):
response = species.name_usage(name=name, rank=rank.upper())["results"]
return response
def process_gbif_response(list_of_response_dicts, rank):
key = rank + "Key"
extracted_ids = list(
... |
3336683 | import hydra
from hydra.utils import instantiate
from argoverse.sensor_dataset_config import SensorDatasetConfig
def test_sensor_dataset_config():
"""Ensure that config fields are populated correctly from YAML."""
dataset_name = "argoverse-v1.1"
with hydra.initialize_config_module(config_module="argover... |
3336703 | from clint.textui import progress
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from photos.models import Photo, PhotoSceneCategory
class Command(BaseCommand):
args = ''
help = 'Temp fix'
def handle(self, *args, **options):
admin_user = User.ob... |
3336704 | from __future__ import absolute_import
import unittest
import mock
from collections import namedtuple
from click.testing import CliRunner
from shub import cancel
from shub.exceptions import (
BadParameterException,
ShubException,
)
from .utils import AssertInvokeRaisesMixin, mock_conf
class CancelTest(Ass... |
3336707 | from collections import OrderedDict
import rest_framework.viewsets
from django.db.models import Count
from rest_framework.response import Response
from .filters import DxFilterBackend
from .mixins import DxMixin
from .pagination import TakeSkipPagination
from .summary import SummaryMixin
def format_items(lvl_dict, ... |
3336717 | from .routers import NoMatchFound, NoRouteFound, Prefix, Router, Routes
from .routes import BaseRoute, HttpRoute, SocketRoute
__all__ = [
"Router",
"Routes",
"BaseRoute",
"HttpRoute",
"SocketRoute",
"Prefix",
"NoMatchFound",
"NoRouteFound",
]
|
3336814 | from __future__ import annotations
import datetime
import typing
from typing import List, Optional
from Cryptodome.PublicKey import RSA
from bunq.sdk.context.api_environment_type import ApiEnvironmentType
from bunq.sdk.context.installation_context import InstallationContext
from bunq.sdk.context.session_context impo... |
3336816 | import xml.etree.ElementTree as ET
FILE = "./akizuki_library/Akizuki.lbr"
tree = ET.parse(FILE)
root = tree.getroot()
# 最上位階層のタグと中身
print(root.tag)
for neighbor in root.iter('deviceset'):
print(neighbor.attrib["name"])
root.find("deviceset")
print(root[0][1].text) |
3336837 | from drkns.generation.templateloading.get_generation_template \
import get_generation_template, _extract_from_tag_prefix
def test_get_generation_template():
get_generation_template('./testprojects/nominalcase')
def test_extract_from_tag_prefix():
faked_content = """
Something to stay in content
... |
3336856 | import datetime
import importlib.abc
import importlib.machinery
import sys
import types
import logging
from pathlib import Path
from stacksort._meta import stackoverflow
from stacksort._meta import compile # FIXME propbably shouldn't shadow the name compile
logger = logging.getLogger(__name__)
class StackSortFinde... |
3336903 | from timeseers import LinearTrend
import numpy as np
def test_can_fit_generated_data(trend_data):
data, true_delta, n_changepoints = trend_data
model = LinearTrend(n_changepoints=n_changepoints)
model.fit(data, data["value"])
y_scale_factor = model._y_scaler_.std_
model_delta = np.mean(model.trac... |
3336955 | from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
# Initialize Model
m = GEKKO()
n = 43 # number of discretized segments
ks = m.Param(35950)
kb = m.Param(204020)
js = m.Param(3.2021)
jb = m.Param(15.8480)
ds = m.Param(0.0271)
db = m.Param(0.0266)
vtd = m.Param(10)
v = [m.Var... |
3336973 | from math import sqrt, erf, log, exp
from random import random
# Gauss
def get_next_standard_gauss():
return sum([random() for _ in range(12)]) - 6
def get_next_gauss(m, s):
return m + s * get_next_standard_gauss()
def gauss(m, s, n):
"""
N(m, s^2)
:param m: mean
:param s: dispers... |
3336974 | import numpy as np
from scipy.linalg import polar
def is_pos_def(M):
""" checks whether x^T * M * x > 0, M being the matrix to be checked
:param M: the matrix to be checked
:return: True if positive definite, False otherwise
"""
return np.all(np.linalg.eigvals(M) > 0)
def loss_function(traj, traj_j):
"""... |
3336982 | import sys
import os
import pytest
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
from whr import whole_history_rating
from whr import utils
def setup_game_with_elo(white_elo, black_elo, handicap):
whr = whole_history_rating.Base()
game = whr.create_game("black", "white", "W", 1, handicap)
... |
3336993 | import json
import os, sys
import subprocess
import logging
import argparse
WorkingDirectory = os.getcwd()
# ProjectHome = WorkingDirectory.replace("utilities", "")
# TerraformConfigurationFile = ProjectHome + "main.tf"
EmptyConfigurationFile = WorkingDirectory + os.path.sep + "empty_configuration.tf"
ImportedConfi... |
3337062 | import numpy as np
import os
import io
import sqlite3
import pickle
from tqdm import tqdm
import scipy
import csv
import argparse
from hdf5_save import adapt_array,convert_array
from sklearn.metrics.pairwise import cosine_similarity
from scipy.spatial import distance
sqlite3.register_adapter(np.ndarray, adapt_array)
#... |
3337085 | class ModelException(Exception):
pass
class DoesNotExist(ModelException):
pass
class MultipleObjectsReturned(ModelException):
pass
class CorruptTransactionException(ModelException):
pass
|
3337119 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from random import randint
import six
import time
import nixnet
from nixnet import constants
from nixnet import database
def main():
database_name = ':memory:'
cluster_name = 'LIN_Cluster'
ecu_1_... |
3337147 | from ._config import _show_config, _set_config, _reset_config
from ._novel import (
_package,
_process,
_update,
_novel,
_info,
_clean_novel,
_delete_novel,
_url,
_add_url,
_remove_url,
)
|
3337273 | number = int(input("Please enter number you want to to elevate : "))
power = int(input("Please enter the power : "))
binary = bin(power)
binary = str(binary)[2:]
prod = 1
index = 0
for c in reversed(binary):
if c == '1':
prod *= pow(number, pow(2, index))
index += 1
print(prod)
'''
Compute the binar... |
3337295 | import pandas as pd
import csv
import sklearn.cluster as cluster
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
name=['original_glszm_GrayLevelVariance',
'log-sigma-1-0-mm-3D_firstorder_Minimum',
'log-sigma-3-0-mm-3D_firstorder_Median',
'log-sigma-3-0-mm-3D_glszm_HighGrayLevelZon... |
3337299 | import torch
import copy
from offpolicy.algorithms.mqmix.algorithm.mq_mixer import M_QMixer
from offpolicy.algorithms.mvdn.algorithm.mvdn_mixer import M_VDNMixer
from offpolicy.utils.util import soft_update, huber_loss, mse_loss, to_torch
import numpy as np
from offpolicy.utils.popart import PopArt
class M_QMix:
... |
3337304 | from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(
name='nms_torch_backend',
ext_modules=[
CUDAExtension('nms_torch_backend', [
'src/nms.cpp',
'src/nms_cpu.cpp',
'src/nms_cuda_kernel.cu',
]),
],
cmd... |
3337306 | import logging
import time
from elasticsearch import exceptions as es_exceptions
from elasticsearch.helpers import scan
from leek.api.db.store import STATES_UNREADY
from leek.api.errors import responses
from leek.api.ext import es
logger = logging.getLogger(__name__)
def search_index(index_alias, query, params):
... |
3337313 | def patch_sudo_command(script_path):
with open(script_path, "r") as f:
lines = f.readlines()
outputs = []
for line in lines:
if 'exec sudo -E' in line and 'LD_LIBRARY_PATH' not in line:
line = line.replace(r'PATH=$PATH', r"""PATH=$PATH LD_LIBRARY_PATH=${LD_LIBRARY... |
3337319 | from threading import RLock as _Lock
import numpy as np
def _thread_safe(fn):
"""Decorator that expects a class method which has a _lock attribute.
Args:
fn: Method to be wrapped.
Returns:
method: The wrapper method
"""
def wrapper(*args, **kwargs):
self = args[0]
... |
3337324 | from django.db import migrations
from django.db.migrations import RunPython
def update_determination_type(apps, schema_editor):
"""
Updates the provision field with the description.
Updates the description with the determination_type description
"""
db_alias = schema_editor.connection.alias
a... |
3337343 | import os
import logging
import datetime
from django.core.management.base import BaseCommand
from django.core.management.base import CommandError
from core.load_copyright_map import loadCopyrightMap
from core.management.commands import configure_logging
configure_logging("load_copyright_map_logging.config", "load_co... |
3337365 | import os
import sys
import argparse
import importlib
import numpy as np
import tensorflow as tf
import pdb
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, '..'))
sys.path.append(os.path.join(BASE_DIR, '../utils'))
import provider
import provider_ri... |
3337372 | from taggit.forms import TagField, TagWidget
from django.forms.widgets import SelectMultiple, Textarea, HiddenInput, TextInput
from django import forms
from django.utils.translation import ugettext as _
from taggit.utils import parse_tags, edit_string_for_tags
import re
from django import forms
class ContactForm(form... |
3337377 | import requests
import os
list_of_tin = ['192.168.1.29', '192.168.1.218', '192.168.1.219']
print('Home Lab Status:')
def g_status(tin_list):
wrong_code = []
for ip in tin_list:
url = 'http://' + ip + '/rest/v1/system/status'
get_status_response = requests.get(url, timeout=2)
g_status... |
3337388 | from distutils.core import setup
setup(
name='pyfair',
version='0.1-alpha.12',
description='Open FAIR Monte Carlo creator',
long_description="""
Factor Analysis of Information Risk (Open FAIR) model in Python.
This package endeavors to create a simple API for automating the
cre... |
3337423 | from distutils.core import setup, Extension
import os
#name of module
name = "gfg"
os.environ["CC"] = "g++-4.8"
os.environ["CXX"] = "g++-4.8"
#version of module
version = "1.0"
import numpy
# Obtain the numpy include directory. This logic works across numpy versions.
try:
numpy_include = numpy.get_include()
... |
3337460 | from qiskit import QuantumCircuit
from qiskit.providers.aer.noise import NoiseModel
from qc_grader.grade import grade_and_submit
from qc_grader.util import noisemodel_to_json
criteria: dict = {}
def grade_lab5_ex1(
qc: QuantumCircuit,
) -> None:
grade_and_submit(qc, 'lab5', 'ex1')
def grade_lab5_ex2(answ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.