text stringlengths 2 999k |
|---|
from django.test import TestCase
from .models import Author, Book, Publisher
from .memorylog import MemoryHandler
class TestQueryInspect(TestCase):
def test_single_query_view(self):
self.author = Author.objects.create(name='Author')
self.publisher = Publisher.objects.create(name='Publisher')
... |
from io import BytesIO
from avro.schema import Parse
from avro.io import DatumReader, BinaryDecoder
schema = Parse("""{
"namespace": "org.buildroot.package.python_avro",
"type": "record",
"name": "Developer",
"fields": [
{"name": "email", "type": "string"},
{"name": "maintainer_of", "type": "string"}
]
}""")
... |
"""
Tests for prepic.simulation module
"""
import pytest
from prepic import Simulation, Plasma
from unyt import assert_allclose_units
import unyt as u
def test_simulation(cet_plasma, cet_param):
"""Check Simulation class."""
with pytest.raises(TypeError):
_ = Simulation(
Plasma(n_pe=cet_... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportErro... |
from plotly.basedatatypes import BaseTraceType as _BaseTraceType
import copy as _copy
class Scatterternary(_BaseTraceType):
# class properties
# --------------------
_parent_path_str = ""
_path_str = "scatterternary"
_valid_props = {
"a",
"asrc",
"b",
"bsrc",
... |
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
from IPython import get_ipython
# %% [markdown]
# ##### Copyright 2019 The TensorFlow Authors.
# %%
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with t... |
# @copyright@
# Copyright (c) 2006 - 2019 Teradata
# All rights reserved. Stacki(r) v5.x stacki.com
# https://github.com/Teradata/stacki/blob/master/LICENSE.txt
# @copyright@
import re
from operator import itemgetter
from itertools import groupby
import ipaddress
from stack.argument_processors.appliance import Appli... |
from isce3.ext.isce3.container import *
|
from gameComponents import gameVars
def winorlose(status):
print("You", status, " Hey~ Would you like to kill the Monster again?")
choice = input("Y / N? ")
if choice == "N" or choice =="n":
print("You chose to quit! See you next time!。^‿^。")
exit()
elif choice == "Y" or choice == "y":
gameVars.player_live... |
# Copyright 2011 OpenStack Foundation
#
# 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 l... |
"""Generate C code for a Python C extension module from Python source code."""
# FIXME: Basically nothing in this file operates on the level of a
# single module and it should be renamed.
import os
import json
from mypy.ordered_dict import OrderedDict
from typing import List, Tuple, Dict, Iterable, Set, TypeVar, Opti... |
# -*- coding: utf-8 -*-
"""Shared Helpful Scripts.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1P2AmVHPmDccstO0BiGu2uGAG0vTx444b
"""
############################ HELPFUL SHELL COMMANDS ############################
!kill -9 -1 # THIS KILLS THE ... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
import os
def dirsize(path: str = '.') -> int:
"""Get the size of a folder (including descendants)"""
total_size = 0
for dirpath, _, filenames in os.walk(path):
for f in filenames:
if not f.startswith('.'):
try:
dir_size = os.path.getsize(os.path.joi... |
###############################################################################
#
# Read the code below. Predict (in your head) what will get printed
# (i.e., displayed) when the code runs.
#
# Then run this module by right clicking anywhere in this window
# and then selecting:
# Run 'name of file'
# ... |
from openpyxl import load_workbook
import re
import requests
import xlwt
import xlrd
from xlutils.copy import copy
def write_excel_xls(path, sheet_name, value):
index = len(value) # 获取需要写入数据的行数
workbook = xlwt.Workbook() # 新建一个工作簿
sheet = workbook.add_sheet(sheet_name) # 在工作簿中新建一个表格
for... |
# -*- coding: utf-8 -*-
from .bert import BERTEncoder
from .xlmr import XLMREncoder
from .encoder_base import Encoder
str2encoder = {"BERT": BERTEncoder, "XLMR": XLMREncoder}
__all__ = ["BERTEncoder", "XLMREncoder"]
|
# coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from p... |
import pygame
class Window():
def __init__(self, width, height, title, flags=0):
self.width = width
self.height = height
self.title = title
self.flags = flags
# create display and set title
self.__display = pygame.display.set_mode((self.width, self.height)... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
"""
Tree tests: testing add_path_** methods
USE: 'pytest' in command line to execute
"""
import pytest
import os
import sys
from .testops import op1, op2, op3, root
# Needed to import from parent directory
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# IGNORE IMPORT NOT AT TOP OF FILE
f... |
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from astropy.io import fits
def plot_param_recovery(
sim_data_list,
stats_file_list,
output_plot_filename,
file_label_list=None,
max_nbins=20,
):
"""
Make plots comparing the physical parameters from simulated data to the... |
#!/usr/bin/env python3
"""Taxdump Class module."""
import os
import re
import file_io
class Taxdump():
"""Class for working with NCBI taxonomy."""
__slots__ = ['directory',
'ancestors',
'names',
'ranks'
]
def __init__(self, directory,... |
import json
import psycopg2
print("Populating points")
with open('fixtures/cols-and-passes.json') as f:
points = json.loads(f.read())
values = []
for point in points:
values.append(f"('{point['name']}', '{point['lat']}', '{point['lng']}', (SELECT id FROM regions WHERE name='{point['region']}')),... |
# python3
# coding=utf-8
# Copyright 2020 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
import pytest
@pytest.mark.parametrize(
'formal_name, candidate',
[
('Hello World', 'HelloWorld'),
('Hello World!', 'HelloWorld'),
('Hello! World', 'HelloWorld'),
('Hello_World', 'Hello_World'),
('Hello-World', 'HelloWorld'),
('24 Jump Street', '_24JumpStreet'),... |
from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from botocore.paginate import Paginator
from botocore.waiter import Waiter
from typing import Union
from typing import List
class Client(BaseClient):
def accept_resource_share_invitation(self, resourceShareInvitationArn: st... |
'''
Author: tusikalanse
Date: 2021-07-28 15:42:59
LastEditTime: 2021-07-28 15:42:59
LastEditors: tusikalanse
Description: pell equation
'''
from math import sqrt
def getperiod(x):
m, d = 0, 1
a0 = int(sqrt(x))
a = a0
p = [0, a0]
while a0 * 2 != a:
m = a * d - m
d = (x - m * m) / d... |
from PIL import Image
box = (100, 100, 400, 400)
im = open("nature-1.jpeg")
region = im.crop(box)
region = region.transpose(Image.ROTATE_180)
im.paste(region, box) # region to box
im.show()
#https://dzone.com/articles/image-processing-in-python-with-pillow
# (Pasting an Image Onto Another Image for logo image)
|
"""Configuration variables."""
import os
HTTP_TIMEOUT = os.environ.get('ODIN_HTTP_TIMEOUT', 5)
SLEEPY_DURATION = int(os.environ.get('ODIN_SLEEP_DURATION', "30"))
CONFIG_LOCATION = os.environ.get("ODIN_CONFIG_FILE", "/app/odin.yaml")
|
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
import asyncio
import os
import pathlib
import signal
import subprocess
import oeqa.core.target.ssh
class OEFVPTarget(oeqa.core.target.ssh.OESSHTarget):
# meta-arm/scripts isn't on PATH, so work out where it is
metaarm = pathlib.Path(__file__).parents[4]
def __init__(self, logger, target_ip, server_ip, ... |
import re
import warnings
import pytest
from pandas import DataFrame
import pandas._testing as tm
from pandas.io.excel import ExcelWriter
xlsxwriter = pytest.importorskip("xlsxwriter")
pytestmark = pytest.mark.parametrize("ext", [".xlsx"])
def test_column_format(ext):
# Test that column formats are applied t... |
import ell
def test():
params = ell.SGDIncrementalTrainerParameters()
params.regularization = 0.01
loss = ell.LossArguments()
trainer = ell.GetSGDIncrementalTrainer(21, loss, params)
print(type(trainer))
dataset = ell.GetDataset("../../../../examples/data/testData.txt")
print(type(dataset... |
# Generated by Django 3.1.2 on 2021-10-05 17:19
import django.core.validators
from django.db import migrations, models
import djongo.storage
class Migration(migrations.Migration):
dependencies = [
('email_parser', '0001_initial'),
]
operations = [
migrations.AddField(
model_... |
from .LeagueEndpoint import LeagueEndpoint
class MatchV4Endpoint(LeagueEndpoint):
def __init__(self, url, **kwargs):
nurl = f"/match/v4{url}"
super().__init__(nurl, **kwargs)
class MatchApiV4Urls:
by_id = MatchV4Endpoint("/matches/{match_id}")
matchlist_by_account = MatchV4Endpoint(
... |
# Generated by Django 2.0.5 on 2018-09-16 21:16
from django.db import migrations, models
import jumpstart.validators
class Migration(migrations.Migration):
dependencies = [
('jumpstart', '0003_auto_20180916_1622'),
]
operations = [
migrations.AlterField(
model_name='helper',... |
import logging
import random
from random_word import RandomWords
from pydantic import ValidationError
from app.models.trello import BugCard
from app.services.trello_service import service_trello
logger = logging.getLogger(__name__)
class BugService:
"""Service who handle Bug data."""
@classmethod
def... |
import requests
from common.constants import POKEAPI_BASE_URL
def pokemon_exists(name):
response = requests.head(f"{POKEAPI_BASE_URL}pokemon/{name}")
return bool(response)
def get_pokemon_by_id(pokemon_id):
response = requests.get(f"{POKEAPI_BASE_URL}pokemon/{pokemon_id}")
if response.status_code =... |
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(prog='format_oy_gwas.py',
description='''
Format GWAS output from `gw_qtl` to txt.gz files
''')
parser.add_argument('--pheno_list', help='''
The list of phenotype file tag name to extract
'''... |
import glob
from PIL import Image
import os
import shutil
def delete_all(m_rcnn_path, path):
#%% Delete all files at path
files = glob.glob(m_rcnn_path +'/' + path + '/*')
for f in files:
os.remove(f)
def delete_all_except(m_rcnn_path, path, file):
#%% Delete all files at path
files = glob.... |
import argparse
import os
import re
import time
import torch
import pandas as pd
from kernel_utils import VideoReader, FaceExtractor, confident_strategy, predict_on_video_set
from training.zoo.classifiers import DeepFakeClassifier
if __name__ == '__main__':
parser = argparse.ArgumentParser("Predict test videos")
... |
import pytest
from utils import *
@pytest.mark.manual_batch_review
def test_reject_pending_batch_change_success(shared_zone_test_context):
"""
Test rejecting a batch change succeeds for a support user
"""
client = shared_zone_test_context.ok_vinyldns_client
rejector = shared_zone_test_context.sup... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Binux<17175297.hk@gmail.com>
# http://binux.me
# Created on 2012-11-15 17:27:54
import time
import socket
import select
import logging
import umsgpack
import threading
import amqp
from six.moves.urllib.p... |
begin_unit
comment|'# Copyright 2013 Red Hat, Inc.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# a copy of the License at'
nl|'\n'
co... |
import logging
from django.views.decorators.csrf import csrf_exempt
from oidc_provider.lib.endpoints.introspection import TokenIntrospectionEndpoint
try:
from urllib import urlencode
from urlparse import urlsplit, parse_qs, urlunsplit
except ImportError:
from urllib.parse import urlsplit, parse_qs, urluns... |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Detection Training Script.
This scripts reads a given config file and runs the training or evaluation.
It is an entry point that is made to train standard models in detectron2.
In order to let one script support training of... |
# coding: utf-8
#
# Project: FabIO X-ray image reader
#
# Copyright (C) 2010-2016 European Synchrotron Radiation Facility
# Grenoble, France
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software")... |
# 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 t... |
from django.db import models
from django.utils import timezone
from django.contrib import admin
# Create your models here.
# <HINT> Create a Car Make model `class CarMake(models.Model)`:
# - Name
# - Description
# - Any other fields you would like to include in car make model
# - __str__ method to print a car make ob... |
#
# module forward2.py
#
# forward chaining inference engine
#
# this is a varient of forward.py that implements
# negation both by explicit assertion, and by
# ommission; see holmes.doc for more info;
# to use negation-by-ommission in the shell:
# holmes> +2
# to use it in a program, just import forward2;
#####... |
from __future__ import absolute_import, division, print_function
import datetime
import pandas as pd
from pandas.core.window import Rolling as pd_Rolling
from numbers import Integral
from ..base import tokenize
from ..utils import M, funcname, derived_from
from ..highlevelgraph import HighLevelGraph
from .core impor... |
from .bot import *
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Tuple
if TYPE_CHECKING:
import curses
class ScreenBase(ABC):
@... |
from django.apps import AppConfig
class AnalogsSearchConfig(AppConfig):
name = 'analogs_search'
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import io
import json
import boto3
import os
from pydub import AudioSegment
def lambda_handler(event, context):
contact_id_info = event['target']['Key']
print(contact_id_info)
contact_array = contact_id_info.split('_')
contact_Id = contact_array[0]
print(contact_Id)
handle_dynamo(ev... |
from __future__ import absolute_import, division, print_function
import sys
import cctbx.masks
from cctbx import maptbx, miller, sgtbx, xray
from cctbx.array_family import flex
from scitbx.math import approx_equal_relatively
from libtbx.utils import xfrange
from six.moves import range
class solvent_accessible_volum... |
# qubit number=4
# total number=40
import cirq
import qiskit
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from ma... |
import json
from testcontainers.core import utils
from testcontainers.core.container import DockerContainer
result = {
'is_linux': utils.is_linux(),
'is_mac': utils.is_mac(),
'is_windows': utils.is_windows(),
'inside_container': utils.inside_container(),
'default_gateway_ip': utils.default_gateway... |
#!/usr/bin/env python
"""
A code to consume Queues data within a QA aggregator container.
"""
import os
import time as t
from confluent_kafka import Producer, Consumer, KafkaError
import pickle
__author__ = "Jamie Farnes"
__email__ = "jamie.farnes@oerc.ox.ac.uk"
# Start the zookeeper service:
os.system('service zoo... |
import _plotly_utils.basevalidators
class SunburstValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="sunburst", parent_name="", **kwargs):
super(SunburstValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class FocalLoss(nn.Module):
def __init__(self, gamma=0, alpha=None, size_average=True):
super(FocalLoss, self).__init__()
self.gamma = gamma
self.alpha = alpha
# if isinstance(alph... |
"""
WSGI config for twoscoops project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`... |
from cosivina.base import *
from cosivina.auxiliary import *
from cosivina.Element import Element, elementSpec
expandDimension2DSpec = [
('expandDimension', intType),
('size', sizeTupleType),
('output', arrayType2D)
]
@jitclass(elementSpec + expandDimension2DSpec)
class ExpandDimension2D(Element):
'''... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2018 Alibaba Group Holding 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-... |
"""Experiments with many_communities dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import nltk
import os
import pandas as pd
import tensorflow as tf
from tf_trainer.common import base_model
from tf_trainer.common import model_trainer
from tf_... |
import os
from qiskit import IBMQ
def login():
try:
token = os.environ['IBMQ_TOKEN']
except:
print("IBMQ_TOKEN environment variable not found. You must set this variable to the account token string.")
return False
print("Connecting to IBMQ account...")
try:
IBMQ.enable_account(token)
except... |
# coding: utf-8
"""
ORY Hydra
Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. # noqa: E501
The version of the OpenAPI document: v1.10.6
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
impo... |
# coding: utf-8
class Solution:
# @param str: a string
# @return an integer
def atoi(self, str):
# write your code here
int_max = 2147483647
int_min = -2147483648
sum = 0
i = 0
str = str.strip()
if not str:
return 0
sign = 1
... |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='relaax',
version='0.1',
description='RELAAX solution',
author='Stanislav Volodarskiy',
author_email='stanislav@dplrn.com',
url='http://www.dplrn.com/',
packages=['relaax'],
install_requires=[
'ruamel.yaml',
... |
import os.path
from itertools import chain
from functools import total_ordering
HERE = os.path.dirname(os.path.abspath(__file__))
@total_ordering
class IPRange:
def __init__(self, start, stop):
# make stop exclusive, saves on the +1s later on
self.start, self.stop = start, stop + 1
def __e... |
import json
import logging
import requests
from common.SlackBot import TwoWayBot
from common.Utils import generate_timestamp
from slack.SigningService import SigningService
logger = logging.getLogger(__name__)
class SlackBotClient:
def __init__(self, bot: TwoWayBot):
self.signing = SigningService(bot.s... |
"""
preprocess-twitter.py
python preprocess-twitter.py "Some random text with #hashtags, @mentions and http://t.co/kdjfkdjf (links). :)"
Script for preprocessing tweets by Romain Paulus
with small modifications by Jeffrey Pennington
with translation to Python by Motoki Wu
Translation of Ruby script to create features f... |
from bson import ObjectId
from flask import Flask
from flask import jsonify
from flask import request
from flask.json import JSONEncoder
from flask.ext.cors import CORS
from clustering.meanshift import cluster_photos
from processing.path_discovery import PathFinder
from storage.cluster_storage import ClusterStorage
fr... |
#!/usr/bin/env python
"""Load data into memcached and an on disk key value store."""
import sys
import getopt
import mc_bin_client
import pickle
def usage(err=None):
err_code = 0
if err:
err_code = 1
print "Error:", err
print
print "./vbucketpop.py -i <server> -p <port> -b <bucket>... |
import json
import lzma
import re
from base64 import b64decode, b64encode
from collections import namedtuple
from datetime import datetime
from typing import Any, Dict, Iterator, List, Optional, Union
from . import __version__
from .exceptions import *
from .instaloadercontext import InstaloaderContext
PostSidecarNo... |
import random
import subprocess
def is_sublist(list_1, list_2):
for i in range(len(list_2) - len(list_1) + 1):
if list(list_1) == list_2[i : i + len(list_1)]:
return True
return False
APPROXIMANTS = [
"l",
"r",
"j",
"w",
]
NON_APPROXIMANT_CONSONANTS = [
"m",
"n",... |
"""
rotate_fc
===============
Autogenerated DPF operator classes.
"""
from warnings import warn
from ansys.dpf.core.dpf_operator import Operator
from ansys.dpf.core.inputs import Input, _Inputs
from ansys.dpf.core.outputs import Output, _Outputs
from ansys.dpf.core.operators.specification import PinSpecification, Speci... |
# 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 ... |
# uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: lib.coginvasion.minigame.DistributedGroupStation
from panda3d.core import CollisionSphere, CollisionNode
from direct.distributed.Distrib... |
import pytest
import os
import requests
import json
import botocore.session
import shutil
from chalice import deployer
from chalice.cli import load_chalice_app
from chalice.config import Config
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIR = os.path.join(CURRENT_DIR, 'testapp')
CHALICE_DIR = os... |
from django_redis import get_redis_connection
coon = get_redis_connection('default')
from.data import is_edge_attr
from apps.analysis.models import NetWorkManager
import json
def hash_set_data(dictionary, type, network_id):
# type指的是要什么物理量
key = get_key(network_id,type)
if is_edge_attr(type):
tem... |
#!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft, Intel Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# ----------------------------------------... |
from axes.decorators import axes_dispatch
from django.conf import settings
from django.contrib.auth import views
from django.shortcuts import Http404
from django.utils.decorators import method_decorator
from .models import DomainWhitelist
class FeatureFlaggedMixin:
def dispatch(self, *args, **kwargs):
if... |
import contextlib
import enum
import getpass
import os
import secrets
import threading
import urllib.parse
from pathlib import Path, PurePosixPath
import appdirs
import httpx
import msgpack
from ..utils import DictView
from .cache import Revalidate
from .utils import (
ASYNC_EVENT_HOOKS,
DEFAULT_ACCEPTED_ENCO... |
str = input()
count = 0
for char in str:
if char == "e":
count += 1
a = int(count)
print("h" + a*2*"e" + "y") |
from django.apps import AppConfig
class ShoppingAppConfig(AppConfig):
name = "shopping"
verbose_name = "Shopping"
|
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from copy import deepcopy
from typing import (
Callable,
List,
Mapping,
... |
import abc
from datetime import date
from mabooia import lazy, Rational
from mabooia.accounting import Currency
from mabooia.collections.mutable import LinkedList
from mabooia.crypto import sha256_to_str, bin_to_hex
from mabooia.finance import Security
class Event(abc.ABC):
def __init__(self, account_id: str, t... |
import logging
from typing import TYPE_CHECKING, Any, Dict, Generic, List, Optional, Type, TypeVar
from lxml import etree
import core.nodes.base
import core.nodes.physical
from core import utils
from core.emane.nodes import EmaneNet
from core.emulator.data import InterfaceData, LinkData, LinkOptions, NodeOptions
from... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... |
from __future__ import print_function, absolute_import, division # makes KratosMultiphysics backward compatible with python 2.6 and 2.7
# Importing the Kratos Library
import KratosMultiphysics
# Import applications and dependencies
import KratosMultiphysics.ParticleMechanicsApplication as KratosParticle
# Importing... |
# least-squares fit for pressure-to-altitude conversion
#
# The equation given at https://www.engineeringtoolbox.com/air-altitude-pressure-d_462.html,
# (inversed) is roughly A = ( 44330.0 * (1.0 - pow(pressurePa / offsetPa, 0.1903)) ) .
# This script will take in true A_AGL, P_Pa, and a ground pressure reading P_Groun... |
import sys
import logging
from lusid.utilities import ApiClientFactory
from lusidtools.cocoon import (
load_data_to_df_and_detect_delimiter,
load_from_data_frame,
parse_args,
identify_cash_items,
validate_mapping_file_structure,
load_json_file,
cocoon_printer,
)
from lusidtools.logger impor... |
from agents import NetworkAgent
from simulation import NetworkSimulation, Sim
from plotting import PlotCreator
from animation import AnimationCreator |
from collections import OrderedDict
from typing import Iterable
import graphene
from django.db import transaction
from graphene import InputObjectType
from graphene.types.utils import yank_fields_from_attrs
from graphene.utils.str_converters import to_snake_case
from graphene_django.registry import get_global_registry... |
# -*- coding: utf-8 -*-
"""API - Status endpoints."""
from __future__ import absolute_import, print_function, unicode_literals
import cloudsmith_api
from .. import ratelimits
from .exceptions import catch_raise_api_exception
from .init import get_api_client
def get_status_api():
"""Get the status API client."""... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import Authenticati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.