filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_20998
from unittest.mock import patch from django.core.management import call_command from django.db.utils import OperationalError from django.test import TestCase class CommandTests(TestCase): def t2test_wait_for_db_ready(self): with patch('django.db.utils.ConnectionHandler.__getitem__') as gi: gi....
the-stack_106_20999
# import gym import box_world_env import time # from PIL import Image import matplotlib.pyplot as plt import argparse import os parser = argparse.ArgumentParser(description='Run environment with random selected actions.') parser.add_argument('--rounds', '-r', metavar='rounds', type=int, help='numbe...
the-stack_106_21000
import sublime import sublime_plugin import subprocess import re class GitShowGitlabPipelines(sublime_plugin.WindowCommand): def run(self): cwd = self.window.folders()[0] output = subprocess.check_output('git config --get remote.gitlab.url', shell=True, cw...
the-stack_106_21002
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from d...
the-stack_106_21005
#!/bin/python3 # encoding: utf-8 import tensorflow as tf import numpy as np tf.enable_eager_execution() X_raw = np.array([2013, 2014, 2015, 2016, 2017], dtype=np.float32) y_raw = np.array([12000, 14000, 15000, 16500, 17500], dtype=np.float32) X = (X_raw - X_raw.max()) / (X_raw.max() - X_raw.min()) y = (y_raw - y_raw...
the-stack_106_21006
from random import * def rockPaperScissors(user,npc): if user == 1 and npc == 1: print("Tie") elif user == 1 and npc == 2: print("NPC Wins") elif user == 1 and npc == 3: print("User Wins!") elif user == 2 and npc == 1: print("User Wins") elif user == 2 and npc == 2: ...
the-stack_106_21008
""" Note: This is an extension of House Robber. After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanw...
the-stack_106_21010
from logging import * import logging.config as config import logging.handlers as handlers from click import style, echo from logging import __all__ __all__.extend(["SUCCESS", "success", "ClickHandler", "SuppressExceptionFormatter"]) # adding a new level SUCCESS SUCCESS = 25 addLevelName(SUCCESS, "SUCCESS") def succe...
the-stack_106_21012
import unittest import numpy as np import pytest from scipy.stats import ortho_group from sklearn.datasets import load_iris from numpy.testing import assert_array_almost_equal, assert_allclose from sklearn.utils.testing import ignore_warnings from metric_learn import ( LMNN, NCA, LFDA, Covariance, MLKR, LSML_S...
the-stack_106_21016
# Copyright 2020 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_21017
import collections import datetime import hashlib import http.cookiejar import logging import re import time import urllib.parse import xml.etree.ElementTree as ET from enum import Enum import requests import requests.exceptions import requests.packages.urllib3 import requests_toolbelt from requests.auth import HTTPD...
the-stack_106_21018
#!/usr/bin/env python from weboob.core import Weboob from weboob.exceptions import ModuleLoadError, ModuleInstallError from weboob.core.backendscfg import BackendAlreadyExists from weboob.capabilities.bank import Account import logging logger = logging.getLogger(__name__) class Boobmanage: """ Class that perfor...
the-stack_106_21020
import machine import ssd1306 import time #define the input from light sensor adc = machine.ADC(0) pinvib = machine.Pin(12) pwmvib = machine.PWM(pinvib) pwmvib.freq(900) pwmvib.duty(0) switchA = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP) switchB = machine.Pin(13, machine.Pin.IN, value = 0) switchC = machine...
the-stack_106_21021
#!/usr/bin/env python # Copyright (c) 2013 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Use the raw transactions API to spend bitcoins received on particular addresses, # and send any change back ...
the-stack_106_21023
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################ # File Name: thread_4.py # Author: One Zero # Mail: zeroonegit@gmail.com # Created Time: 2015-12-29 19:16:22 ############################ import threading import time class myThread(threading.Thread): def __init__(self, threadID, name, co...
the-stack_106_21024
import json import pickle import argparse import os def get_args(): parser = argparse.ArgumentParser("Parsing MS COCO dataset") parser.add_argument("--input", type=str, default="data/COCO") parser.add_argument("--type", type=str, default="val2014") parser.add_argument("--output", type=str, default="dat...
the-stack_106_21025
""" @date: 2021/7/19 @description: """ import torch import loss from utils.misc import tensor2np def build_criterion(config, logger): criterion = {} device = config.TRAIN.DEVICE for k in config.TRAIN.CRITERION.keys(): sc = config.TRAIN.CRITERION[k] if sc.WEIGHT is None or float(sc.WEIGHT...
the-stack_106_21027
# Copyright 2019-2020 ETH Zurich and the DaCe authors. All rights reserved. import dace from dace.transformation.interstate import StateAssignElimination, StateFusion def test_eliminate_end_state(): sdfg = dace.SDFG('state_elimination_test') state1 = sdfg.add_state() state2 = sdfg.add_state() state3 =...
the-stack_106_21028
from datetime import datetime from helper.embed_props import * import discord header_text = "Message for the Koders" def morning_embed(quote, author): author = "<br />" + "<i>- " + author + "</i>" # Adding proper spacing for author via HTML message = quote + author embed = discord.Embed( descri...
the-stack_106_21030
import os import json import pathlib import tempfile import contextlib from http import HTTPStatus from unittest.mock import patch import aiohttp from dffml.model.slr import SLRModel from dffml.source.json import JSONSource from dffml import Record, Features, DefFeature, save, train, accuracy from dffml.util.asynctes...
the-stack_106_21031
""" test indexing with ix """ import pytest from warnings import catch_warnings import numpy as np import pandas as pd from pandas.core.dtypes.common import is_scalar from pandas.compat import lrange from pandas import Series, DataFrame, option_context, MultiIndex from pandas.util import testing as tm from pandas.e...
the-stack_106_21032
from typing import Any, Callable, Dict, List, Optional, Set import logging import os from tensorboardX import SummaryWriter import torch from allennlp.common.from_params import FromParams from allennlp.data.dataloader import TensorDict from allennlp.nn import util as nn_util from allennlp.training.optimizers import O...
the-stack_106_21033
import tensorflow as tf import tensorflow_datasets as tfds AUTO = tf.data.experimental.AUTOTUNE class DatasetGenerator: def __init__(self, data_dir, image_size, batch_size): """ Args: data_dir: 데이터셋 상대 경로 ( default : './datasets/' ) image_size: 백본에 따른 이미지 해상도 크기 ...
the-stack_106_21034
from typing import List, Tuple, Dict import streamlit as st import pandas as pd # Custom packages from lib.preprocessing import prepare_data import streamlit_page.generalstats as generalstats import streamlit_page.teacherstats as teacherstats FILE_PATH = 'dataset/subjects_master_2022_modefied.csv' def main(): p...
the-stack_106_21035
from fastapi import APIRouter import json import pandas as pd router = APIRouter() strain = pd.read_csv('data/strains.csv') """ Return the data as JSON """ @router.get('/ailments') async def ailments(): depression = [] for i in range(strain.shape[0]): if 'Depression' in strain.ailment.iloc[i]: ...
the-stack_106_21036
import re from word2number import w2n ORDINAL_MAP = { 'first': 1, 'second': 2, 'third': 3, 'fourth': 4, 'fifth': 5, 'sixth': 6, 'seventh': 7, 'eighth': 8, 'ninth': 9 } DECADE_MAP = { 'twenties': 20, 'thirties': 30, 'forties': 40, 'fifties': 50, 'sixties': 60,...
the-stack_106_21037
from contextlib import contextmanager from copy import copy # Hard-coded processor for easier use of CSRF protection. _builtin_context_processors = ('django.template.context_processors.csrf',) class ContextPopException(Exception): "pop() has been called more times than push()" pass class ContextDict(dict):...
the-stack_106_21038
from keras.layers import Input, Conv2D, Activation, BatchNormalization, GaussianNoise, add, UpSampling2D, concatenate, Conv2DTranspose, Lambda from keras.models import Model from keras.regularizers import l2 import tensorflow as tf from keras.engine.topology import Layer from keras.engine import InputSpec from keras.ut...
the-stack_106_21040
import os import re import numpy as np import scipy.optimize from ledsa.core.model import target_function from ledsa.core.LEDAnalysisData import LEDAnalysisData import time sep = os.path.sep def generate_led_analysis_data(conf, channel, data, debug, iled, img_filename, led_array_idx, search_areas, ...
the-stack_106_21043
# -*- coding: utf-8 -*- """ Created on Wed Feb 2 07:15:26 2022 @author: ACER """ # lista en blanco lista = [] #lista con elementos ñistElementos = [1,3,4,5] #acceder a los elementos listAlumnos = ["adri","rither","jose","juan"] alumnoPos_1 =listAlumnos[len(listAlumnos)-1] #'juan' #obtener el tamanio de la lista ta...
the-stack_106_21044
#!/usr/bin/env python import rospy from sensor_msgs.msg import JointState from std_msgs.msg import Float64 import gazebo_msgs.msg import geometry_msgs.msg from gazebo_msgs.srv import SetPhysicsProperties def joint_states_cb(msg): pub_joint1_pos.publish(msg.position[0]) pub_joint2_pos.publish(msg.position[1]) ...
the-stack_106_21046
import Adafruit_DHT import time import RPi.GPIO as GPIO #Initialize PIN 17 for the DHT22 data; DHT_SENSOR = Adafruit_DHT.DHT22 DHT_PIN = 17 #sets the mode to broadcom (GPIO pinout); GPIO.setmode(GPIO.BCM) # Relay # Tells python that GPIO 4 is an output; rpin = 4 GPIO.setup(rpin, GPIO.OUT) while True: humidity,...
the-stack_106_21048
import pytest import numpy from numpy.testing import assert_allclose from scipy import sparse from fvm import Continuation from fvm import Interface @pytest.fixture(autouse=True, scope='module') def import_test(): try: from fvm import JadaInterface # noqa: F401 except ImportError: pytest.sk...
the-stack_106_21049
import datetime import importlib import itertools import warnings from typing import Any, Callable, Optional, Union from .timezone import tz_aware def import_from_str(import_string: Optional[Union[Callable, str]]) -> Any: """Import an object defined as import if it is an string. If `import_string` follows t...
the-stack_106_21050
# flake8: noqa # disable flake check on this file because some constructs are strange # or redundant on purpose and can't be disable on a line-by-line basis import ast import inspect import linecache import sys import textwrap from types import CodeType from typing import Any from typing import Dict from typing import ...
the-stack_106_21051
from datetime import datetime import logging import os from .rest_session import * from .api.organizations import Organizations from .api.networks import Networks from .api.devices import Devices from .api.appliance import Appliance from .api.camera import Camera from .api.cellularGateway import CellularGateway from ....
the-stack_106_21052
"""Test service helpers.""" from collections import OrderedDict from copy import deepcopy import unittest from unittest.mock import Mock, patch import pytest import voluptuous as vol # To prevent circular import when running just this file from homeassistant import core as ha, exceptions from homeassistant.auth.permi...
the-stack_106_21054
#!/usr/bin/env python import os from core.utils import get_benchmark, parser from core.runner.RepairTask import RepairTask from core.runner.get_runner import get_runner if __name__ == "__main__": # Arja -b Bugs.jar -i Wicket-295e73bd # Arja -b Defects4J -i Chart-1 args = parser.parse_args() if "ben...
the-stack_106_21055
import copy import json import os import random import platform import subprocess import sys from collections import defaultdict import numpy as np import pytest import ray from ray.external_storage import (create_url_with_offset, parse_url_with_offset) from ray.test_utils import wait...
the-stack_106_21057
from model.contact import Contact from model.grroup import Group import random def test_del_contact_to_group(app, db, orm): # предусловие на наличие группы if len(db.get_group_list()) == 0: app.group.create(Group(name='test')) # предусловие на наличие контакта if len(db.get_contact_list()) == ...
the-stack_106_21059
#!/usr/bin/env python # -*- coding: utf-8 -*- """ screen_capture.py Description: Author: PhatLuu Contact: tpluu2207@gmail.com Created on: 2021/03/27 """ #%% # ================================IMPORT PACKAGES==================================== # Standard Packages import os import shutil import sys # Visualization Pa...
the-stack_106_21060
from django.test import override_settings from django.urls import reverse, reverse_lazy from django_webtest import WebTestMixin from reversion.models import Version from test_plus.test import TestCase from company.factories import CompanyFactory from pola.tests.test_views import PermissionMixin from pola.users.factori...
the-stack_106_21061
import pandas as pd import numpy as np import math import random from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.layers.recurrent import LSTM #% matplotlib inline import matplotlib.pyplot as plt random.seed(0) # 乱数の係数 random_factor = 0.05 # サイクルあたりのステップ数 ...
the-stack_106_21065
#Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. #This program is free software; you can redistribute it and/or modify it under the terms of the BSD 0-Clause License. #This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of ...
the-stack_106_21067
import os import pickle import tempfile from contextlib import contextmanager import nbformat import pytest from dagstermill import DagstermillError, define_dagstermill_solid from dagstermill.compat import ExecutionError from jupyter_client.kernelspec import NoSuchKernel from nbconvert.preprocessors import ExecutePrep...
the-stack_106_21068
# -*- coding: utf-8 -*- """ Copyright [2009-2020] EMBL-European Bioinformatics Institute 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...
the-stack_106_21070
"""Module containing utility functions to compare parameters and results""" __author__ = 'Robert Meyer' from collections import Sequence, Mapping import numpy as np import pandas as pd import scipy.sparse as spsp import pypet.slots as slots def results_equal(a, b): """Compares two result instances Checks...
the-stack_106_21071
# Copyright (C) 2021-2022, Mindee. # This program is licensed under the Apache License version 2. # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. # Credits: post-processing adapted from https://github.com/xuannianz/DifferentiableBinarization from copy import deepcop...
the-stack_106_21072
def check_membership(username, allowed=[], banned_sets={}): """ This function is badly written, but for once it is intentional. :param username: :param allowed: :return: """ """One more thing""" found = True if username == None: # noqa: B003 return False, f"Username not pro...
the-stack_106_21073
"""Verifica se o número recebido possui ao menos um digíto adjacente igual a ele""" numero = int(input('Digite um número inteiro: ')) tem_adjacente = False while numero > 0: ultimo_numero = numero % 10 penultimo_numero = (numero // 10) % 10 if ultimo_numero == penultimo_numero: tem_adjacente = True...
the-stack_106_21075
""" @file @brief Calls :epkg:`nbconvert` in command line for latex and pdf. """ import sys import warnings try: from nbconvert.nbconvertapp import main as nbconvert_main except AttributeError as e: raise ImportError("Unable to import nbconvert") from e def run_nbconvert(argv): try: nbconvert_main...
the-stack_106_21076
# -*- coding: utf-8 -*- # GUI Application automation and testing library # Copyright (C) 2006-2019 Mark Mc Mahon and Contributors # https://github.com/pywinauto/pywinauto/graphs/contributors # http://pywinauto.readthedocs.io/en/latest/credits.html # All rights reserved. # # Redistribution and use in source and binary f...
the-stack_106_21077
from MessageSentiment import MessageSentiment from Author import Author from Message import Message from HelperFunctions import find_author, make_authors import re, datetime, numpy, json, nltk, pickle, sys, math class ChatStat: """Base class for ChatStat""" __version__ = '1.0' def __init__(self, raw_messages, m...
the-stack_106_21080
import networkx as nx import markdown as md def parse_concepts(filename): """Takes a markdown file with with a certain structure and parses it to separate the concept and the relations between the concepts. Structure: # [Title] ## [Concept] [Some text] [Even Latex math] ### [A...
the-stack_106_21082
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('articles', '0046_articlepage_include_main_image_overlay'), ] operations = [ migrations.AddField( model_name='top...
the-stack_106_21083
import re import pygraphviz as pgv import sys from ..graph_helper import get_label, reserve_and_get_next_available_numbered_node_name, attr_encode, attr_decode from .. import DecisionGraphNode, decision_graph_from_agraph class DecisionBaseNode(DecisionGraphNode): def __init__(self, taken_succs=(), unsat_succs=()...
the-stack_106_21084
import FWCore.ParameterSet.Config as cms from TrackPropagation.SteppingHelixPropagator.SteppingHelixPropagatorAny_cfi import * cosmicMuonsBarrelOnlyFilter = cms.EDFilter("HLTMuonPointingFilter", SALabel = cms.InputTag("cosmicMuons"), PropagatorName = cms.string("SteppingHelixPropagatorAny"), radius = cms....
the-stack_106_21085
# Copyright 2017 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_21086
# Time: O((m * n) * (m * n)!) # Space: O((m * n) * (m * n)!) # On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, # and an empty square represented by 0. # # A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. # # The state of the board is solved if and only if...
the-stack_106_21089
def test_create_yaml_files(tmp_path): from infra2salt.utility import create_yaml_files, get_yaml_files input_data = {"first": { "first_a": "AAA", "first_b": "BBB", "first_c": "CCC" }, "second": { "second_a": "AAA", "second_b": "B...
the-stack_106_21092
#!/usr/bin/python #coding:utf-8 import os import time from selenium import webdriver import codecs # const variable SIZE_WIDTH = 780 SIZE_HEIGHT = 480 POS_WIDTH = 520 POS_HEIGHT = 1 # 様々なブラウザ連携を行う class Browser(): # ブラウザの初期設定 def __init__(self): # ブラウザの定義 # obj_options = we...
the-stack_106_21097
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import yaml from gdwrap.Gdwrap import Gdwrap CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) KEY_FILE = os.path.join(CURRENT_DIR, 'keys', 'keys.json') CREDENTIAL_FILE = os.path.join(CURRENT_DIR, 'keys', 'credential.json') def main(): gd = Gdwrap(K...
the-stack_106_21099
import numpy as np from .. import utils class SDFT(utils.Window): """Sliding Discrete Fourier Transform (SDFT). Initially, the coefficients are all equal to 0, up until enough values have been seen. A call to `numpy.fft.fft` is triggered once ``window_size`` values have been seen. Subsequent values ...
the-stack_106_21101
#!/usr/bin/env python # encoding: utf-8 import os import sys from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings from spiders.tweet import TweetSpider from spiders.comment import CommentSpider from spiders.follower import FollowerSpider from spiders.user import UserSpider fr...
the-stack_106_21103
from ..utils import current_ts, get_class from .config import Configurable from .datasets import BaseDataset class BaseTask(Configurable): def __init__(self, model, config): super().__init__(config) self.model = model # generate a task ID if not specified id = self.config.id ...
the-stack_106_21105
# GNU MediaGoblin -- federated, autonomous media hosting # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either versio...
the-stack_106_21106
#!/usr/bin/env python # coding: utf-8 # In[9]: import cv2 import numpy as np import os import pytesseract from collections import Counter # In[10]: CONFIDENCE = 0.5 #threshold probability for a label SCORE_THRESHOLD = 0.5 #a threshold used to filter boxes by score. IOU_THRESHOLD = 0.5 #threshold intersection ...
the-stack_106_21109
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains th...
the-stack_106_21110
# -*- coding: utf-8 -*- import os import shutil import pytest from constants import ( FILE, FILE_EXISTS, FILE_NOT_FOUND, FILES, FOLDER, FOLDERS, SCOPE, TEST_DATE, TEST_DIR, does_not_raise, ) from setups import ( mk_dir, setup_contains, setup_ls, setup_mk, s...
the-stack_106_21111
# Copyright Contributors to the Amundsen project. # SPDX-License-Identifier: Apache-2.0 import os from setuptools import setup, find_packages __version__ = '2.5.5' requirements_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'requirements.txt') with open(requirements_path) as requirements_file: ...
the-stack_106_21113
class Solution: def reverse(self, x: int) -> int: ''' 题目:Given a 32-bit signed integer, reverse digits of an integer. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem...
the-stack_106_21114
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W...
the-stack_106_21115
''' :created: 2019-09-24 @author: Leandro (cerberus1746) Benedet Garcia''' from pathlib import Path from typing import Union, Mapping, Iterable, List, Dict, Any PathType = Union[Path, str] DataDict = List[Dict[str, Any]] JsonValue = Union[int, str] JsonMapping = Mapping[str, JsonValue] JsonTypes = Union[JsonMapping...
the-stack_106_21116
""" :codeauthor: Alexander Schwartz <alexander.schwartz@gmx.net> """ import salt.client from salt.cloud.clouds import saltify from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import ANY, MagicMock, patch from tests.support.unit import TestCase TEST_PROFILES = { "testprofile1": No...
the-stack_106_21118
#!/usr/bin/env python # coding: UTF-8 import glob from PIL import Image, ImageChops def crop_alpha(img): bg = Image.new(img.mode, img.size, (0, 0, 0, 0)) diff = ImageChops.difference(img, bg) bbox = diff.getbbox() if bbox: return img.crop(bbox) return img def align_resize(img, size=512)...
the-stack_106_21121
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # Copyright 2018 New Vector 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...
the-stack_106_21123
from entityservice.async_worker import celery, logger from entityservice.database import DBConn, get_created_runs_and_queue, get_uploaded_encoding_sizes, \ get_project_schema_encoding_size, get_project_encoding_size, set_project_encoding_size, \ update_project_mark_all_runs_failed from entityservice.models.run ...
the-stack_106_21124
from django.contrib.contenttypes.models import ContentType from drf_yasg.utils import swagger_serializer_method from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from taggit_serializer.serializers import TaggitSerializer, TagListSerializerField from dcim.choices impor...
the-stack_106_21125
import os from typing import Any import numpy as np import pytest from jina.drivers.cache import BaseCacheDriver from jina.executors.indexers.cache import DocIDCache from jina.proto import jina_pb2, uid from tests import random_docs, rm_files filename = 'test-tmp.bin' class MockCacheDriver(BaseCacheDriver): @...
the-stack_106_21127
import datetime import time from urllib.parse import urlencode import requests from pandas import read_csv from geodataimport.compat import StringIO, binary_type, bytes_to_str from geodataimport.utils import RemoteDataError, _init_session, _sanitize_dates class _GeoData(object): """ Parameters ---------...
the-stack_106_21128
import speech_recognition as sr def reconhece(): rec = sr.Recognizer() with sr.Microphone() as s: rec.adjust_for_ambient_noise(s) while True: try: audio = rec.listen(s) entrada = rec.recognize_google(audio, language="pt") return "Você disse: {}".format(entrada) except sr.Unknow...
the-stack_106_21130
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W...
the-stack_106_21131
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import csv import datetime import os import signal import sys from time import time import uuid from warnings import warn from configobj import ConfigObj, ConfigObjError, flatten_errors from validate import Validator from logfile import write_metapop_dat...
the-stack_106_21133
''' Created on Mar 4, 2013 @author: Devindra The main class. Links the program together and then starts the fun. ''' from guppy import hpy import atexit import pyglet from regicide.mvc import State from regicide import model, view, controller from regicide.view import window def on_exit(): print("Exiting...") ...
the-stack_106_21134
import argparse import logging import os import pdb from torch.autograd import Variable import os.path as osp import torch from torch.optim.lr_scheduler import StepLR, MultiStepLR import numpy as np import resource import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import torch.opti...
the-stack_106_21137
#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import MassGridTestFramework from test_framework.util import * def read_d...
the-stack_106_21138
import json, pycurl from io import BytesIO class Couchpotato(): def __init__(self, host, port, api_key): self.__host = host self.__port = port self.__api_key = api_key self.reply = {} def __apicall(self, host, port, api_key, endpoint): buffer = BytesIO() c = p...
the-stack_106_21140
from glob import glob from pathlib import Path from typing import Callable, List, Optional import torch from torch_geometric.data import InMemoryDataset, extract_zip from torch_geometric.io import read_ply class CoMA(InMemoryDataset): r"""The CoMA 3D faces dataset from the `"Generating 3D faces using Convol...
the-stack_106_21141
# ------------------------------------------------------------------------ # MIT License # # Copyright (c) [2021] [Avinash Ranganath] # # This code is part of the library PyDL <https://github.com/nash911/PyDL> # This code is licensed under MIT license (see LICENSE.txt for details) # ------------------------------------...
the-stack_106_21142
#!/usr/bin/env python import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1,2,3], label="test") l = ax.legend() d1 = l.draggable() xy = 1, 2 txt = ax.annotate("Test", xy, xytext=(-30, 30), textcoords="offset points", bbox=dict(boxstyle="round",fc=(0.2, 1, 1)), ...
the-stack_106_21144
# Standard imports from typing import Union from pathlib import Path import functools # External imports import tqdm import numpy as np import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms _DEFAULT_DATASET_ROOT = "/opt/Datasets" _DEFAULT_MNIST_DIGIT = 6 # _MNIST_MEAN = 0.1...
the-stack_106_21145
"""PyTorch trainer module. - Author: Jongkuk Lim, Junghoon Kim - Contact: lim.jeikei@gmail.com, placidus36@gmail.com """ import os import shutil from typing import Optional, Tuple, Union import numpy as np import torch import torch.nn as nn import torch.optim as optim import torchvision from sklearn.metrics import f...
the-stack_106_21146
# %% # read data for tests import pandas as pd df = pd.read_csv('/Users/lukasgehrke/Documents/temp/chatham/LG_data_crdPhase1/df_scenario1_random_sample.csv') # df = df.sample(100000) # select random rows for faster debugging # df.to_csv('/Users/lukasgehrke/Documents/temp/chatham/LG_data_crdPhase1/df_scenario1_random_s...
the-stack_106_21147
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # Copyright (c) 2011 Piston Cloud Computing, Inc # Copyright (c) 2012 Univer...
the-stack_106_21148
import warnings import numpy as np import torch import torch.nn.functional as F from sklearn import metrics from torch.utils.data import DataLoader, SequentialSampler, TensorDataset from tqdm import tqdm from datasets.bow_processors.abstract_processor import StreamingSparseDataset # Suppress warnings from sklearn.me...
the-stack_106_21149
import numpy as np from bayes_implicit_solvent.molecule import Molecule from simtk import unit def sample_path_to_unitted_snapshots(path_to_npy_samples): xyz = np.load(path_to_npy_samples) traj = [snapshot * unit.nanometer for snapshot in xyz] return traj from glob import glob from pkg_resources import ...
the-stack_106_21152
# Manga API from bs4 import BeautifulSoup import requests # Finder # Manga_Name = {'Mangakakalot' : [['ul', 'class', 'manga-info-text'], 'h1'], 'Manganelo' : [['div', 'class', 'story-info-right'], 'h1'] } Image_Link = {'Mangakakalot' : [['div', 'class', 'manga-info-pic']], 'Man...
the-stack_106_21153
import _plotly_utils.basevalidators class ColorbarValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="colorbar", parent_name="streamtube", **kwargs): super(ColorbarValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
the-stack_106_21156
import sublime import os import time import base64 import logging import tempfile import threading from queue import Queue, Empty from .ptty import TerminalPtyProcess, TerminalScreen, TerminalStream from .utils import responsive, intermission from .view import panel_window, view_size from .key import get_key_code fro...
the-stack_106_21157
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('video/<str:video_code>/', views.watch_video, name='watch_video'), path('video/add_comment', views.add_comment, name='add_comment'), path('video/add_like/<str:video_code>/', views.add_like, n...