filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_17698 | import tensorflow as tf
import numpy as np
from ares.attack.base import BatchAttack
from ares.attack.utils import get_xs_ph, get_ys_ph
class DeepFool(BatchAttack):
''' DeepFool. A white-box iterative optimization method. It needs to calculate the Jacobian of the logits with
relate to input, so that it only a... |
the-stack_106_17699 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Create a nifti image from a numpy array and an affine transform."""
import os
import numpy as np
from nipy.core.api import fromarray, Affine
from nipy.io.api import save_image, load_image
from nipy.ut... |
the-stack_106_17700 | from __future__ import absolute_import, division, print_function
import iotbx.pdb
import iotbx.cif.model
import iotbx.phil
import libtbx
from libtbx.utils import Usage, format_cpu_times
import sys, os
master_phil = iotbx.phil.parse("""
join_fragment_files {
reset_atom_serial = True
.type = bool
model_file = No... |
the-stack_106_17701 | #!/usr/bin/env python3
# vim: set ai et ts=4 sw=4:
import sys
if len(sys.argv) < 4:
print("Usage: " + sys.argv[0] + " input.txt frame.dat payload.dat")
sys.exit(1)
infile = sys.argv[1]
framefile = sys.argv[2]
payloadfile = sys.argv[3]
peak_threshold = 0.1
step_threshold = 0.25
peak_reports = 50
eps = 0.01
vm... |
the-stack_106_17703 | from ailment.expression import BinaryOp, BasePointerOffset, Const
from .base import PeepholeOptimizationExprBase
class BasePointerOffsetAddN(PeepholeOptimizationExprBase):
__slots__ = ()
name = "(Ptr - M) + N => Ptr - (M - N)"
expr_classes = (BinaryOp, ) # all expressions are allowed
def optimize(... |
the-stack_106_17706 | import tensorflow as tf
import tensorflow.keras as keras
import numpy as np
from tqdm import tqdm
import os
import datetime
import logging
from mnist_loader import MNISTLoader
from mnist_model import Teacher_model, Student_model
from mnist_backdoor import Backdoor
# log dir
log_dir = os.path.join('.\lo... |
the-stack_106_17707 | #################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... |
the-stack_106_17708 | """
This initialization scripts will create CUDA context and initialize UCX-Py,
depending on user parameters.
It is sometimes convenient to initialize the CUDA context, particularly before
starting up Dask workers which create a variety of threads.
To ensure UCX works correctly, it is important to ensure it is initia... |
the-stack_106_17710 | from django.urls import path
from . import views
from django.views.generic.base import TemplateView
urlpatterns = {
path('add_annotation', views.add_annotation),
path('getChatGroupPapers', views.getChatGroupPapers),
path('getChatGroupMembers', views.getChatGroupMembers),
path('createChatGroup', views.c... |
the-stack_106_17711 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="hvvabfahrtsmonitor",
version="0.1.1",
author="Manuel Catu",
author_email="m.cantu.reinhard@gmail.com",
description="Do requests to the hvv abfahrtsmonitor and get parsed data",
long_de... |
the-stack_106_17713 | # coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from enum import Enum
from typing import TYPE_CHECKING
from ._generated.models import ContentProperties
if TYPE_CHECKING:
from ._generated.models im... |
the-stack_106_17714 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, Nathan Davison <ndavison85@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_ve... |
the-stack_106_17715 | """===========================
Pipeline template
===========================
.. Replace the documentation below with your own description of the
pipeline's purpose
Overview
========
This pipeline computes the word frequencies in the configuration
files :file:``pipeline.yml` and :file:`conf.py`.
Usage
=====
See ... |
the-stack_106_17716 | """Plot the history of the drag coefficient."""
from matplotlib import pyplot
import numpy
import pathlib
from scipy import signal
import petibmpy
from kinematics import Am, D, f, rho, Um, w
show_figure = True # if True, display the figure(s)
# Load drag force from file.
simudir = pathlib.Path(__file__).absolute... |
the-stack_106_17717 | # -*- coding: utf-8 -*-
import time
from six import raise_from
from .backoff import Backoff
from .errors import ErrorWhitelist
from .strategies import ConstantBackoff
from .exceptions import MaxRetriesExceeded, RetryError, RetryTimeoutError
class Retrier(object):
"""
Implements a simple function retry mechani... |
the-stack_106_17718 | from datetime import datetime
import os
import sys
import discord
from discord.ext import commands
import psutil
from x86 import helpers
class About:
"""Commands that display information about bot, guild, user, etc"""
@commands.command(aliases=["botinfo","about"])
@commands.cooldow... |
the-stack_106_17722 | #!/usr/bin/env python3
# Copyright (c) 2014-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.
#
# Test node handling
#
from test_framework.test_framework import BitcoinOilTestFramework
from test_fra... |
the-stack_106_17724 | import random
from collections import OrderedDict
import numpy as np
import torch
import torch.distributed as dist
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import DistSamplerSeedHook, Runner
from mmdet.core import (DistEvalHook, DistOptimizerHook, Fp16OptimizerHook,
... |
the-stack_106_17725 | # Copyright 2019 TerraPower, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
the-stack_106_17727 | def comp_axes(
self,
axes_list,
machine=None,
axes_dict_in=None,
is_periodicity_a=None,
is_periodicity_t=None,
per_a=None,
is_antiper_a=None,
per_t=None,
is_antiper_t=None,
):
"""Compute simulation axes such as time / angle / phase axes, with or without periodicities
and ... |
the-stack_106_17729 | """This is a somewhat delicate package. It contains all registered components
and preconfigured templates.
Hence, it imports all of the components. To avoid cycles, no component should
import this in module scope."""
import logging
import warnings
import typing
from typing import Any, Dict, List, Optional, Text, Type... |
the-stack_106_17731 | from random import choice
from typing import Type
from Coolapk.object import Account
import base64
import string
from Coolapk.Exception import LoginError, LoginErrorAttributes
def randomNumber():
"""
:return: 返回酷安登录所需的随机数
"""
number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
randomNumber = '0... |
the-stack_106_17732 | #
# The Python Imaging Library
# $Id$
#
# base class for raster font file parsers
#
# history:
# 1997-06-05 fl created
# 1997-08-19 fl restrict image width
#
# Copyright (c) 1997-1998 by Secret Labs AB
# Copyright (c) 1997-1998 by Fredrik Lundh
#
# See the README file for information on usage and redis... |
the-stack_106_17733 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 23 08:04:48 2020
@author: Mursito
"""
import random
from halma_model import HalmaModel
class HalmaPlayer:
nama = "Pemain"
deskripsi = "Random Strategy"
nomor = 1
index = 0
papan = []
teman = None
def __init__(self, ... |
the-stack_106_17734 | import os, sys, json
from flask import abort
from polarishub_flask.server.parser import printv
settings = {}
def load_settings():
with open(os.path.join(os.getcwd(), 'server', 'settings.json')) as f:
return json.load(f)
def get_settings():
global settings
if settings == {} or settings is None:
... |
the-stack_106_17737 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/r... |
the-stack_106_17738 | import collections.abc
import copy
import datetime
import decimal
import operator
import uuid
import warnings
from base64 import b64decode, b64encode
from functools import partialmethod, total_ordering
from django import forms
from django.apps import apps
from django.conf import settings
from django.core import checks... |
the-stack_106_17739 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest # noqa
from parglare import Grammar, Parser, ParseError, ParserInitError, \
GrammarError, DisambiguationError
from parglare.actions import pass_single, pass_nochange, collect
def test_parse_list_of_integers():
grammar = """
Nu... |
the-stack_106_17740 | from django import http
from django.conf import settings
from django.contrib import messages
from django.shortcuts import redirect
from django.utils.translation import gettext as _
from django.views import generic
from paypal.payflow import facade, models
class TransactionListView(generic.ListView):
model = mode... |
the-stack_106_17741 | """show_mcast.py
IOSXE parsers for the following show commands:
* show ip mroute
* show ipv6 mroute
* show ip mroute
* show ip mroute vrf <vrf_name>
* show ipv6 mroute
* show ipv6 mroute vrf <vrf_name>
* show ip mroute static
* show ip mroute vrf <vrf_name> static
* show ip multica... |
the-stack_106_17742 | from FnAssetAPI.ui.toolkit import QtCore, QtGui, QtWidgets
import FnAssetAPI
import nuke
from . import filters
class KnobChangedAggregator(object):
"""
Nuke currently communicates selection with a knobChanged event, and the
'selected' knob. So we have to keep track of which are selected during a drag
as we d... |
the-stack_106_17744 | # Copyright 2012 OpenStack Foundation
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 - 2012 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
#... |
the-stack_106_17745 | # -*- coding: utf-8 -*-
#
# Module providing the `Pool` class for managing a process pool
#
# multiprocessing/pool.py
#
# Copyright (c) 2006-2008, R Oudkerk
# Licensed to PSF under a Contributor Agreement.
#
from __future__ import absolute_import
#
# Imports
#
import copy
import errno
import itertools
import os
import... |
the-stack_106_17746 | from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="pyschemagen",
version="0.0.4",
author='alexwhb',
description="A package to generate orator DB schemas from a python dict.",
long_description=long_description,
long_description_content_... |
the-stack_106_17747 | import json
from packlib.base import ProxmoxAction
class NodesNodeStorageStorageRrddataAction(ProxmoxAction):
"""
Read storage RRD statistics.
"""
def run(self, node, storage, timeframe, cf=None, profile_name=None):
super().run(profile_name)
# Only include non None arguments to pass ... |
the-stack_106_17748 | import torch
import logging
import os
import io
from torchtext.utils import download_from_url, extract_archive
from torchtext.vocab import build_vocab_from_iterator
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import Vocab
from torchtext.data.functional import numericalize_tokens_from_iterator
U... |
the-stack_106_17749 | import os
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import graphviz as gv
class HiddenMarkovModel:
def __init__(
self,
observable_states,
hidden_states,
transition_matrix,
emission_matrix,
title="HMM",
):
... |
the-stack_106_17752 | import json
import http.client
import csv
#Setup the Parameter of Premiumize and your NAS
params = open('params.csv', "r")
for line in params:
line = line.split(',')
if line[0] == 'synAccName':
synAccName = line[1].rstrip()
elif line[0] == 'synAccPw':
synAccPw = line[1].rstrip()
elif line[0] == 'sy... |
the-stack_106_17754 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A distribution contains the meta data for a major grouping of packages
within a :class:Repository, such as all of those used for a major release.
All of the packages in a repo are expected to be compatible with a system,
although some may conflict directly with each ... |
the-stack_106_17755 | ####################
# Import Libraries
####################
import os
import sys
from PIL import Image
import cv2
import numpy as np
import pandas as pd
import pytorch_lightning as pl
from pytorch_lightning.metrics import Accuracy
from pytorch_lightning import loggers
from pytorch_lightning import seed_e... |
the-stack_106_17760 | # coding: utf8
import logging
import os
import subprocess
from kalliope.core.Utils.FileManager import FileManager
logging.basicConfig()
logger = logging.getLogger("kalliope")
class PlayerModule(object):
"""
Mother class of Players.
Ability to convert mp3 to wave format.
"""
def __init__(self, ... |
the-stack_106_17761 | #!/usr/bin/env python3
# Copyright (c) 2009-2019 The Bitcoin Core developers
# Copyright (c) 2014-2019 The DigiByte Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the listsincelast RPC."""
from test_framew... |
the-stack_106_17763 | from __future__ import absolute_import
from __future__ import print_function
from dpark.serialize import load_func, dump_func
import sys
import operator
from six.moves import range
if sys.version_info[0] < 3:
def next_func(it):
return it.next
else:
def next_func(it):
return it.__next__
class ... |
the-stack_106_17764 | # -*- coding: utf-8 -*-
import json
from math import sqrt
from typing import List
from flask import Flask, request, Response, jsonify
from flask_cors import CORS
from sliding_puzzle import Puzzle, TypePuzzle
from sliding_puzzle.algorithm import get_algorithm
app = Flask(__name__)
application = app
CORS(application)... |
the-stack_106_17765 | #! /usr/bin/env python3
"""Checks file name lengths
Copyright (C) 2019-2021 kaoru https://www.tetengo.org/
"""
import os
import subprocess
import sys
from typing import List
import list_sources
max_length: int = 80
def main(args: List[str]) -> None:
"""The main function.
Args:
args (list[str... |
the-stack_106_17767 | import sys
def minPalPartion(str1):
n = len(str1);
C = [0]*(n+1);
P = [[False for x in range(n+1)] for y in range(n+1)];
for i in range(n):
P[i][i] = True;
for L in range(2, n + 1):
for i in range(n - L + 1):
j = i + L - 1;
... |
the-stack_106_17768 | """ Utility functions that simplify defining field of dataclasses.
"""
import argparse
import dataclasses
import enum
import functools
import inspect
import json
import warnings
from collections import OrderedDict
from dataclasses import _MISSING_TYPE, MISSING
from enum import Enum
from typing import (
Any,
Ca... |
the-stack_106_17770 | import os
from .memory_index import MemoryIndex
from ..utils.serialization import dump_object, load_object
class PersistentIndex(MemoryIndex):
"""An extension of the in-memory index class that commits index
changes to disk."""
def __init__(self, index_path: str) -> None:
super().__init__()
... |
the-stack_106_17771 | import sys
import os
import json
import re
import numpy as np
#import pandas as pd
from... |
the-stack_106_17772 | import os
import random
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from sklearn.metrics import accuracy_score, roc_auc_score
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import LabelEncoder
from torch import nn, optim
from torch.utils.data import Data... |
the-stack_106_17773 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Benjamin Vial
# License: MIT
import json
import os
from urllib.request import urlretrieve
def _get_data_path(data_path=None):
"""Return path to data dir.
This directory stores large datasets required for the examples, to avoid
downloading the data... |
the-stack_106_17776 | #!/usr/bin/env python3
"""Calculates the Frechet Inception Distance (FID) to evalulate GANs
The FID metric calculates the distance between two distributions of images.
Typically, we have summary statistics (mean & covariance matrix) of one
of these distributions, while the 2nd distribution is given by a GAN.
When run... |
the-stack_106_17777 | # -*- coding: utf-8 -*-
# stdlib imports
import subprocess
import re
import sys
# third-party imports
import pytest
import toml
HISTKEY = "black/mtimes"
def pytest_addoption(parser):
group = parser.getgroup("general")
group.addoption(
"--black", action="store_true", help="enable format checking wi... |
the-stack_106_17778 | # 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_17779 | import unittest
import os
import importlib
import glob
import matplotlib
matplotlib.use("Agg")
dirname, filename = os.path.split(os.path.abspath(__file__))
example_dir = dirname.split(os.path.sep)[:-2] + ["examples"]
dirs_to_test = ["07-nsem", "08-vrm", "09-flow", "10-pgi", "20-published"]
class ExampleTest(unitt... |
the-stack_106_17782 | #!/usr/bin/env python
import subprocess, time, csv
from multiprocessing import Pool
QUEUE_SIZE = 3
SLEEP_TIME = 1 #in minutes
WAIT_TIME = 4*60 #in minutes
max_trial = WAIT_TIME//SLEEP_TIME
def execute_command(command_tuple):
qsub_command = command_tuple[0]
command_id = command_tuple[1]
tmp_file = 'tmp/comm_'+... |
the-stack_106_17783 | """
Provides helper functions to parse url/query
parameters from aiohttp.
"""
def parse_int(value, allow_non_zero=False):
"""
Parses the given value and returns
it as an integer.
Args:
value (str): The string to be parsed.
allow_non_zero (bool): If False, all values below 1 will
... |
the-stack_106_17785 | import logging
import os
from abc import ABC, abstractmethod
from typing import Optional
from checkov.terraform.module_loading.content import ModuleContent
from checkov.terraform.module_loading.registry import module_loader_registry
# ModuleContent allows access to a directory containing module file via the `path()`... |
the-stack_106_17786 | import overpy
import numpy as np
from selfdrive.mapd.lib.geo import R
def create_way(way_id, node_ids, from_way):
"""
Creates and OSM Way with the given `way_id` and list of `node_ids`, copying attributes and tags from `from_way`
"""
return overpy.Way(way_id, node_ids=node_ids, attributes={}, result=from_way.... |
the-stack_106_17788 |
import unittest
from unittest import TestCase
import numpy as np
import os, sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import src.data_processing as data_processing
class TestDataProcessing(TestCase):
def test_reading_file(self):
"""
"""
test_filepath = "../data/test_data/basic_test_data.txt"
... |
the-stack_106_17790 | """
custom-menu setup
"""
import json
from pathlib import Path
from jupyter_packaging import (
create_cmdclass,
install_npm,
ensure_targets,
combine_commands,
skip_if_exists
)
import setuptools
HERE = Path(__file__).parent.resolve()
# The name of the project
name = "custom-menu"
lab_path = (HERE... |
the-stack_106_17791 | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Xfindproxy(AutotoolsPackage):
"""xfindproxy is used to locate available X11 proxy services... |
the-stack_106_17792 | """
sentry.tsdb.redis
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from binascii import crc32
from collections import defaultdict
from datetime import timedelta
from hashlib import ... |
the-stack_106_17793 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... |
the-stack_106_17794 | import numpy as np
import sys
import os
import pandas as pd
import glob
import subprocess
import scanpy as sc
from agutil import parallel
from anndata import AnnData
from typing import Union
from tqdm import tqdm
import pkg_resources
from typing import Union
import rpy2
from rpy2.robjects.packages import importr
"""
... |
the-stack_106_17795 | #!/usr/bin/env python
import grp
import os
import pwd
import sys
from odkim_rotate.key_table import *
from odkim_rotate.manager import *
from odkim_rotate.utils import *
def main(verbose):
manager = Manager(verbose)
manager.opendkim_conf = '/etc/opendkim.conf'
manager.opendkim_keys_basedir = '/etc/dkimke... |
the-stack_106_17796 | from __future__ import annotations
import datetime
from functools import partial
from textwrap import dedent
import warnings
import numpy as np
from pandas._libs.tslibs import Timedelta
import pandas._libs.window.aggregations as window_aggregations
from pandas._typing import (
Axis,
FrameOrSeries,
FrameO... |
the-stack_106_17797 | import os
import threading
import time
import requests
from werkzeug.serving import make_server
from flask import Response
class ServerThread(threading.Thread):
def __init__(self, app):
super().__init__()
@app.route('/ping', methods=['GET'])
def ping():
return Response(status... |
the-stack_106_17800 | import numpy as np
import mahotas.thin
import pytest
def slow_thin(binimg, n=-1):
"""
This was the old implementation
"""
from mahotas.bbox import bbox
from mahotas._morph import hitmiss
_struct_elems = []
_struct_elems.append([
[0,0,0],
[2,1,2],
[1,1,1]... |
the-stack_106_17801 | from django.http import Http404
from rest_framework import status
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.generics import ListAPIView
class RelatedModelMixin:
related_field = None
related_model_class = None
related_model_serializer_class = No... |
the-stack_106_17802 | """
Module containing logic related to eager DataFrames
"""
import os
import typing as tp
import warnings
from io import BytesIO, StringIO
from pathlib import Path
from typing import (
Any,
BinaryIO,
Callable,
Dict,
Iterable,
Iterator,
Optional,
Sequence,
TextIO,
Tuple,
Type,... |
the-stack_106_17803 |
class Part1:
def __init__(self):
with open("day16.txt") as f:
self.data = [i.strip() for i in f.readlines()]
self.constraints = {}
self.valid = {}
for line in self.data:
if "your ticket" in line:
break
parts = line.split(':')
... |
the-stack_106_17804 | # Copyright 2019 The Texar 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 applicable ... |
the-stack_106_17806 | import logging
import time
import random
import numpy as np
from smac.configspace import impute_inactive_values, get_one_exchange_neighbourhood, Configuration
__author__ = "Aaron Klein, Marius Lindauer"
__copyright__ = "Copyright 2015, ML4AAD"
__license__ = "3-clause BSD"
__maintainer__ = "Aaron Klein"
__email__ = "k... |
the-stack_106_17807 | #
# 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_17810 | # -*- coding: utf-8 -*-
import sys
import logging
try:
from cStringIO import StringIO # NOQA
except ImportError:
from io import StringIO # NOQA
try:
import importlib # NOQA
except ImportError:
from django.utils import importlib # NOQA
from django.core.management import call_command
from django.te... |
the-stack_106_17813 | """Data anylisis of a restaurant order data"""
data = [
{'order_id': '355c96f5-944e-4ef6-977b-6972df7b8f93', 'price': 3000,
'customer': 'Gerrie Killshaw', 'type': 'takeaway', 'district': None, 'note': None, 'review': 5},
{'order_id': 'ebc2b077-d18a-492d-86b7-81756205fe29', 'price': 2100, 'customer': 'K... |
the-stack_106_17814 | import argparse
import os
import os.path as osp
import torch
import mmcv
from mmaction.apis import init_recognizer
from mmcv.parallel import collate, scatter
from mmaction.datasets.pipelines import Compose
from mmaction.datasets import build_dataloader, build_dataset
from mmcv.parallel import MMDataParallel
import nump... |
the-stack_106_17815 | import functools
from django import http
from django.core.exceptions import PermissionDenied
from amo.decorators import login_required
from access import acl
from addons.decorators import addon_view
from devhub.models import SubmitStep
def dev_required(owner_for_post=False, allow_editors=False, theme=False):
""... |
the-stack_106_17817 | """
https://matplotlib.org/stable/gallery/style_sheets/style_sheets_reference.html
"""
import re
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
def plot_scatter(ax, prng, nb_samples=100):
"""Scatter plot."""
for mu, sigma, marker in [(-0... |
the-stack_106_17825 | # -*- coding: utf-8 -*-
import pytest
from pandas import Categorical
from pandas.util.testing import assert_categorical_equal
@pytest.mark.parametrize("c", [
Categorical([1, 2, 3, 4]),
Categorical([1, 2, 3, 4], categories=[1, 2, 3, 4, 5]),
])
def test_categorical_equal(c):
assert_categorical_equal(c, c)... |
the-stack_106_17826 | from typing import Tuple, FrozenSet
from pysmt.environment import Environment as PysmtEnv
from pysmt.fnode import FNode
import pysmt.typing as types
from utils import symb_to_next
from hint import Hint, Location
def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode,
... |
the-stack_106_17827 | # Copyright 2020 Alexis Lopez Zubieta
#
# 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 use, copy, modify, merge, ... |
the-stack_106_17828 | import json
from newrelic_rest_api import NewRelicRestAPI
class NewRelicAccount():
def __init__(self, rest_api_key=''):
self.__rest_api = NewRelicRestAPI(rest_api_key)
self.__cache = []
def __get_cache(self, set_name):
L = list(filter(lambda set: set['set_name'] == set_name, self.__c... |
the-stack_106_17830 | import threading
import collections
import random
import time
BUFFER_SIZE = 10
REPONEDORES = random.randint(0,2)
CLIENTES = random.randint(3,6)
nombres_c = []
# DECLARACIÓN DEL MONITOR
class maquina(object):
def __init__(self, arg):
self.nRep = REPONEDORES
self.nCli = CLIENTES
self... |
the-stack_106_17832 | # 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_106_17835 | """
Data_Reduction.DSN
==================
Subclasses for reducing data taken with DSN-like open loop recorders.
Open-loop recorders are raw IF voltage recorders that are not synchronized with
the communications between the spacecraft and the ground station. As such, they
are the most basic kind of recorder possible ... |
the-stack_106_17836 | import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import csv
from sklearn import metrics
import sys
log_loc0 = 'logs/TTN/TTN_hid1_it1/'
log_loc1 = 'logs/MERA/MERA_hid1_it1/'
log_loc5 = 'logs/MPS/MPS_hid1_it1/'
log_loc2 = 'logs/CGNN/CGNN_hid1_it1/'
log_loc3 = 'logs/CGNN/CGNN_hid5_it1/'
log_loc4 = '... |
the-stack_106_17839 | from collections import Counter
from itertools import groupby, product
from devito.ir.clusters import Cluster, ClusterGroup, Queue
from devito.ir.support import TILABLE, Scope
from devito.passes.clusters.utils import cluster_pass
from devito.symbolics import pow_to_mul
from devito.tools import DAG, as_tuple, frozendic... |
the-stack_106_17840 | import requests
from typing import List, Dict
from data_refinery_common.models import (
Batch,
File,
SurveyJobKeyValue,
Organism
)
from data_refinery_foreman.surveyor import utils
from data_refinery_foreman.surveyor.external_source import ExternalSourceSurveyor
from data_refinery_common.job_lookup impo... |
the-stack_106_17842 | # encoding: utf-8
from sqlalchemy.orm import relation
from sqlalchemy import types, Column, Table, ForeignKey, UniqueConstraint
from ckan.model import (
core,
meta,
types as _types,
domain_object,
vocabulary,
)
import ckan # this import is needed
import ckan.model
import ckan.lib.dictization
impo... |
the-stack_106_17845 | # Copyright [yyyy] [name of copyright owner]
# Copyright 2021 Huawei Technologies Co., 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.or... |
the-stack_106_17847 | import maya.cmds as mc
import math
#find angle by givin line(2 points) and vertrical line, first point should be the center
def angleIB(x0, y0, x1, y1):
from math import degrees, atan2
a = (degrees( atan2(y1-y0, x1-x0) ) + 90) / 180
return a
#find the 2D distance
def distance(x0, y0, x1, y1)... |
the-stack_106_17848 | # SEÑALES ENVIADAS POR EL CHAT
# > LAMADA DEL CHAT A LA CREACIÓN DEL CAMINO
def on_chat_crea_camino():
agent.teleport(world(44, 4, 7), SOUTH)
crea_camino()
player.on_chat("crea_camino", on_chat_crea_camino)
# > LAMADA DEL CHAT A LA CREACIÓN DEL CAMINO
def on_chat_recorre_camino():
agent.teleport(world(44, 4... |
the-stack_106_17849 | import csv
from datetime import datetime
zeek_dict = {
'dhcp.log': ['ts', 'uid', 'id_orig_h', 'id_orig_p', 'id_resp_h', 'id_resp_p', 'mac', 'assigned_ip', 'lease_time',
'trans_id'],
'dns.log': ['ts', 'uid', 'id_orig_h', 'id_orig_p', 'id_resp_h', 'id_resp_p', 'proto', 'port', 'query', 'qclass',... |
the-stack_106_17850 | """
***************************************************************************************
MP3 audio player based on Rpi Pico
audio data is stored in onboard flash filesystem Up to 800 KB of sound capacity
plays one clip of sound (random) on every power on
and uses external circuit for very low power
****************... |
the-stack_106_17851 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
from fnmatch import fnmatch
from ipaddress import ip_address
from urllib.parse import urlparse
from string import ascii_letters
from . import arg, PatternExtractor
from .. import RefineryCriticalException
from ...lib.patterns import indicators
class xtp(Patte... |
the-stack_106_17853 |
escolha = 0
while escolha != 5:
num1 = int(input("\nDigite um número: "))
num2 = int(input("\nDigite outro número: "))
result = 0
escolha = int(input("""Escolha uma das opções e digite:
[1] - soma
[2] - subtrair
[3] - multiplicar
... |
the-stack_106_17856 | # import the necessary packages
from scipy.spatial import distance as dist
from collections import OrderedDict
import numpy as np
class CentroidTracker:
def __init__(self, maxDisappeared=50, maxDistance=50):
# initialize the next unique object ID along with two ordered
# dictionaries used to keep track of mapping... |
the-stack_106_17859 | #!./bin/python
# ---------------------------------------------------------------------
# MRTHandler
# ---------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Pytho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.