filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_0_4361 | import os
from alipay import AliPay
from django.conf import settings
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from orders.models import OrderInfo
... |
the-stack_0_4366 | from itertools import chain
import glob
import torch
from PIL import Image
from os import path
from torch.utils.data import Dataset
class SegmentationDataset(Dataset):
_EXTENSIONS = ["*.jpg", "*.jpeg", "*.png"]
def __init__(self, in_dir, transform):
super(SegmentationDataset, self).__init__()
... |
the-stack_0_4369 | #!/usr/bin/env python
###############################################################################
# Copyright (C) 1994 - 2009, Performance Dynamics Company #
# #
# This software is licensed as described in the file COP... |
the-stack_0_4372 | __author__ = 'Sergey Matyunin'
import numpy as np
def interp2linear(z, xi, yi, extrapval=np.nan):
"""
Linear interpolation equivalent to interp2(z, xi, yi,'linear') in MATLAB
@param z: function defined on square lattice [0..width(z))X[0..height(z))
@param xi: matrix of x coordinates wher... |
the-stack_0_4379 | import yaml
d = {'subcommand': 'lottery', 'platform': 'local', 'display_output_location': False, 'num_workers': 0, 'gpu': '6',
'replicate': 2, 'default_hparams': 'mnist_lenet_300_100', 'quiet': False, 'evaluate_only_at_end': False,
'levels': 0, 'rewinding_steps': None, 'pretrain': False, 'dataset_name': 'fas... |
the-stack_0_4380 | # -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import numpy as np
from alpharotate.utils.pretrain_zoo import PretrainModelZoo
from configs._base_.models.retinanet_r50_fpn import *
from configs._base_.datasets.dota_detection import *
from configs._base_.schedules.schedule_1x i... |
the-stack_0_4382 | #!/usr/bin/env python
# encoding: utf-8
import argparse
from zstacklib import *
start_time = datetime.now()
# set default value
file_root = "files/appliancevm"
pip_url = "https=//pypi.python.org/simple/"
proxy = ""
sproxy = ""
chroot_env = 'false'
zstack_repo = 'false'
post_url = ""
chrony_servers = None
pkg_applianc... |
the-stack_0_4383 | from typing import Union
from pydantic.types import UUID5
from account.models import JWTModel
import uuid
from time import time
from datetime import datetime, timedelta
from pathlib import Path
from config.conf import JWT_KEY_PATH, JWT_CERT_PATH
from cryptography.x509 import load_pem_x509_certificate
from fastapi impor... |
the-stack_0_4385 | import mdtraj as md
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
import scipy.optimize
import unyt as u
class BondCalculator:
def __init__(self, traj, T):
self.traj = traj
graph = traj.top.to_bondgraph()
bonds = self.identify_b... |
the-stack_0_4388 | # (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from __future__ import unicode_literals
import re
from ..._env import E2E_FIXTURE_NAME, deserialize_data
CONFIG_MESSAGE_PATTERN = 'DDEV_E2E_START_MESSAGE (.+) DDEV_E2E_END_MESSAGE'
def parse_config_from_resul... |
the-stack_0_4390 | # -*- coding: utf-8 -*-
import numpy as np
"""
This script is for outputting PC1/PC2/PC3 data from preprocd_dataset.npz
of MD 1000K-LCx3 samples
"""
def makePC123(dtsetfile, outfile, grpname):
dtset= np.load(dtsetfile, allow_pickle=True)
#allow_pickle op is for adapting spec change of numpy 1.16.3 and later
... |
the-stack_0_4391 | # 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 required by applicable law or a... |
the-stack_0_4392 | import time
import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
from transformers import BartTokenizer, BartForConditionalGeneration
import torch
device = "cuda" if torch.cuda.is_available() else ... |
the-stack_0_4393 | import requests
import json
import configparser as cfg
class telegram_chatbot():
def __init__(self, config):
self.token = self.read_token_from_config_file(config)
self.base = "https://api.telegram.org/bot{}/".format(self.token)
def get_updates(self, offset=None):
url = self.base + "g... |
the-stack_0_4394 | from discord.ext.commands import Cog
class Cancer(Cog):
def __init__(self, bot):
self.bot = bot
self.ok_list = [198101180180594688, 246291440106340352]
@Cog.listener()
async def on_member_join(self, member):
if member.guild.id not in self.ok_list:
return
await ... |
the-stack_0_4395 | import pandas as pd
train = pd.read_csv('../data/train_mapped.tsv', sep='\t', header=0)
data = pd.DataFrame(columns=['SentenceId','Phrase', 'Sentiment'])
temp = list(train['SentenceId'])
count = 1
for index, row in train.iterrows():
if row['SentenceId'] == count:
data = data.append(row[['SentenceId', '... |
the-stack_0_4396 | """
"""
from __future__ import division
from datetime import date
import logging
from date_helper import *
logger = logging.getLogger(__name__).addHandler(logger.NullHandler())
def check_date_objects(date1, date2):
if not(isinstance(date1, date) or isinstance(date2, date)):
raise InputError(expr = "Dates ... |
the-stack_0_4398 | # %% [markdown]
# ##
import os
import warnings
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
import numpy as np
import pandas as pd
import seaborn as sns
from joblib import Parallel, delayed
from sklearn.exceptions import ConvergenceWarning
from sklearn.manifold im... |
the-stack_0_4399 | """
Mask R-CNN
Multi-GPU Support for Keras.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
Ideas and a small code snippets from these sources:
https://github.com/fchollet/keras/issues/2436
https://medium.com/@kuza55/transparent-multi-gpu-training... |
the-stack_0_4401 | import random
import numpy as np
import skimage.color as sc
import torch
def get_patch(*args, patch_size=96, scale=2, multi=False, input_large=False):
ih, iw = args[0].shape[:2]
if not input_large:
p = scale if multi else 1
tp = p * patch_size
ip = tp // scale
else:
tp = ... |
the-stack_0_4402 | # Examples of mouse input
import simplegui
import math
# intialize globals
width = 450
height = 300
ball_list = []
ball_radius = 15
ball_color = "Red"
# helper function
def distance(p, q):
return math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)
# define event handler for mouse click, draw
def click(pos):
... |
the-stack_0_4403 | import time
import shelve
import datetime
import settings
from twython import Twython
from contextlib import contextmanager
@contextmanager
def closing(this):
try:
yield this
finally:
this.close()
class TwitterStats():
def __init__(self):
# connect to twitter api
self.twi... |
the-stack_0_4404 | #!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to us... |
the-stack_0_4405 | # Copyright 2016 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_0_4406 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 21 11:05:24 2017
The oil and sugar separation (pretreatment) section for the baseline lipid cane biorefinery is defined here as System objects. The systems include all streams and units starting from enzyme treatment to purification of the sugar sol... |
the-stack_0_4409 | #!/usr/bin/python3
class Rectangle():
number_of_instances = 0
print_symbol = "#"
def __init__(self, width=0, height=0):
self.height = height
self.width = width
Rectangle.number_of_instances += 1
def area(self):
return self.__height * self.__width
def perimeter(sel... |
the-stack_0_4411 | # -*- coding: utf-8 -*-
"""
Interpolation
=============
Defines the classes and definitions for interpolating variables.
- :class:`colour.KernelInterpolator`: 1-D function generic interpolation with
arbitrary kernel.
- :class:`colour.NearestNeighbourInterpolator`: 1-D function
nearest-neighbour interpolat... |
the-stack_0_4413 | import os
import numpy as np
from shapely import geometry, affinity
from pyquaternion import Quaternion
from shapely.geometry import Point
from nuscenes.eval.detection.utils import category_to_detection_name
from nuscenes.eval.detection.constants import DETECTION_NAMES
from nuscenes.utils.data_classes import LidarPoint... |
the-stack_0_4414 | import ast
import contextlib
import json
import os
import re
import sys
import threading
from datetime import timedelta
import pytest
import retrying
from six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from dcos import constants
from dcoscli.test.common import (assert_command, assert_lines, exec... |
the-stack_0_4415 | import unittest, traceback
from subprocess import TimeoutExpired
class TestcaseError(BaseException):
pass
class TestResult(unittest.TextTestResult):
def __init__(self, stream=None, descriptions=None, verbosity=0):
super(TestResult, self).__init__(stream, descriptions, verbosity)
self.success_... |
the-stack_0_4416 | from __future__ import print_function, division
import scipy
import torch.nn as nn
import torch.nn.functional as F
import torch
import functools
import datetime
import matplotlib.pyplot as plt
import sys
from data_loader import InMemoryDataLoader
import numpy as np
import pandas as pd
import os
import random
import... |
the-stack_0_4418 | # ----------------------------------------------------------------------------
# Copyright (c) 2020, Franck Lejzerowicz.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------... |
the-stack_0_4419 | from typing import Dict
from dbnd import parameter
from dbnd._core.settings import EngineConfig
from dbnd_docker.docker_ctrl import DockerRunCtrl
class AwsBatchConfig(EngineConfig):
"""Amazon Web Services Batch"""
_conf__task_family = "aws_batch"
job_definition = parameter(description="the job definitio... |
the-stack_0_4420 | import os
import sys
import numpy as np
import importlib
from dataclasses import dataclass
from loguru import logger
from tqdm import tqdm
import psutil
__all__ = [
'sanitize_filename',
'get_tqdm',
'show_docstring',
'Results',
]
def _is_ipython_notebook(): # pragma: no cover
try:
shell ... |
the-stack_0_4421 | import ezdxf
import random # needed for random placing points
def get_random_point():
"""Creates random x, y coordinates."""
x = random.randint(-100, 100)
y = random.randint(-100, 100)
return x, y
# Create a new drawing in the DXF format of AutoCAD 2010
dwg = ezdxf.new('ac1024')
# Create a block w... |
the-stack_0_4424 | from typing import Optional, Tuple
import torch
import torch.nn as nn
from torch.distributions import Categorical, Normal
class BasePolicy(nn.Module):
"""
Basic implementation of a general Policy
:param state_dim: State dimensions of the environment
:param action_dim: Action dimensions of the enviro... |
the-stack_0_4426 | from diff_prof.diffusion_profiles import DiffusionProfiles
from msi.msi import MSI
import os
import numpy as np
def test_diffusion_profiles(ref_dp_file_path, calculated_dp_file_path):
# Saved
# this is loading the reference directory
dp_saved = DiffusionProfiles(alpha=None, max_iter=None, tol=None,
... |
the-stack_0_4427 | # -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import os
import codecs
import numpy as np
import hashlib
import random
import preprocess
class Preparation(object):
'''Convert dataset of different text matching tasks into a unified format as the input of deep matching modules. Users pro... |
the-stack_0_4429 | import copy
import logging
import random
from typing import Any, Callable, Dict, List, Optional, Tuple
from generator import (
DefinitionDataset,
InteractiveGoal,
ObjectDefinition,
RetrievalGoal,
SceneException,
base_objects,
containers,
geometry,
materials,
specific_objects,
... |
the-stack_0_4433 | import collections
from nltk import NaiveBayesClassifier, DecisionTreeClassifier
from nltk.metrics import precision, recall, f_measure
from nltk.classify import apply_features, accuracy
from nltk.classify.scikitlearn import SklearnClassifier
from prueba_paquete.utils import clean_html_tags, shuffled, tokenize_and_stem
... |
the-stack_0_4435 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
import threading
from PyQt6 import QtCore
class Socket_server():
"""
A class for creating and listening the socket server that connect errors messages from device modules
and a dedicated text box in the main window of the programm.
"""
d... |
the-stack_0_4436 | #!/usr/bin/env python3
"""
Functions for finding and killing processes
"""
import os
import psutil
import signal
import time
def process_exists(pid):
"""
Determine if process 'pid' exists.
"""
try:
os.kill(pid, 0)
except ProcessLookupError:
return False # Doesn't exist
exc... |
the-stack_0_4437 | from __future__ import absolute_import, division, print_function
import pytest
import numpy as np
from glue.core import Data
from glue.tests.helpers import requires_h5py
from ..hdf5 import hdf5_writer
DTYPES = [np.int16, np.int32, np.int64, np.float32, np.float64]
@requires_h5py
@pytest.mark.parametrize('dtype', ... |
the-stack_0_4438 | import torch
import torch.nn as nn
from torchvision import models
class BaseModel_scratch(nn.Module):
def __init__(self, model_name, eps=3, num_classes=200, init_weights=True):
super().__init__()
if model_name == 'vgg16bn':
backbone = nn.Sequential(*list(models.vgg16_bn(pretrained=Fals... |
the-stack_0_4439 | # -*- coding: utf-8 -*-
# Copyright 2013-2021 CERN
#
# 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 a... |
the-stack_0_4440 | # Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Test Access Control roles propagation."""
from ggrc.models import all_models, get_model
from integration.ggrc import TestCase
from integration.ggrc.models import factories
from integration.ggrc_basic_perm... |
the-stack_0_4441 | # 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_0_4443 | import datetime
from casexml.apps.case.models import CommCareCaseAction
from corehq.apps.reports.standard.cases.basic import CaseListReport
from corehq.apps.api.es import ReportCaseES
from corehq.apps.reports.generic import GenericTabularReport
from corehq.apps.reports.basic import BasicTabularReport, Column
from coreh... |
the-stack_0_4444 | # 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_0_4445 | """
ViP training and evaluating script
This script is modified from pytorch-image-models by Ross Wightman (https://github.com/rwightman/pytorch-image-models/)
It was started from an early version of the PyTorch ImageNet example
(https://github.com/pytorch/examples/tree/master/imagenet)
"""
import argparse
import time
i... |
the-stack_0_4446 | #!/usr/bin/python
"""
(C) Copyright 2020-2021 Intel Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
"""
import re
from apricot import TestWithServers
from daos_perf_utils import DaosPerfCommand
from command_utils_base import CommandFailure
class DaosPerfBase(TestWithServers):
"""Base test cases fo... |
the-stack_0_4447 | import numpy as np
from random import shuffle
from scipy.sparse import csr_matrix
class SVM:
def __init__(self, learning_rate=1, regularization_loss_tradeoff=1):
self.learning_rate = learning_rate
self.regularization_loss_tradeoff = regularization_loss_tradeoff
def train(self, train, labels, ... |
the-stack_0_4449 | from dataclasses import dataclass, field
from typing import List
__NAMESPACE__ = "NISTSchema-SV-IV-list-negativeInteger-maxLength-2-NS"
@dataclass
class NistschemaSvIvListNegativeIntegerMaxLength2:
class Meta:
name = "NISTSchema-SV-IV-list-negativeInteger-maxLength-2"
namespace = "NISTSchema-SV-I... |
the-stack_0_4453 | import pygame
import random
import os
pygame.init()
win = pygame.display.set_mode((700, 700))
pygame.display.set_caption("Falling Blocks")
script_dir = os.path.dirname('Obstacles')
rel_path = r"/Users/alecdewulf/Desktop/Falling-Blocks/Images/Obstacles"
abs_file_path = os.path.join(script_dir, rel_path)
# loading o... |
the-stack_0_4454 | """Handle presentation exchange information interface with non-secrets storage."""
from marshmallow import fields
from ....messaging.models.base_record import BaseRecord, BaseRecordSchema
class PresentationExchange(BaseRecord):
"""Represents a presentation exchange."""
class Meta:
"""PresentationEx... |
the-stack_0_4455 | # Copyright (c) 2020 PaddlePaddle 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 appli... |
the-stack_0_4457 | """Module to define main fnet model wrapper class."""
from pathlib import Path
from typing import Callable, Iterator, List, Optional, Sequence, Tuple, Union
import logging
import math
import os
from scipy.ndimage import zoom
import numpy as np
import tifffile
import torch
from fnet.metrics import corr_coef
from fne... |
the-stack_0_4462 | # Copyright (c) 2012-2017 Snowflake Computing Inc. All rights reserved.
"""
test_tokens.py - This defines a series of tests to ascertain that we are
capable of renewing JWT tokens
"""
from snowflake.ingest.utils import SecurityManager
from snowflake.ingest.error import IngestClientError
from snowflake.ingest.errorcod... |
the-stack_0_4463 | """
Ethereum Virtual Machine (EVM) Keccak Instructions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. contents:: Table of Contents
:backlinks: none
:local:
Introduction
------------
Implementations of the EVM keccak instructions.
"""
from ethereum.base_types import U256, Uint
from ethereum.crypto.has... |
the-stack_0_4464 | from typing import Any, Dict, Optional, Union
from uuid import uuid4
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.crud.crud_user import user
from app.models.login_link import LoginLink
from app.schemas.login_link import LoginLinkCreate, LoginLinkUpdate
class CRUDLoginLink(CRUDBase[... |
the-stack_0_4466 | import random
import torch
import sys
import torch.nn as nn
import torchaudio
import bz2
import pickle
import torchvision.transforms as transforms
import cv2
import math
import os
import numpy as np
from torch.utils.data import Dataset, DataLoader
from logging import Logger
from torchvision.transforms.transforms impo... |
the-stack_0_4470 | from distutils import log
from weaverbird.backends.sql_translator.steps.utils.query_transformation import (
build_selection_query,
)
from weaverbird.backends.sql_translator.types import (
SQLPipelineTranslator,
SQLQuery,
SQLQueryDescriber,
SQLQueryExecutor,
SQLQueryRetriever,
)
from weaverbird.... |
the-stack_0_4474 | # 深海棲艦の装備一覧のURL
from typing import Dict, Tuple, List
import lxml.html
import requests
from model.weapon import Weapon
from model.weapon_type import WeaponType
ENEMY_WEAPON_DATA_URL = 'https://kancolle.fandom.com/wiki/List_of_equipment_used_by_the_enemy'
# 装備種テキストと装備種との対応表
WEAPON_TYPE_DICT: Dict[str, WeaponType] = {... |
the-stack_0_4475 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from foundation_tenant.models.base.abstract_thing import AbstractThing
class TagManager(models.Manager):
def delete_all(self):
items = Tag.objects.all()
for item in items.all():
item.delete()
class T... |
the-stack_0_4477 | from fasteve import Fasteve, BaseSchema, Resource, ObjectID, SubResource
from fasteve.utils import Unique, DataRelation
from typing import Optional, List, NewType, Union, Any
from pydantic import EmailStr, SecretStr, Field, BaseModel
from datetime import datetime
from time import sleep
class Data(BaseSchema):
dat... |
the-stack_0_4479 | import json
from os import urandom
import urllib
import urlparse
import flask
import requests
from requests_oauthlib import OAuth1 as OAuth1Manager
from oauthlib.oauth1.rfc5849 import SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER
from oauthlib.oauth2.draft25 import tokens
from werkzeug.urls import url_decode
from foauth... |
the-stack_0_4480 |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from tensorflow.python.keras import Sequential
from tensorflow.python.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from replay_buffer import ReplayBuffer
def DeepQNetwork(lr, num_... |
the-stack_0_4481 | import re
from lxml import etree
from pyramid.settings import asbool
from .exception import ConfigurationError
def clean_oai_settings(settings):
"""Parse and validate OAI app settings in a dictionary.
Check that the settings required by the OAI app are in the settings
dictionary and have vali... |
the-stack_0_4482 | import pygame.font
class Button():
"""Basic button, since pygame doesn't have it built-in"""
def __init__(self, ai_game, message):
"""Initialize button attributes"""
self.screen = ai_game.screen
self.screen_rect = self.screen.get_rect()
self.width, self.height = 200, 50
... |
the-stack_0_4483 | #! /usr/bin/python
import argparse
import glob
import os
import sys
import tarfile
def parse_args():
parser = argparse.ArgumentParser()
products = ["rdn", "obs_ort", "loc", "igm", "glt"]
formats = ["envi", "hdf"]
parser.add_argument("-p", "--product",
help=("Choose one of the ... |
the-stack_0_4484 | import logging
import os
from pythonjsonlogger import jsonlogger
def setup_logging(log_level):
logger = logging.getLogger()
logger.setLevel(log_level)
handler = logging.StreamHandler()
handler.setFormatter(
jsonlogger.JsonFormatter(
fmt='%(asctime)s %(levelname)s %(lambda)s %(m... |
the-stack_0_4485 | import speech_recognition
import re
name = re.compile(r'(name is | nome é)(.*)', re.IGNORECASE)
goodbye = re.compile(r'(.*)(goodbye)(.*)', re.IGNORECASE)
recognizer = speech_recognition.Recognizer()
with speech_recognition.Microphone() as source:
print("Say something!")
audio = recognizer.listen(source)
pr... |
the-stack_0_4487 | """
:ref:`chainladder.methods<methods>`.MackChainladder
===================================================
:ref:`MackChainladder<mack>` produces the same IBNR results as the deterministic
approach, but ldf selection happens in a regression framework that allows for
the calculation of prediction errors. The Mack Chai... |
the-stack_0_4488 | """
pygments.cmdline
~~~~~~~~~~~~~~~~
Command line interface.
:copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import os
import sys
import getopt
from textwrap import dedent
from pygments import __version__, highlight
from pygments.ut... |
the-stack_0_4489 | # Copyright 2019 Open End AB
#
# 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, s... |
the-stack_0_4490 | """
A stress-test of sorts for LLDB's handling of threads in the inferior.
This test sets a breakpoint in the main thread where test parameters (numbers of
threads) can be adjusted, runs the inferior to that point, and modifies the
locals that control the event thread counts. This test also sets a breakpoint in
breakp... |
the-stack_0_4491 | import socket
host = '127.0.0.1'
port = 4000
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
client.send(b'Hello! Is there anybody in there?!')
response = client.recv(4096)
print(response)
|
the-stack_0_4496 | import argparse
import datetime
import logging
import requests
import rdflib
import sys
import tempfile
import time
import urllib
import xml.etree.ElementTree as ET
def run():
parser = argparse.ArgumentParser(description='Finds vocabulary concepts (identifying them by a namespace) in a triplestore and enriches th... |
the-stack_0_4497 | # stdlib
from typing import Any
from typing import Optional
# third party
from torch import device
# relative
from ...core.common.serde.serializable import serializable
from ...proto.lib.torch.device_pb2 import Device as Device_PB
# use -2 to represent index=None
INDEX_NONE = -2
def object2proto(obj: device) -> "D... |
the-stack_0_4500 | from base64 import b64encode
from base64 import b64decode
from threading import local
import boto3
import six
__all__ = [
'_as_bytes',
'b64_str',
'from_b64_str',
'_get_client',
'_prefix_alias',
]
thread_local = local()
thread_local.sessions = {}
def _as_bytes(value):
if isinstance(value, s... |
the-stack_0_4502 | #! /usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import math
import unittest
import torch
from botorch import fit_gpytorch_model
from botorch.models import SingleTaskGP
from botorch.optim.fit import (
OptimizationIteration,
fit_gpytorch_scipy,
fit_gpytorch_to... |
the-stack_0_4503 | # SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2015, ARM Limited, Google and contributors.
#
# 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-... |
the-stack_0_4504 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# ... |
the-stack_0_4505 |
import psycopg2
import psycopg2.extras
from ..sql import SqlMinqlClient
class PostgresqlMinqlClient(SqlMinqlClient):
def __init__(self, address, name, user, password, *args, **kwargs):
url, port = address.split(':')
params = "dbname='%s' user='%s' password='%s' host='%s' port='%s'" % (name, use... |
the-stack_0_4506 | import random
from models import model
def create_room(room_type, room_name, dojo):
"""
input : room_type -> string represent type of room_type
room_name -> string represent name of room_name
output : returns -> return Room with name -> room_name
Raises -> TypeError if room_name exists
... |
the-stack_0_4507 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
import os
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Type
import pytorch_lightning as pl # type: ignore
from d2go.config import CfgNode, temp_defrost, auto_scale_world_si... |
the-stack_0_4509 | # Copyright The PyTorch Lightning team.
#
# 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 i... |
the-stack_0_4510 | import numpy as np
import pandas as pd
from hamcrest import assert_that, has_item
import cifrum as lib
from conftest import decimal_places
from cifrum._settings import _MONTHS_PER_YEAR
__asset_name = 'index/OKID10'
def test__present_in_available_names():
sym_ids = [x.fin_sym_id.format() for x in lib.available_n... |
the-stack_0_4516 | #!/usr/bin/env python
from __future__ import print_function
import thread
import socket
import argparse
import sys, time, os, glob, shutil, math, datetime
from tmuxsend import TmuxSend
def run_server(port):
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsoc... |
the-stack_0_4517 | #!/usr/bin/env python
import click
import json
import os
import shutil
import subprocess
import uuid
LOGISTICIAN_ROOT = os.path.dirname(os.path.abspath(__file__))
CONFIG_PATH = os.path.expanduser("~/.logistician/")
def random_id():
return str(uuid.uuid4()).split("-")[0]
def write_to_file(path, contents):
... |
the-stack_0_4519 | """
This script takes a pre-trained Spatial Transformer and applies it to an unaligned dataset to create an aligned and
filtered dataset in an unsupervised fashion. By default, this script will only use the similarity transformation
portion of the Spatial Transformer (rotation + crop) to avoid introducing warping artif... |
the-stack_0_4521 | from glob import glob
import pandas as pd
import process_trial
import json, os
from tqdm import tqdm
print(os.getcwd())
print('Process testset')
for test_group in tqdm(glob('data/raw/*/metrics_*.csv')):
try:
platform = test_group.split('/')[2]
df = pd.read_csv(test_group)
df['init_time'] =... |
the-stack_0_4523 | #!/usr/bin/env python3
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import argparse
import os
import platform
import shutil
import subprocess
import sys
import time
from vmstat import capture_sample
from vmstat import plot_output
from vmstat import print_output_to_file
def main():
args = parse_args()
... |
the-stack_0_4525 | import json
from contextlib import contextmanager
from datetime import datetime, timedelta
from xml.sax.saxutils import unescape
from mock import patch
from casexml.apps.case.models import CommCareCase
from casexml.apps.case.sharedmodels import CommCareCaseIndex
from corehq.apps.domain.shortcuts import create_domain... |
the-stack_0_4528 | import http.server
class MyHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == "good":
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write(b"A good request")
retu... |
the-stack_0_4531 | import argparse
import logging
from dvc.command.base import CmdBase, append_doc_link
from dvc.exceptions import DvcException
logger = logging.getLogger(__name__)
class CmdRun(CmdBase):
def run(self):
if not any(
[
self.args.deps,
self.args.outs,
... |
the-stack_0_4532 | from functools import lru_cache as memoized
import os
from os import path
import sys
import yaml
import geopandas as gpd
from mapshader.colors import colors
from mapshader.io import load_raster
from mapshader.io import load_vector
from mapshader.transforms import get_transform_by_name
import spatialpandas
class Ma... |
the-stack_0_4535 | # Copyright 2002 by Andrew Dalke. All rights reserved.
# Revisions 2007-2016 copyright by Peter Cock. All rights reserved.
# Revisions 2008-2009 copyright by Cymon J. Cox. All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or th... |
the-stack_0_4536 | # coding: utf-8
"""
Module containing various definitions of Stores.
Stores are a default access pattern to data and provide
various utilities
"""
import json
import yaml
from itertools import chain, groupby
from socket import socket
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
import mongomoc... |
the-stack_0_4538 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django import forms
from django.contrib.auth import get_user_model
from django.forms.utils import ErrorDict
from django.utils.translation import ugettext_lazy as _
from shop.conf import app_settings as shop_settings
from shop.modifie... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.