filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_28477 | import code
import os
import sys
from importlib import import_module
from pathlib import Path
from typing import Any, Callable, Iterable, List, Optional, TYPE_CHECKING
import click
try:
from dotenv import load_dotenv
except ImportError:
pass
from .__about__ import __version__
from .helpers import get_debug_... |
the-stack_106_28478 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2013 Kitware 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 cop... |
the-stack_106_28482 | # -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. 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 requir... |
the-stack_106_28483 | # -*- coding: utf-8 -*-
#
# 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
... |
the-stack_106_28486 | import datetime
from abc import abstractmethod
import six
import sqlalchemy as db
from dagster import check, seven
from dagster.core.errors import DagsterEventLogInvalidForRun
from dagster.core.events import DagsterEventType
from dagster.core.events.log import EventRecord
from dagster.core.serdes import deserialize_j... |
the-stack_106_28489 | from __future__ import absolute_import, division, print_function, unicode_literals
import warnings
from canvasapi.account import Account
from canvasapi.course import Course
from canvasapi.course_epub_export import CourseEpubExport
from canvasapi.current_user import CurrentUser
from canvasapi.exceptions import Require... |
the-stack_106_28492 | """empty message
Revision ID: 77b63ea5b036
Revises:
Create Date: 2020-05-20 16:09:45.241980
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '77b63ea5b036'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
the-stack_106_28493 | import coreschema
import six
from django.utils.translation import gettext_lazy as _
from django_filters import rest_framework as filters
from django_filters.fields import ModelMultipleChoiceField, MultipleChoiceField
from django_filters.filters import QuerySetRequestMixin
from django_filters.rest_framework import Djang... |
the-stack_106_28494 | ########################################################################################################################
# The following class is for different kinds of annealing optimizer
########################################################################################################################
from pic... |
the-stack_106_28495 | from logging import log
from typing import Dict as _Dict
from typing import List as _List
from xml.etree.ElementTree import ParseError as _XmlParseError
import asyncio as _asyncio
from discord import TextChannel as _TextChannel
import discord.ext.tasks as _tasks
from discord.ext.commands import Bot as _Bot
from discor... |
the-stack_106_28497 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2021 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... |
the-stack_106_28498 | # Time: O(n)
# Space: O(1)
# counting sort solution
class Solution(object):
def specialArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
MAX_NUM = 1000
count = [0]*(MAX_NUM+1)
for num in nums:
count[num] += 1
n = len(nums)
... |
the-stack_106_28500 | from raptiformica.shell.raptiformica import clean
from tests.testcase import TestCase
class TestClean(TestCase):
def setUp(self):
self.log = self.set_up_patch('raptiformica.shell.raptiformica.log')
self.run_raptiformica_command = self.set_up_patch(
'raptiformica.shell.raptiformica.run_... |
the-stack_106_28501 | #!/usr/bin/env python3
# Copyright (C) 2019-2021 The btclib developers
#
# This file is part of btclib. It is subject to the license terms in the
# LICENSE file found in the top-level directory of this distribution.
#
# No part of btclib including this file, may be copied, modified, propagated,
# or distributed except... |
the-stack_106_28502 | # vim: set fileencoding=utf-8:
#
# GPIO Zero: a library for controlling the Raspberry Pi's GPIO pins
# Copyright (c) 2016-2019 Dave Jones <dave@waveform.org.uk>
# Copyright (c) 2019 Ben Nuttall <ben@bennuttall.com>
# Copyright (c) 2018 Rick Ansell <rick@nbinvincible.org.uk>
# Copyright (c) 2016 Andrew Scheller <github@... |
the-stack_106_28506 | """
食糖购销交易接口
"""
import json
import hashlib
import sys
from copy import copy
from datetime import datetime
import pytz
from typing import Dict, List, Any, Callable, Type, Union
from types import TracebackType
from functools import lru_cache
import requests
import wmi
from vnpy.api.rest import RestClient, Request
from... |
the-stack_106_28507 | import requests
import sys
import time
from lib.tracing import init_tracer
def say_hello(hello_to):
with tracer.start_active_span('say-hello') as scope:
scope.span.set_tag('hello-to', hello_to)
hello_str = format_string(hello_to)
print_hello(hello_str)
def format_string(hello_to):
wit... |
the-stack_106_28508 | # -*- coding: utf-8 -*-
#
# 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
#... |
the-stack_106_28510 | """
A federated learning client at the edge server in a cross-silo training workload.
"""
import time
from dataclasses import dataclass
from plato.algorithms import registry as algorithms_registry
from plato.clients import base
from plato.config import Config
from plato.processors import registry as processor_registr... |
the-stack_106_28511 | # Parallel implementation template from: https://gitlab.com/lucasrthompson/Sonic-Bot-In-OpenAI-and-NEAT
# PuyoPuyo gym environment from: https://github.com/frostburn/gym_puyopuyo
import os
import pickle
import numpy as np
from gym_puyopuyo import register
import gym
import neat
import visualize
NUM_WORKERS = 4 # numb... |
the-stack_106_28512 | import numpy as np
import csv
from decision_tree import DecisionTree
from collections import Counter
class RandomForest:
def __init__(self, num):
self.num = num
self.dts = []
for _ in range(num):
self.dts.append(DecisionTree())
def fit(self, x, y, detailed=False):
nu... |
the-stack_106_28515 | """
CLI configuration decorator to use TOML configuration files for click commands.
"""
## This section contains code copied and modified from [click_config_file][https://github.com/phha/click_config_file/blob/master/click_config_file.py]
## SPDX-License-Identifier: MIT
import os
import functools
import logging
from... |
the-stack_106_28516 | #!/usr/bin/env python
"""
ml_fits2.py
Intermediate-level code for building models in scikit-learn and xgboost
For basic-level code, see ml_fits.py
"""
import argparse
import catboost
import lightgbm
import numpy as np
import os
import pandas as pd
import pickle
import warnings
import xgboost as xgb
from hyperopt im... |
the-stack_106_28517 | import asyncio
import datetime
import functools
import json
import logging
import time
from collections import defaultdict
import discord
from discord.ext import commands
from tle.util import codeforces_common as cf_common
from tle.util import cache_system2
from tle.util import db
from tle.util import discord_common... |
the-stack_106_28518 | import numpy as np
from matplotlib import pyplot as plt
n_tokens = 100
fs = 0.5
x = np.arange(0, n_tokens, 0.1) * fs
pos_enc = np.sin(x)
print(pos_enc.shape)
plt.plot(x, pos_enc)
plt.xlabel('Embedding Dimensions')
plt.ylabel('Token Position')
plt.show()
|
the-stack_106_28520 | # Copyright 2014 Google Inc. All Rights Reserved.
"""Command for getting a target pool's health."""
from googlecloudsdk.compute.lib import base_classes
from googlecloudsdk.compute.lib import request_helper
from googlecloudsdk.compute.lib import utils
class GetHealth(base_classes.BaseCommand):
"""Get the health of i... |
the-stack_106_28521 | import asyncio
import contextlib
from datetime import datetime
from functools import wraps
import hashlib
import json
import logging
import multiprocessing
import os
from pathlib import Path
import platform
import sys
import textwrap
import typing
from typing import Any, Callable, Dict, List, Optional, Text
import uuid... |
the-stack_106_28522 | import sys
import time
from django.core.management import call_command
from cms.categories.models import PublicationType
from .importer_cls import Importer
# the indiators from wordpress aren't nice so map them to better titles
SOURCES = {
"publication_types": "NHS England & Improvement",
"publication_types... |
the-stack_106_28524 | """Custom loader."""
from collections import OrderedDict
import fnmatch
import logging
import os
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional, TextIO, TypeVar, Union, overload
import yaml
from homeassistant.exceptions import HomeAssistantError
from .const import SECRET_YAML
from .o... |
the-stack_106_28525 | #!/usr/bin/env python
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Run this script from the root of the repository to update all translations from
transifex.
It will do the follo... |
the-stack_106_28526 | from . import ml5_nn
from . import utilis
import jp_proxy_widget
from IPython.display import display
from jupyter_ui_poll import ui_events
import numpy as np
import matplotlib.pyplot as plt
import cv2
import time
class ObjectDetector(ml5_nn.neuralNetwork):
def __init__(self, model, options=None, *pargs, **kwargs... |
the-stack_106_28527 | # @Time : 2020/6/28
# @Author : Zihan Lin
# @Email : linzihan.super@foxmail.com
# UPDATE
# @Time : 2020/10/04, 2020/10/9
# @Author : Shanlei Mu, Yupeng Hou
# @Email : slmu@ruc.edu.cn, houyupeng@ruc.edu.cn
"""
recbole.config.configurator
################################
"""
import re
import os
import sys
import... |
the-stack_106_28528 |
import os
import sys
os.environ['MLFLOW_TRACKING_URI'] = 'http://127.0.0.1:5000'
# Imports
import glob
import numpy as np
import os.path as path
from scipy import misc
from keras.models import Sequential
from keras.layers import Activation, Dropout, Flatten, Dense, Conv2D, MaxPooling2D
from keras.callbacks import E... |
the-stack_106_28529 | import os
import multiprocessing
import tensorflow as tf
from functools import partial
from riptide.utils.datasets import imagerecord_dataset
from riptide.utils.thread_helper import setup_gpu_threadpool
from riptide.anneal.anneal_config import Config
from riptide.anneal.models import get_model, get_optimizer
from ripti... |
the-stack_106_28530 | import argparse
import unittest
from unittest import mock
import train_model
from shared import utils
class TestMain(unittest.TestCase):
@mock.patch('train_model.setup_args')
@mock.patch('train_model.get_model')
@mock.patch('train_model.train_model')
def test_main_code_is_behaving_as_expected(self, ... |
the-stack_106_28531 | # Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
the-stack_106_28532 | #!/usr/bin/env python
# coding: utf-8
from __future__ import unicode_literals
import os
import shutil
import tempfile
import unittest
from mkdocs import config
from mkdocs import utils
from mkdocs.config import config_options
from mkdocs.exceptions import ConfigurationError
from mkdocs.tests.base import dedent
def ... |
the-stack_106_28533 | from typing import KeysView
SERVICES_FOR_GROUP = {
"all": "chia_harvester chia_timelord_launcher chia_timelord chia_farmer chia_full_node chia_wallet".split(),
"node": "chia_full_node".split(),
"harvester": "chia_harvester".split(),
"farmer": "chia_harvester chia_farmer chia_full_node chia_wallet".spli... |
the-stack_106_28534 | import json
import os
import sys
import re
import copy
import numpy as np
from .base_model import BaseModel
from .base_model import AutoSubRegistrationMeta
from .. import dp_logging
logger = dp_logging.get_child_logger(__name__)
class RegexModel(BaseModel, metaclass=AutoSubRegistrationMeta):
def __init__(self... |
the-stack_106_28536 | # -*- coding: utf-8 -*-
first_names = [
'Adelheid',
'Agnes',
'Albert',
'Anna',
'Arnold',
'Barbara',
'Bernhard',
'Berthold',
'Christine',
'Dietrich',
'Eberhard',
'Elisabeth',
'Fenne',
'Friedrich',
'Georg',
'Gerhard',
'Gerhaus',
'Gertrud',
'Hedwi... |
the-stack_106_28538 |
import librosa
import numpy as np
# function to extract all the features needed for the classification
def extract_features(audio_samples, sample_rate):
print(" Extracting features ..... ")
extracted_features = np.empty((0, 41,))
if not isinstance(audio_samples, list):
audio_samples = [audio_samp... |
the-stack_106_28540 | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015, 2016, 2017 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Li... |
the-stack_106_28541 | # Copyright (c) 2010-2020 openpyxlzip
from openpyxlzip.descriptors.serialisable import Serialisable
from openpyxlzip.descriptors import (
Sequence,
Typed,
Alias,
)
from openpyxlzip.descriptors.excel import ExtensionList
from openpyxlzip.descriptors.nested import (
NestedBool,
NestedInteger,
Nes... |
the-stack_106_28542 | """
Suppose an numsay sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the numsay return its index, otherwise return -1.
You may assume no duplicate exists in the numsay.
Your algor... |
the-stack_106_28544 | import geopandas as gpd
import pandas as pd
from gis_utils import gis_main_dir
def main():
dfd = pd.read_csv('{}census/aff_download1/ACS_15_5YR_B19013_with_ann.csv'.format(gis_main_dir))
dfs = gpd.read_file('{}census/va_block_groups/tl_2015_51_bg.shp'.format(gis_main_dir))
dfd = dfd[dfd['marg_err'].str.c... |
the-stack_106_28545 | from django.shortcuts import render
from django.http import HttpResponse, Http404
from .models import Category, Location, Image
# Create your views here.
def welcome(request):
try:
category = Category.objects.all()
location = Location.objects.all()
images = Image.objects.all()
except:... |
the-stack_106_28546 | #!/usr/bin/env python
# Copyright (c) 2016 Hewlett Packard Enterprise Development Company, L.P.
#
# 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... |
the-stack_106_28547 | from mako.template import Template
from dtest.syslog import log
import json
import traceback
import random
import string
def selectParameters(**kwargs):
"""组合参数"""
value_len = []
params_list = []
for k in kwargs.keys():
value_len.append(len(kwargs[k]))
value_len.sort()
for v in range(va... |
the-stack_106_28548 | from Module import AbstractModule
class Module(AbstractModule):
def __init__(self):
AbstractModule.__init__(self)
def run(
self, network, antecedents, out_attributes, user_options, num_cores,
out_path):
import os
from genomicode import parallel
from genomicode i... |
the-stack_106_28550 | """
Ported using Python-Future from the Python 3.3 standard library.
Parse (absolute and relative) URLs.
urlparse module is based upon the following RFC specifications.
RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding
and L. Masinter, January 2005.
RFC 2732 : "Format for Literal IPv6... |
the-stack_106_28551 | import pyaztro
from scape.events import register
ASTRO = ""
@register(outgoing=True, disable_errors=True, pattern=r"^\.hc (.*)")
async def astro(e):
await e.edit("Fetching data...")
if not e.pattern_match.group(1):
x = ASTRO
if not x:
await e.edit("Not Found.")
return... |
the-stack_106_28552 |
VALOR_MAXIMO = 100
for numero in range(1, VALOR_MAXIMO + 1):
saida = ""
if numero % 2 == 0:
saida += "Fizz"
if numero % 3 == 0:
saida += "Buzz"
if numero % 5 == 0:
saida += "Zyzz"
if saida == "":
saida = numero
print(saida)
|
the-stack_106_28555 | #!/usr/bin/env python
# coding: utf-8
#### Optimized by Eduardo Coronado and Andrew Carr, Duke University
import numpy as np
def get_perplexity(x_ji, doc_arrays, topic_idx, n_kv, m_k, beta, alpha, gamma, V):
'''Computes the models perplexity given inferences at epoch i, in other words provides a metric
... |
the-stack_106_28556 | #!/usr/bin/env python
from .util import create_url
class PartialDeleteAPI:
"""Create a job to partially delete the contents of the table with the given
time range.
This class is inherited by :class:`tdclient.api.API`.
"""
def partial_delete(self, db, table, to, _from, params=None):
"""C... |
the-stack_106_28557 | import datetime
import importlib
import pathlib
author = "dynamicslab"
project = "pysindy" # package name
# no need to edit below this line
copyright = f"{datetime.datetime.now().year}, {author}"
module = importlib.import_module(project)
version = release = getattr(module, "__version__")
master_doc = "index"
ex... |
the-stack_106_28558 | """empty message
Revision ID: 8f8001e98e65
Revises: 2721189b0c8f
Create Date: 2020-02-07 12:42:57.248894
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '8f8001e98e65'
down_revision = '2721189b0c8f'
branch_labels = None
depends_on = None
def upgrade():
# ### ... |
the-stack_106_28559 | from keras.layers import *
from keras.models import *
from keras.optimizers import *
from config import KERAS_FILTERS as FILTERS, KERAS_KERNEL_SIZE as KERNEL_SIZE, \
KERAS_LEARNING_RATE as LEARNING_RATE, KERAS_DROPOUT as DROPOUT
def build_model(board_shape: tuple, action_size: int):
board_x, board_y = board_... |
the-stack_106_28562 | import os, sys
sys.path.append(os.getcwd())
import pickle as pkl
from urllib import request
import pandas as pd
import numpy as np
from zipfile import ZipFile
dataset_list = []
def load_datasets(datasets=None):
"""
Args:
datasets (list of str): Lists of datasets to load by name. If None, all availabl... |
the-stack_106_28563 | import nbp
import numpy as np
import matplotlib.pyplot as plt
data = nbp.Parser('sodium-chloride-example.npz').parse()
for key, val in data.items():
if isinstance(val, np.ndarray):
print(key, val.shape)
print('flipped ', val[:, None].shape)
elif isinstance(val, dict):
for sk, sv in va... |
the-stack_106_28564 | import FWCore.ParameterSet.Config as cms
def printGeomInfo(process):
process.load("SimGeneral.HepPDTESSource.pdt_cfi")
process.load("Geometry.TrackerNumberingBuilder.trackerNumberingGeometry_cfi")
process.load("Geometry.MuonNumbering.muonNumberingInitialization_cfi")
process.load("Geometry.HcalCommon... |
the-stack_106_28569 | from simple_tensor.segmentation.deeplab import *
segmentation = DeepLab(num_classes=1,
model_path = "/home/model/resnet_v2_101/resnet_v2_101.ckpt",
is_training=True)
train_generator = segmentation.batch_generator(batch_size=4,
... |
the-stack_106_28570 | from tests import PyResTests, Basic
from pyres import failure
from pyres.job import Job
class FailureTests(PyResTests):
def setUp(self):
PyResTests.setUp(self)
self.queue_name = 'basic'
self.job_class = Basic
def test_count(self):
self.resq.enqueue(self.job_class,"test1")
... |
the-stack_106_28571 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = 'mp3chaps'
VERSION = '0.2'
KEYWORDS = 'mp3 chapters'
DESCRIPTION = 'tool for inserting chapter marks in mp3 files'
URL = 'https://gith... |
the-stack_106_28572 | import os
from pathlib import Path
from my.bash import _parse_file
test_dir = os.path.dirname(os.path.abspath(__file__))
history_file = Path(os.path.join(test_dir, "bash", "history"))
def test_single_file() -> None:
history = list(_parse_file(history_file))
assert len(history) == 4
assert history[0].com... |
the-stack_106_28575 |
import os
import math
from kivy.app import App
from kivy.clock import Clock
from kivy3 import Scene, Renderer, PerspectiveCamera, Mesh, Material
from kivy3.extras.geometries import BoxGeometry
from kivy3.loaders import OBJLoader
from kivy.uix.floatlayout import FloatLayout
from urdf_parser_py.urdf import URDF
# Resou... |
the-stack_106_28576 | from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
# Implements parse_requirements as standalone functionality
with ... |
the-stack_106_28577 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2003-2009 Edgewall Software
# Copyright (C) 2003-2005 Jonas Borgström <jonas@edgewall.com>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at htt... |
the-stack_106_28578 | #
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or th... |
the-stack_106_28580 | # Copyright 2020 The FastEstimator 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... |
the-stack_106_28582 | a=input('Enter the name of the file you want to open:\n')
if len(a)<1:
doc=open('Num.txt','r+')
print('Opening Num.txt...')
else:
doc=open(a,'r+')
Prevnum=''
for line in doc:
x=line.strip()
number=Prevnum+x
Prevnum=number
#print(x)
#for i in x:
#print(number)
#prod=1
i=0
... |
the-stack_106_28583 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
the-stack_106_28584 | # Copyright 2019 The TensorFlow 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 applica... |
the-stack_106_28588 | """
Copyright (C) 2020 Dabble Lab - All Rights Reserved
You may use, distribute and modify this code under the
terms and conditions defined in file 'LICENSE.txt', which
is part of this source code package.
For additional copyright information please
visit : http://dabblelab.com/copyright
"""
from ask_sdk_core... |
the-stack_106_28590 | import logging
import logging.handlers
import sys
def init():
logging.getLogger().setLevel(logging.NOTSET)
# Add stdout handler, with level INFO
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-13s: %(levelname)-8s %(message)s')
... |
the-stack_106_28591 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pdb
# 3rd party imports
import numpy as np
import xarray as xr
__author__ = "Louis Richard"
__email__ = "louisr@irfu.se"
__copyright__ = "Copyright 2020-2021"
__license__ = "MIT"
__version__ = "2.3.7"
__status__ = "Prototype"
def _idx_closest(lst0, lst1):
ret... |
the-stack_106_28593 | class Solution:
def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
m = len(A)
n = len(B)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = dp[i - 1][j - 1] + 1 if A[i - 1] == B[j - 1] \
else max(dp[i - 1][j... |
the-stack_106_28595 | import augment
import numpy as np
import torch
import torchaudio
import argparse
import yaml
import os
import random
from tqdm import tqdm
import threading
def aug_pitch(audio, sr=16000, low_pitch=-350, high_pitch=300):
random_pitch_shift = lambda: np.random.randint(low_pitch, high_pitch)
y = augment.EffectCha... |
the-stack_106_28597 | from modules.ImageCreator import ImageCreator
from modules.BamHandler import BamHandler
from modules.FastaHandler import FastaHandler
import os
class Bed2ImageAPI:
"""
Works as a main class and handles user interaction with different modules.
"""
def __init__(self, bam_file_path, reference_file_path):
... |
the-stack_106_28598 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import os.path
import shutil
from glob import glob
import sys
import setuptools
from setuptools import Extension
from setuptools.command.build_ext import build_ext
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "pythia"))
with ope... |
the-stack_106_28599 | # -*- coding: utf-8 -*-
# Copyright (c) 2016-2019 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
from math import pi
from numpy import sign, nan, append, zeros, array, sqrt, where
from numpy import max as max_
from pandas impor... |
the-stack_106_28600 | # This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Codon tables based on those from the NCBI.
These tables are based on parsing the NCBI file
ftp://ftp.ncbi.nih.gov/entrez/misc/data/gc.prt
using Scri... |
the-stack_106_28603 | import torch
from torch import nn
from .torch_nn import BasicConv, batched_index_select
from .torch_edge import DenseDilatedKnnGraph, DilatedKnnGraph
import torch.nn.functional as F
class MRConv2d(nn.Module):
"""
Max-Relative Graph Convolution (Paper: https://arxiv.org/abs/1904.03751) for dense data type
... |
the-stack_106_28605 | """Example with fitting a 32 triangles soup to an image."""
import copy
import os
import cv2
import deodr
from deodr import differentiable_renderer_cython
from deodr.differentiable_renderer import Scene2D
from imageio import imread
import matplotlib.pyplot as plt
import numpy as np
def create_example_scene(n_t... |
the-stack_106_28610 | # Copyright 2015 Cisco Systems, 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 agreed to in writing... |
the-stack_106_28611 | from time import sleep
from org.myrobotlab.service import InMoovArm
# create the IK3D service.
ik3d= Runtime.createAndStart("ik3d", "InverseKinematics3D")
ik3d.setCurrentArm(InMoovArm.getDHRobotArm())
# starting point
# x , y , z
x1 = 100
y1 = 100
z1 = 100
# ending point
# x , y , z
x2 = 500
y2 = ... |
the-stack_106_28612 | # 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... |
the-stack_106_28613 | # vanilla topological sorting
"""
This method is based on DFS. It is not based on in degree and out degree!
"""
import collections
class Graph(object):
# directed graph
def __init__(self, vertices):
self.graph = collections.defaultdict(list)
self.v = vertices
def addEdge(self, u, v):
self.graph[u].append(v)
... |
the-stack_106_28614 | # -*- coding: utf-8 -*-
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, 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... |
the-stack_106_28615 | #!usr/bin/python3
# * head.direction이라는 attribute 사용보다는 안좋기는 하지만 아이들이 더 쉽게 이해하도록 global variable 사용.
import turtle
import time
import random
wn = turtle.Screen()
wn.title("SNAKE!")
wn.bgcolor("steel blue")
wn.setup(width = 600, height = 600)
wn.tracer(0) # 매뉴얼로 업데이트하도록 설정
# [2] Snake 객체
head = turtle.Turtle()
head.... |
the-stack_106_28616 | import mal_types as mal
class MalEnv():
"""Mal environment class.
An environment mapping symbols to Mal objects. Note that the symbols should
be strings, not Mal objects, although the initializer accepts both strings
naming symbols and mal_types.Symbol.
"""
def __init__(self, outer=None, da... |
the-stack_106_28620 | import logging
from datetime import datetime
from django.conf import settings
from django import forms
from django.core.mail import mail_admins
from django.template.loader import render_to_string
from .models import get_gsheets_client
log = logging.getLogger(__name__)
class SuggestionForm(forms.Form):
ward_i... |
the-stack_106_28621 | import numpy as np
import pandas as pd
df = pd.read_csv('tests/bugs/issue_19/issue_19_data_1.csv')
import datetime
def convert_date(x):
y = np.nan
try:
y = datetime.datetime.strptime(str(x), "%Y")
except:
# bad format
pass
return y
df['date'] = df['date'].apply(convert_date)... |
the-stack_106_28622 |
from __future__ import print_function
import os
import platform
import sys
from mvIMPACT import acquire
from mvIMPACT.Common import exampleHelper
import ctypes
import numpy as np
import datetime as dt
import matplotlib
from LEDDriver import detect_LED_devices, LEDDriver, LEDException
from spectracular.fpi_driver i... |
the-stack_106_28625 | import logging
import os
import sys
import warnings
from django.apps import AppConfig
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
log = logging.getLogger('z.startup')
class CoreConfig(AppConfig):
name = 'olympia.core'
verbose_name = _('Core')
def ready(self... |
the-stack_106_28626 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import os
import shutil
import numpy as np
from dmriqcpy.io.report import Report
from dmriqcpy.viz.graph import graph_tractogram
from dmriqcpy.analysis.stats import stats_tractogram
from dmriqcpy.viz.screenshot import screenshot_tracking
from dmriqcpy.vi... |
the-stack_106_28627 | import torch
import torch.nn as nn
import os
import glob
class Model(nn.Module):
def __init__(self, name):
super(Model, self).__init__()
self.name = name
def save(self, path, epoch=0):
complete_path = os.path.join(path, self.name)
if not os.path.exists(complete_path):
... |
the-stack_106_28629 | import math
import numpy as np
from common.numpy_fast import interp, clip
from common.realtime import sec_since_boot
from selfdrive.modeld.constants import T_IDXS
from selfdrive.controls.lib.radar_helpers import _LEAD_ACCEL_TAU
from selfdrive.controls.lib.lead_mpc_lib import libmpc_py
from selfdrive.controls.lib.drive_... |
the-stack_106_28630 | # Copyright 2021 Collate
# 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... |
the-stack_106_28632 | import typing
from argparse import Namespace
from kgtk.cli_argparse import KGTKArgumentParser, KGTKFiles
def parser():
return {
'help': 'Split a sorted KGTK edge file into multiple byte sized files',
'description': 'split a sorted KGTK edge file into smaller files, keeping the Qnode'
... |
the-stack_106_28633 | from airflow import DAG
import pandas as pd
import datetime as dt
from airflow.operators.python import PythonOperator
from minio import Minio
import os
import glob
import functions as f
data_lake_server= f.var['data_lake_server_airflow']
data_lake_login= f.var['data_lake_login']
data_lake_password= f.var['data_lake_pa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.