edited_code stringlengths 17 978k | original_code stringlengths 17 978k |
|---|---|
# 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.
import gc
import itertools
import logging
import os
import socket
import time
from typing import Any, Dict, List, Tuple
import numpy as np
imp... | # 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.
import gc
import itertools
import logging
import os
import socket
import time
from typing import Any, Dict, List, Tuple
import numpy as np
imp... |
from __future__ import annotations
import json
import pickle
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
from pathlib import Path
import os
from srim import Ion, Layer, Target # , output
from srim.srim import TRIM
from srim.output import Results
from concurrent.futures import as_c... | from __future__ import annotations
import json
import pickle
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
from pathlib import Path
import os
from srim import Ion, Layer, Target # , output
from srim.srim import TRIM
from srim.output import Results
from concurrent.futures import as_c... |
#!/usr/bin/env python
# This file is part of the pycalver project
# https://gitlab.com/mbarkhau/pycalver
#
# Copyright (c) 2019 Manuel Barkhau (mbarkhau@gmail.com) - MIT License
# SPDX-License-Identifier: MIT
"""
CLI module for PyCalVer.
Provided subcommands: show, test, init, bump
"""
import sys
import typing as typ
... | #!/usr/bin/env python
# This file is part of the pycalver project
# https://gitlab.com/mbarkhau/pycalver
#
# Copyright (c) 2019 Manuel Barkhau (mbarkhau@gmail.com) - MIT License
# SPDX-License-Identifier: MIT
"""
CLI module for PyCalVer.
Provided subcommands: show, test, init, bump
"""
import sys
import typing as typ
... |
import json
import logging
import re
import time
from json import JSONDecodeError
from typing import Optional, Tuple, Dict, Any
from requests import HTTPError, Response
from importer import JSON
from importer.functions import requests_get
from importer.models import CachedObject
logger = logging.getLogger(__name__)... | import json
import logging
import re
import time
from json import JSONDecodeError
from typing import Optional, Tuple, Dict, Any
from requests import HTTPError, Response
from importer import JSON
from importer.functions import requests_get
from importer.models import CachedObject
logger = logging.getLogger(__name__)... |
"""Download"""
import subprocess
from src.helpers import logger
LOG = logger.getLogger(__name__)
def run(settings: dict):
"""Download"""
sequences_file = settings['downloads']['sequences']
LOG.info(f"Downloading {sequences_file}")
subprocess.run([
'wget',
'-q',
sequences_file... | """Download"""
import subprocess
from src.helpers import logger
LOG = logger.getLogger(__name__)
def run(settings: dict):
"""Download"""
sequences_file = settings['downloads']['sequences']
LOG.info(f"Downloading {sequences_file}")
subprocess.run([
'wget',
'-q',
sequences_file... |
from io import BytesIO
from zipfile import ZipFile
import requests
import os
from utilities.get_or_create_temporary_directory import get_temporary_directory as get_temp
def get_file_from_server(url, return_directory, **kwargs):
"""
This accepts a a URL and (ii) retrieves a zipped shapefile from the URL.
... | from io import BytesIO
from zipfile import ZipFile
import requests
import os
from utilities.get_or_create_temporary_directory import get_temporary_directory as get_temp
def get_file_from_server(url, return_directory, **kwargs):
"""
This accepts a a URL and (ii) retrieves a zipped shapefile from the URL.
... |
from colorama import Fore
from config import token, prefix, dev_mode
from helpers import print, parse, get_server_actions
import actions
import actions.readme
import actions.settings
import actions.propose_command
import discord
import math
if dev_mode:
import importlib
client = discord.Client()
@client.event
a... | from colorama import Fore
from config import token, prefix, dev_mode
from helpers import print, parse, get_server_actions
import actions
import actions.readme
import actions.settings
import actions.propose_command
import discord
import math
if dev_mode:
import importlib
client = discord.Client()
@client.event
a... |
# pylint: disable=locally-disabled, too-few-public-methods, no-self-use, invalid-name
"""cmds.py - Implementations of the different HAProxy commands"""
import re
import csv
import json
from io import StringIO
class Cmd():
"""Cmd - Command base class"""
req_args = []
args = {}
cmdTxt = ""
helpTxt ... | # pylint: disable=locally-disabled, too-few-public-methods, no-self-use, invalid-name
"""cmds.py - Implementations of the different HAProxy commands"""
import re
import csv
import json
from io import StringIO
class Cmd():
"""Cmd - Command base class"""
req_args = []
args = {}
cmdTxt = ""
helpTxt ... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import json
from unittest.mock import Mock, PropertyMock
import numpy as np
import pandas as pd
from ax.core.arm imp... | #!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import json
from unittest.mock import Mock, PropertyMock
import numpy as np
import pandas as pd
from ax.core.arm imp... |
###
# Pickpocket list: area > person > item
# Add XP, Gold, Rep
###
import struct
import os
from manual.area_names import gen_area_names
from template_index import index
from handle_page import handle
from root_index import root_index
# wrapper function to convert byte string to regular string
def mystr(a_str):
ret... | ###
# Pickpocket list: area > person > item
# Add XP, Gold, Rep
###
import struct
import os
from manual.area_names import gen_area_names
from template_index import index
from handle_page import handle
from root_index import root_index
# wrapper function to convert byte string to regular string
def mystr(a_str):
ret... |
import time
from discord.ext import commands
import os
import psutil
import platform
uname = platform.uname()
class Status(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(name="status", aliases=["stats", "dash", "dashboard", "übersicht", "performance", "stat"])
... | import time
from discord.ext import commands
import os
import psutil
import platform
uname = platform.uname()
class Status(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(name="status", aliases=["stats", "dash", "dashboard", "übersicht", "performance", "stat"])
... |
import re
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyperclip
import seaborn as sns
class QPCRAnalysis:
def __init__(self,
data,
genes,
samples,
ntc_cols=True,
columns_per_sample=2):
'... | import re
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyperclip
import seaborn as sns
class QPCRAnalysis:
def __init__(self,
data,
genes,
samples,
ntc_cols=True,
columns_per_sample=2):
'... |
import json
from io import BytesIO
from pathlib import Path
from tokenize import tokenize
import click
SECTIONS = [
'md_buttons',
'md_install',
'py_install',
'md_create',
'py_create',
'md_script',
'py_script',
'md_display',
'py_display', ]
@click.command()
@click.option(
'-t'... | import json
from io import BytesIO
from pathlib import Path
from tokenize import tokenize
import click
SECTIONS = [
'md_buttons',
'md_install',
'py_install',
'md_create',
'py_create',
'md_script',
'py_script',
'md_display',
'py_display', ]
@click.command()
@click.option(
'-t'... |
import os
import time
from pathlib import Path
from typing import Optional
import fsspec
import posixpath
from aiohttp.client_exceptions import ServerDisconnectedError
from .. import config
from .download_manager import DownloadConfig, map_nested
from .file_utils import get_authentication_headers_for_url, is_local_pa... | import os
import time
from pathlib import Path
from typing import Optional
import fsspec
import posixpath
from aiohttp.client_exceptions import ServerDisconnectedError
from .. import config
from .download_manager import DownloadConfig, map_nested
from .file_utils import get_authentication_headers_for_url, is_local_pa... |
import os
import time
from argparse import ArgumentParser
from os import makedirs
from os.path import basename, exists
from shutil import copyfile
import torch
import torch.backends.cudnn as cudnn
from torch import nn
from torch.optim import Adam, lr_scheduler
from torch.utils.data import DataLoader
from config.confi... | import os
import time
from argparse import ArgumentParser
from os import makedirs
from os.path import basename, exists
from shutil import copyfile
import torch
import torch.backends.cudnn as cudnn
from torch import nn
from torch.optim import Adam, lr_scheduler
from torch.utils.data import DataLoader
from config.confi... |
from collections import namedtuple
from torch.testing._internal.common_utils import run_tests
from torch.testing._internal.jit_utils import JitTestCase
from torch.testing import FileCheck
from torch import jit
from typing import NamedTuple, List, Optional, Dict, Tuple, Any
from jit.test_module_interface import TestModu... | from collections import namedtuple
from torch.testing._internal.common_utils import run_tests
from torch.testing._internal.jit_utils import JitTestCase
from torch.testing import FileCheck
from torch import jit
from typing import NamedTuple, List, Optional, Dict, Tuple, Any
from jit.test_module_interface import TestModu... |
"""
test_sgc_input_phaselocking.py
Test phase locking from an input sgc to a target cell type. Runs simulations
with AN input, and plots the results, including PSTH and phase histogram.
usage: test_sgc_input_phaselocking.py [-h]
[-c {bushy,tstellate,octopus,dstellate}]
... | """
test_sgc_input_phaselocking.py
Test phase locking from an input sgc to a target cell type. Runs simulations
with AN input, and plots the results, including PSTH and phase histogram.
usage: test_sgc_input_phaselocking.py [-h]
[-c {bushy,tstellate,octopus,dstellate}]
... |
################################################################################
#
# Copyright 2021-2022 Rocco Matano
#
# 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, in... | ################################################################################
#
# Copyright 2021-2022 Rocco Matano
#
# 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, in... |
# -*- coding: utf-8 -*-
"""Click commands."""
from subprocess import call
import click
from flask import current_app
from flask.cli import with_appcontext
from werkzeug.exceptions import MethodNotAllowed, NotFound
from pathlib import Path
from itertools import chain
from flaskshop.random_data import (
create_users... | # -*- coding: utf-8 -*-
"""Click commands."""
from subprocess import call
import click
from flask import current_app
from flask.cli import with_appcontext
from werkzeug.exceptions import MethodNotAllowed, NotFound
from pathlib import Path
from itertools import chain
from flaskshop.random_data import (
create_users... |
'''Update handlers for boes_bot.'''
import os
import datetime, calendar
import locale
import json
import pymongo
import pysftp
from pymongo import MongoClient
from telegram import messages
from telegram import types
from telegram import methods
from handlers.section_handler import SectionHandler
locale.setlocale(lo... | '''Update handlers for boes_bot.'''
import os
import datetime, calendar
import locale
import json
import pymongo
import pysftp
from pymongo import MongoClient
from telegram import messages
from telegram import types
from telegram import methods
from handlers.section_handler import SectionHandler
locale.setlocale(lo... |
"""Set module shortcuts and globals"""
import logging
from pydicom.uid import UID
from ._version import __version__
_version = __version__.split(".")[:3]
# UID prefix provided by https://www.medicalconnections.co.uk/Free_UID
# Encoded as UI, maximum 64 characters
PYNETDICOM_UID_PREFIX = "1.2.826.0.1.3680043.9.381... | """Set module shortcuts and globals"""
import logging
from pydicom.uid import UID
from ._version import __version__
_version = __version__.split(".")[:3]
# UID prefix provided by https://www.medicalconnections.co.uk/Free_UID
# Encoded as UI, maximum 64 characters
PYNETDICOM_UID_PREFIX = "1.2.826.0.1.3680043.9.381... |
# %%
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options # for suppressing the browser
from selenium import webdriver
import warnings
from bs4 import B... | # %%
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options # for suppressing the browser
from selenium import webdriver
import warnings
from bs4 import B... |
from functools import lru_cache
from typing import Dict, List, Optional, Set, Tuple
from collections import OrderedDict
from coreapp.models import Asm, Assembly
from coreapp import util
from coreapp.sandbox import Sandbox
from django.conf import settings
import json
import logging
import os
from pathlib import Path
imp... | from functools import lru_cache
from typing import Dict, List, Optional, Set, Tuple
from collections import OrderedDict
from coreapp.models import Asm, Assembly
from coreapp import util
from coreapp.sandbox import Sandbox
from django.conf import settings
import json
import logging
import os
from pathlib import Path
imp... |
from zlib import crc32
import requests
class Avacat:
def __init__(self, root='https://shantichat.github.io/avacats'):
self.root = root
self.info = requests.get(f'{root}/index.json').json()
def __call__(self, name, size):
assert size in self.info['sizes'], f"Size {size} not allowed, a... | from zlib import crc32
import requests
class Avacat:
def __init__(self, root='https://shantichat.github.io/avacats'):
self.root = root
self.info = requests.get(f'{root}/index.json').json()
def __call__(self, name, size):
assert size in self.info['sizes'], f"Size {size} not allowed, a... |
from __future__ import print_function
import pyttsx3
import datetime
import smtplib
import speech_recognition as sr
import wikipedia
import webbrowser
import os
import random
from twilio.rest import Client
import pickle
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
f... | from __future__ import print_function
import pyttsx3
import datetime
import smtplib
import speech_recognition as sr
import wikipedia
import webbrowser
import os
import random
from twilio.rest import Client
import pickle
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
f... |
import re
from typing import List
import requests
from anime_cli.anime import Anime
from anime_cli.search import SearchApi
class GogoAnime(SearchApi):
def __init__(self, mirror: str):
super().__init__(mirror)
self.url = f"https://gogoanime.{mirror}"
@staticmethod
def get_headers() -> di... | import re
from typing import List
import requests
from anime_cli.anime import Anime
from anime_cli.search import SearchApi
class GogoAnime(SearchApi):
def __init__(self, mirror: str):
super().__init__(mirror)
self.url = f"https://gogoanime.{mirror}"
@staticmethod
def get_headers() -> di... |
# Python Version: 3.x
import functools
import pathlib
import subprocess
from logging import getLogger
from typing import *
from onlinejudge_verify.config import get_config
from onlinejudge_verify.languages.models import Language, LanguageEnvironment
logger = getLogger(__name__)
class NimLanguageEnvironment(Language... | # Python Version: 3.x
import functools
import pathlib
import subprocess
from logging import getLogger
from typing import *
from onlinejudge_verify.config import get_config
from onlinejudge_verify.languages.models import Language, LanguageEnvironment
logger = getLogger(__name__)
class NimLanguageEnvironment(Language... |
#!/usr/bin/env python3
# Author: Volodymyr Shymanskyy
# Usage:
# ./run-wasi-test.py
# ./run-wasi-test.py --exec ../custom_build/wasm3 --timeout 120
# ./run-wasi-test.py --exec "wasmer run --mapdir=/:." --separate-args
# ./run-wasi-test.py --exec "wasmer run --mapdir=/:. wasm3.wasm --" --fast
import argparse
i... | #!/usr/bin/env python3
# Author: Volodymyr Shymanskyy
# Usage:
# ./run-wasi-test.py
# ./run-wasi-test.py --exec ../custom_build/wasm3 --timeout 120
# ./run-wasi-test.py --exec "wasmer run --mapdir=/:." --separate-args
# ./run-wasi-test.py --exec "wasmer run --mapdir=/:. wasm3.wasm --" --fast
import argparse
i... |
import builtins
import importlib
import inspect
import io
import linecache
import os.path
import types
from contextlib import contextmanager
from pathlib import Path
from typing import Any, BinaryIO, Callable, cast, Dict, List, Optional, Union
from weakref import WeakValueDictionary
import torch
from torch.serializati... | import builtins
import importlib
import inspect
import io
import linecache
import os.path
import types
from contextlib import contextmanager
from pathlib import Path
from typing import Any, BinaryIO, Callable, cast, Dict, List, Optional, Union
from weakref import WeakValueDictionary
import torch
from torch.serializati... |
"""Sub-interfaces Classes."""
from fmcapi.api_objects.apiclasstemplate import APIClassTemplate
from fmcapi.api_objects.device_services.devicerecords import DeviceRecords
from fmcapi.api_objects.object_services.securityzones import SecurityZones
from fmcapi.api_objects.device_services.physicalinterfaces import Physical... | """Sub-interfaces Classes."""
from fmcapi.api_objects.apiclasstemplate import APIClassTemplate
from fmcapi.api_objects.device_services.devicerecords import DeviceRecords
from fmcapi.api_objects.object_services.securityzones import SecurityZones
from fmcapi.api_objects.device_services.physicalinterfaces import Physical... |
from __future__ import print_function
import pathlib
from builtins import object
from builtins import str
from typing import Dict
from empire.server.common import helpers
from empire.server.common.module_models import PydanticModule
from empire.server.utils import data_util
from empire.server.utils.module_util import... | from __future__ import print_function
import pathlib
from builtins import object
from builtins import str
from typing import Dict
from empire.server.common import helpers
from empire.server.common.module_models import PydanticModule
from empire.server.utils import data_util
from empire.server.utils.module_util import... |
# Authors: Robert Luke <mail@robertluke.net>
# Eric Larson <larson.eric.d@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD-3-Clause
import re
import numpy as np
from ...io.pick import _picks_to_idx
from ...utils import fill_doc
# Standardized fNIRS channel name regexs... | # Authors: Robert Luke <mail@robertluke.net>
# Eric Larson <larson.eric.d@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD-3-Clause
import re
import numpy as np
from ...io.pick import _picks_to_idx
from ...utils import fill_doc
# Standardized fNIRS channel name regexs... |
from torch.utils.data import Dataset, DataLoader, Subset
from zipfile import BadZipFile
import os
from process_data import files_utils, mesh_utils, points_utils
import options
from constants import DATASET
from custom_types import *
import json
class MeshDataset(Dataset):
@property
def transforms(self):
... | from torch.utils.data import Dataset, DataLoader, Subset
from zipfile import BadZipFile
import os
from process_data import files_utils, mesh_utils, points_utils
import options
from constants import DATASET
from custom_types import *
import json
class MeshDataset(Dataset):
@property
def transforms(self):
... |
# The App listening to new blocks written read the exstrincs and store the transactions in a mysql/mariadb database.
# the database must be created, the app will create the tables and indexes used.
# import libraries
# system packages
import sys
import os
import json
# Substrate module
from substrateinterface import Su... | # The App listening to new blocks written read the exstrincs and store the transactions in a mysql/mariadb database.
# the database must be created, the app will create the tables and indexes used.
# import libraries
# system packages
import sys
import os
import json
# Substrate module
from substrateinterface import Su... |
"""
The typing module: Support for gradual typing as defined by PEP 484.
At large scale, the structure of the module is following:
* Imports and exports, all public names should be explicitly added to __all__.
* Internal helper functions: these should never be used in code outside this module.
* _SpecialForm and its i... | """
The typing module: Support for gradual typing as defined by PEP 484.
At large scale, the structure of the module is following:
* Imports and exports, all public names should be explicitly added to __all__.
* Internal helper functions: these should never be used in code outside this module.
* _SpecialForm and its i... |
# coding: utf-8
from __future__ import unicode_literals
import calendar
import copy
import datetime
import functools
import hashlib
import itertools
import json
import math
import os.path
import random
import re
import sys
import time
import traceback
import threading
from .common import InfoExtractor, SearchInfoExt... | # coding: utf-8
from __future__ import unicode_literals
import calendar
import copy
import datetime
import functools
import hashlib
import itertools
import json
import math
import os.path
import random
import re
import sys
import time
import traceback
import threading
from .common import InfoExtractor, SearchInfoExt... |
from delphin_6_automation.database_interactions import mongo_setup
from delphin_6_automation.database_interactions.auth import auth_dict
from delphin_6_automation.database_interactions.db_templates import sample_entry, delphin_entry
__author__ = "Christian Kongsgaard"
__license__ = 'MIT'
# ---------------------------... | from delphin_6_automation.database_interactions import mongo_setup
from delphin_6_automation.database_interactions.auth import auth_dict
from delphin_6_automation.database_interactions.db_templates import sample_entry, delphin_entry
__author__ = "Christian Kongsgaard"
__license__ = 'MIT'
# ---------------------------... |
from math import tau
from random import choice
import pkgutil
import string
from .common import change_sprite_image
ROTS = {
(1, 0): 0,
(0, 1): 1,
(-1, 0): 2,
(0, -1): 3,
}
SYMBOLS = {}
text = pkgutil.get_data('mufl', 'text/symbols.txt').decode('utf-8')
for line in text.splitlines():
sym, codes =... | from math import tau
from random import choice
import pkgutil
import string
from .common import change_sprite_image
ROTS = {
(1, 0): 0,
(0, 1): 1,
(-1, 0): 2,
(0, -1): 3,
}
SYMBOLS = {}
text = pkgutil.get_data('mufl', 'text/symbols.txt').decode('utf-8')
for line in text.splitlines():
sym, codes =... |
import os
import sys
from types import ModuleType
from .module_loading import load_module
# we assume that our code is always run from the root dir of this repo and nobody tampers with the python path
# we use this to determine whether we should make a backup of the file of a class or not, because if it is from
# ou... | import os
import sys
from types import ModuleType
from .module_loading import load_module
# we assume that our code is always run from the root dir of this repo and nobody tampers with the python path
# we use this to determine whether we should make a backup of the file of a class or not, because if it is from
# ou... |
import htcondor
import os
import shutil
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path
from .conf import *
from .dagman import DAGMan
# Must be consistent with job status definitions in src/condor_includes/proc.h
JobStatus = [
"NONE",
"IDLE",
"RUNNING",
... | import htcondor
import os
import shutil
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path
from .conf import *
from .dagman import DAGMan
# Must be consistent with job status definitions in src/condor_includes/proc.h
JobStatus = [
"NONE",
"IDLE",
"RUNNING",
... |
#!/usr/bin/env python3
#
# Copyright 2018 Brian T. Park
#
# MIT License.
"""
Read the raw TZ Database files at the location specified by `--input_dir` and
generate the zonedb files in various formats as determined by the '--action'
flag:
* --action tzdb
JSON file representation of the internal zonedb named 't... | #!/usr/bin/env python3
#
# Copyright 2018 Brian T. Park
#
# MIT License.
"""
Read the raw TZ Database files at the location specified by `--input_dir` and
generate the zonedb files in various formats as determined by the '--action'
flag:
* --action tzdb
JSON file representation of the internal zonedb named 't... |
from typing import List
import json
from time import sleep
from datetime import date
from os import path
from api import BilibiliApi
from writer import write_md, write_raw_data
BASE_PATH = './archive'
NAP_TIME = .5
def generate_md(raw_data: BilibiliApi.RAW_DATA_T) -> str:
res = []
for video in raw_data:
... | from typing import List
import json
from time import sleep
from datetime import date
from os import path
from api import BilibiliApi
from writer import write_md, write_raw_data
BASE_PATH = './archive'
NAP_TIME = .5
def generate_md(raw_data: BilibiliApi.RAW_DATA_T) -> str:
res = []
for video in raw_data:
... |
# Copyright 2016 - 2022 Alexey Stepanov aka penguinolog
# Copyright 2016 Mirantis, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licens... | # Copyright 2016 - 2022 Alexey Stepanov aka penguinolog
# Copyright 2016 Mirantis, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licens... |
#
# 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... | #
# 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... |
# Copyright 2021 Katteli Inc.
# TestFlows.com Open-Source Software Testing Framework (http://testflows.com)
#
# 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/lice... | # Copyright 2021 Katteli Inc.
# TestFlows.com Open-Source Software Testing Framework (http://testflows.com)
#
# 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/lice... |
#
# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
#
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
#
import argparse
import os
import pathlib
import re
import sys
import subprocess
import time
import logging
... | #
# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
#
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
#
import argparse
import os
import pathlib
import re
import sys
import subprocess
import time
import logging
... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import json
import boto3
import datetime
s3 = boto3.resource('s3')
sm = boto3.client('sagemaker')
time_created = datetime.datetime.now()
def lambda_handler(event, context):
print... | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import json
import boto3
import datetime
s3 = boto3.resource('s3')
sm = boto3.client('sagemaker')
time_created = datetime.datetime.now()
def lambda_handler(event, context):
print... |
"""
Module to dynamically generate a Starlette routing map based on a directory tree.
"""
import importlib
import inspect
import typing as t
from pathlib import Path
from starlette.routing import Route as StarletteRoute, BaseRoute, Mount
from nested_dict import nested_dict
from backend.route import Route
def cons... | """
Module to dynamically generate a Starlette routing map based on a directory tree.
"""
import importlib
import inspect
import typing as t
from pathlib import Path
from starlette.routing import Route as StarletteRoute, BaseRoute, Mount
from nested_dict import nested_dict
from backend.route import Route
def cons... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from concurrent.futures import ThreadPoolExecutor
from typing import Dict, List, Optional, Any, Final
... | #!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from concurrent.futures import ThreadPoolExecutor
from typing import Dict, List, Optional, Any, Final
... |
import tensorflow as tf
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
def visualize(**images):
"""PLot images in one row."""
n = len(images)
plt.figure(figsize=(16, 5))
for i, (name, image) in enumerate(images.items()):
plt.subplot(1, n, i + 1)
plt.... | import tensorflow as tf
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
def visualize(**images):
"""PLot images in one row."""
n = len(images)
plt.figure(figsize=(16, 5))
for i, (name, image) in enumerate(images.items()):
plt.subplot(1, n, i + 1)
plt.... |
import logging
import os
import yaml
import sys
from ClusterShell import NodeSet
class Config:
POSSIBLE_ATTRS = ["ipmi_user", "ipmi_pass", "model", "snmp_oids", "ro_community" ]
def __init__(self, yamlConfigFilePath):
logging.basicConfig(stream=sys.stdout, level=logging.ERROR)
if os.path.i... | import logging
import os
import yaml
import sys
from ClusterShell import NodeSet
class Config:
POSSIBLE_ATTRS = ["ipmi_user", "ipmi_pass", "model", "snmp_oids", "ro_community" ]
def __init__(self, yamlConfigFilePath):
logging.basicConfig(stream=sys.stdout, level=logging.ERROR)
if os.path.i... |
from .graph_module import GraphModule
from .graph import Graph
from .node import Argument, Node, Target, map_arg, map_aggregate
from .proxy import Proxy
from .symbolic_trace import Tracer
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
class Interpreter:
"""
An Interpreter executes an FX g... | from .graph_module import GraphModule
from .graph import Graph
from .node import Argument, Node, Target, map_arg, map_aggregate
from .proxy import Proxy
from .symbolic_trace import Tracer
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
class Interpreter:
"""
An Interpreter executes an FX g... |
#
# Copyright (c) 2021 Project CHIP 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
#
# ... | #
# Copyright (c) 2021 Project CHIP 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
#
# ... |
from collections import OrderedDict
from unittest import TestCase
from pyjsonnlp import validation
from flairjsonnlp import FlairPipeline
from . import mocks
import pytest
text = "Autonomous cars from the countryside of France shift insurance liability toward manufacturers. People are afraid that they will crash."
... | from collections import OrderedDict
from unittest import TestCase
from pyjsonnlp import validation
from flairjsonnlp import FlairPipeline
from . import mocks
import pytest
text = "Autonomous cars from the countryside of France shift insurance liability toward manufacturers. People are afraid that they will crash."
... |
""" Explicit commands using the router api. """
import json
import time
from hitron_cpe.common import Logger
from hitron_cpe.router import Router
def _strip_external_spaces(json_str):
clean = ''
in_quotes = False
for letter in json_str:
if letter == '"':
in_quotes = not in_quotes
if letter == ' ... | """ Explicit commands using the router api. """
import json
import time
from hitron_cpe.common import Logger
from hitron_cpe.router import Router
def _strip_external_spaces(json_str):
clean = ''
in_quotes = False
for letter in json_str:
if letter == '"':
in_quotes = not in_quotes
if letter == ' ... |
#
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# 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 ... | #
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# 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 ... |
# Copyright (c) 2021-2022, NVIDIA CORPORATION.
from __future__ import annotations
import pickle
import warnings
from functools import cached_property
from typing import Any, Set
import pandas as pd
import cudf
from cudf._lib.copying import _gather_map_is_valid, gather
from cudf._lib.stream_compaction import (
a... | # Copyright (c) 2021-2022, NVIDIA CORPORATION.
from __future__ import annotations
import pickle
import warnings
from functools import cached_property
from typing import Any, Set
import pandas as pd
import cudf
from cudf._lib.copying import _gather_map_is_valid, gather
from cudf._lib.stream_compaction import (
a... |
#!/usr/bin/env python3
import gzip
import json
import os
import shutil
import subprocess
import sys
import tempfile
import click
import koji
import requests
# The data we use is meant to be a point-in-time snapshot of Fedora at this
# date; we sneak some newer things in below to test aspects that weren't
# in Fedor... | #!/usr/bin/env python3
import gzip
import json
import os
import shutil
import subprocess
import sys
import tempfile
import click
import koji
import requests
# The data we use is meant to be a point-in-time snapshot of Fedora at this
# date; we sneak some newer things in below to test aspects that weren't
# in Fedor... |
import sys
import inspect
import importlib
import glob
from pathlib import Path
from panda3d.core import NodePath
from ursina.vec3 import Vec3
from panda3d.core import Vec4, Vec2
from panda3d.core import TransparencyAttrib
from panda3d.core import Shader
from panda3d.core import TextureStage, TexGenAttrib
from ursina.... | import sys
import inspect
import importlib
import glob
from pathlib import Path
from panda3d.core import NodePath
from ursina.vec3 import Vec3
from panda3d.core import Vec4, Vec2
from panda3d.core import TransparencyAttrib
from panda3d.core import Shader
from panda3d.core import TextureStage, TexGenAttrib
from ursina.... |
#!/usr/bin/env python3
import sys
import json
from datetime import datetime
'''
A sample line:
{
"date": {
"utc": "2020-06-05T23:30:00.000Z",
"local": "2020-06-06T04:00:00+04:30"
},
"parameter": "pm25",
"value": 22,
"unit": "µg/m³",
"averagingPeriod": {
"value": 1,
"unit": "hours"
},
"... | #!/usr/bin/env python3
import sys
import json
from datetime import datetime
'''
A sample line:
{
"date": {
"utc": "2020-06-05T23:30:00.000Z",
"local": "2020-06-06T04:00:00+04:30"
},
"parameter": "pm25",
"value": 22,
"unit": "µg/m³",
"averagingPeriod": {
"value": 1,
"unit": "hours"
},
"... |
import re
import logging
from typing import Any
from typing import Set
from typing import List
from typing import Dict
from typing import Optional
from httpx import ReadTimeout
from json.decoder import JSONDecodeError
from clairvoyancex import graphql
def get_valid_fields(error_message: str) -> Set:
valid_fields... | import re
import logging
from typing import Any
from typing import Set
from typing import List
from typing import Dict
from typing import Optional
from httpx import ReadTimeout
from json.decoder import JSONDecodeError
from clairvoyancex import graphql
def get_valid_fields(error_message: str) -> Set:
valid_fields... |
import pytest
from test.icat.test_query import prepare_icat_data_for_assertion
class TestICATCreateData:
investigation_name_prefix = "Test Data for API Testing, Data Creation"
@pytest.mark.usefixtures("remove_test_created_investigation_data")
def test_valid_create_data(
self, flask_test_app_icat... | import pytest
from test.icat.test_query import prepare_icat_data_for_assertion
class TestICATCreateData:
investigation_name_prefix = "Test Data for API Testing, Data Creation"
@pytest.mark.usefixtures("remove_test_created_investigation_data")
def test_valid_create_data(
self, flask_test_app_icat... |
"""The input function allows you to interact with the user"""
name = input("What is your name? ")
print(f"Hello, {name}!")
print("What is your age?")
age = int(input("age: ") or 100)
print(f"You are {age} year{"s" if age > 1 else ""} old.")
hobbies = input("What are your hobbies? (comma separated): ")
hobbies = map(... | """The input function allows you to interact with the user"""
name = input("What is your name? ")
print(f"Hello, {name}!")
print("What is your age?")
age = int(input("age: ") or 100)
print(f"You are {age} year{'s' if age > 1 else ''} old.")
hobbies = input("What are your hobbies? (comma separated): ")
hobbies = map(... |
"""AVM FRITZ!Box binary sensors."""
from __future__ import annotations
import datetime
import logging
from typing import Callable, TypedDict
from fritzconnection.core.exceptions import FritzConnectionException
from fritzconnection.lib.fritzstatus import FritzStatus
from homeassistant.components.sensor import STATE_C... | """AVM FRITZ!Box binary sensors."""
from __future__ import annotations
import datetime
import logging
from typing import Callable, TypedDict
from fritzconnection.core.exceptions import FritzConnectionException
from fritzconnection.lib.fritzstatus import FritzStatus
from homeassistant.components.sensor import STATE_C... |
import ee
from datetime import timedelta, datetime
from dateutil.relativedelta import relativedelta
from monthdelta import monthdelta
def s2_cloudmask(image):
qa = image.select('QA60');
# Bits 10 and 11 are clouds and cirrus, respectively.
cloudBitMask = 1 << 10
cirrusBitMask = 1 << 11
# Both fla... | import ee
from datetime import timedelta, datetime
from dateutil.relativedelta import relativedelta
from monthdelta import monthdelta
def s2_cloudmask(image):
qa = image.select('QA60');
# Bits 10 and 11 are clouds and cirrus, respectively.
cloudBitMask = 1 << 10
cirrusBitMask = 1 << 11
# Both fla... |
from vyper import ast as vy_ast
from vyper.exceptions import (
ConstancyViolation,
FunctionDeclarationException,
StructureException,
TypeMismatch,
VariableDeclarationException,
)
from vyper.parser.lll_node import LLLnode
from vyper.parser.parser_utils import getpos, pack_arguments, unwrap_location
f... | from vyper import ast as vy_ast
from vyper.exceptions import (
ConstancyViolation,
FunctionDeclarationException,
StructureException,
TypeMismatch,
VariableDeclarationException,
)
from vyper.parser.lll_node import LLLnode
from vyper.parser.parser_utils import getpos, pack_arguments, unwrap_location
f... |
import os
import re
import itertools
import json
import glob
from contextlib import contextmanager
from typing import List, Tuple, Union, Optional, Generator, Iterable
import logging
import requests
import hachoir.parser
import hachoir.metadata
from .tools import write_file_or_remove
logger = logging.getLogger(__name... | import os
import re
import itertools
import json
import glob
from contextlib import contextmanager
from typing import List, Tuple, Union, Optional, Generator, Iterable
import logging
import requests
import hachoir.parser
import hachoir.metadata
from .tools import write_file_or_remove
logger = logging.getLogger(__name... |
# 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.
"""This module defines the validation result tuple."""
import itertools
import re
from collections import Counter
from typing import Iterable, ... | # 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.
"""This module defines the validation result tuple."""
import itertools
import re
from collections import Counter
from typing import Iterable, ... |
"""
Run custom Graql queries on Grakn graph to answer questions based on business case.
"""
from grakn.client import GraknClient
keyspace_name = "social_network"
def run_queries():
# Builds a Grakn graph within the specified keyspace
with GraknClient(uri="localhost:48555") as client:
with client.sess... | """
Run custom Graql queries on Grakn graph to answer questions based on business case.
"""
from grakn.client import GraknClient
keyspace_name = "social_network"
def run_queries():
# Builds a Grakn graph within the specified keyspace
with GraknClient(uri="localhost:48555") as client:
with client.sess... |
import discord
from discord.ext import commands
from dislash import ActionRow, Button, ButtonStyle, SelectMenu, SelectOption
import asyncio
import random
import json
from datetime import datetime
import os
with open('./ext/brawl.json', 'r') as f:
data = json.load(f)
class Brawl(commands.Cog):
def __init__(sel... | import discord
from discord.ext import commands
from dislash import ActionRow, Button, ButtonStyle, SelectMenu, SelectOption
import asyncio
import random
import json
from datetime import datetime
import os
with open('./ext/brawl.json', 'r') as f:
data = json.load(f)
class Brawl(commands.Cog):
def __init__(sel... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright (c) 2020 K. KOBAYASHI <root.4mac@gmail.com>
#
# Distributed under terms of the MIT license.
"""
BaseTrainer class
"""
import logging
import random
from abc import abstractmethod
from pathlib import Path
import numpy as np
import torch
from... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright (c) 2020 K. KOBAYASHI <root.4mac@gmail.com>
#
# Distributed under terms of the MIT license.
"""
BaseTrainer class
"""
import logging
import random
from abc import abstractmethod
from pathlib import Path
import numpy as np
import torch
from... |
import pytest
from django.test import Client
from django.urls import reverse
from django.test.utils import override_settings
from mock import patch, MagicMock
from rest_framework import status
from urllib.parse import (
quote,
urljoin,
)
import requests
import requests_mock
from lms_connector.responses import ... | import pytest
from django.test import Client
from django.urls import reverse
from django.test.utils import override_settings
from mock import patch, MagicMock
from rest_framework import status
from urllib.parse import (
quote,
urljoin,
)
import requests
import requests_mock
from lms_connector.responses import ... |
# 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... | # 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... |
"""
Validates all keys in all elections.toml files are valid according to
the keys in election_schema, plus a few hardcoded values
It might be that the key is a new key and we've not decided to what to do
with it yet. That might be fine.
Usually its a typo though.
NOTE: This doesn't check val... | """
Validates all keys in all elections.toml files are valid according to
the keys in election_schema, plus a few hardcoded values
It might be that the key is a new key and we've not decided to what to do
with it yet. That might be fine.
Usually its a typo though.
NOTE: This doesn't check val... |
from socketIO_client import SocketIO, BaseNamespace
from time import sleep
import json
import requests
import base64
import sys
import os
import argparse
URI = None
TOKEN = None
TASK_ID = None
OPENVIDU_URL = None
OPENVIDU_AUTH_TOKEN = None
# Define the namespace
class ChatNamespace(BaseNamespace):
# Called when... | from socketIO_client import SocketIO, BaseNamespace
from time import sleep
import json
import requests
import base64
import sys
import os
import argparse
URI = None
TOKEN = None
TASK_ID = None
OPENVIDU_URL = None
OPENVIDU_AUTH_TOKEN = None
# Define the namespace
class ChatNamespace(BaseNamespace):
# Called when... |
# pylint: disable=too-many-ancestors
import itertools
from copy import deepcopy
from typing import Any, Callable, Dict, Generator, Iterator, List, Optional, Sequence, Tuple
from urllib.parse import urljoin, urlsplit
import jsonschema
from hypothesis.strategies import SearchStrategy
from requests.structures import Case... | # pylint: disable=too-many-ancestors
import itertools
from copy import deepcopy
from typing import Any, Callable, Dict, Generator, Iterator, List, Optional, Sequence, Tuple
from urllib.parse import urljoin, urlsplit
import jsonschema
from hypothesis.strategies import SearchStrategy
from requests.structures import Case... |
from .dataclasses import Skill, Card
from .string_mgr import DictionaryAccess
from typing import Callable, Union, Optional
from collections import UserDict
from .skill_cs_enums import (
ST,
IMPLICIT_TARGET_SKILL_TYPES,
PERCENT_VALUE_SKILL_TYPES,
MIXED_VALUE_SKILL_TYPES,
)
VALUE_PERCENT = 1
VALUE_MIXED... | from .dataclasses import Skill, Card
from .string_mgr import DictionaryAccess
from typing import Callable, Union, Optional
from collections import UserDict
from .skill_cs_enums import (
ST,
IMPLICIT_TARGET_SKILL_TYPES,
PERCENT_VALUE_SKILL_TYPES,
MIXED_VALUE_SKILL_TYPES,
)
VALUE_PERCENT = 1
VALUE_MIXED... |
import pathlib
import sys
sys.path.append(str(pathlib.Path(__file__).parent.parent.absolute()))
import itertools
import json
import logging
import math
import os
from collections import OrderedDict
import torch
from torch.distributions import Categorical
from torch import nn, optim
from torch.nn.parallel.data_parall... | import pathlib
import sys
sys.path.append(str(pathlib.Path(__file__).parent.parent.absolute()))
import itertools
import json
import logging
import math
import os
from collections import OrderedDict
import torch
from torch.distributions import Categorical
from torch import nn, optim
from torch.nn.parallel.data_parall... |
import json
import pathlib
import pytest
import requests
from jsonschema import RefResolver, validate
from pytest_intro.app import app
from pytest_intro.models import Article
@pytest.fixture
def client():
app.config["TESTING"] = True
with app.test_client() as client:
yield client
def validate_pay... | import json
import pathlib
import pytest
import requests
from jsonschema import RefResolver, validate
from pytest_intro.app import app
from pytest_intro.models import Article
@pytest.fixture
def client():
app.config["TESTING"] = True
with app.test_client() as client:
yield client
def validate_pay... |
def add_imagestream_namespace_rbac(gendoc):
resources = gendoc
context = gendoc.context
puller_subjects = []
if not context.private:
puller_subjects.append({
'apiGroup': 'rbac.authorization.k8s.io',
'kind': 'Group',
'name': 'system:authenticated'
})... |
def add_imagestream_namespace_rbac(gendoc):
resources = gendoc
context = gendoc.context
puller_subjects = []
if not context.private:
puller_subjects.append({
'apiGroup': 'rbac.authorization.k8s.io',
'kind': 'Group',
'name': 'system:authenticated'
})... |
"""
Common solar physics coordinate systems.
This submodule implements various solar physics coordinate frames for use with
the `astropy.coordinates` module.
"""
from contextlib import contextmanager
import numpy as np
import astropy.units as u
from astropy.coordinates import ConvertError, QuantityAttribute
from ast... | """
Common solar physics coordinate systems.
This submodule implements various solar physics coordinate frames for use with
the `astropy.coordinates` module.
"""
from contextlib import contextmanager
import numpy as np
import astropy.units as u
from astropy.coordinates import ConvertError, QuantityAttribute
from ast... |
import json
from flatmates_api import Flatmates
api = Flatmates(
sessionId="abcd",
flatmatesSessionId="abcd",
csrfToken="abcd",
)
# search people
people = api.search(location="west-end-4101", min_price=300, max_depth=1)
# send message
person = people[0]
error = api.send_message(person.get("memberId"), "H... | import json
from flatmates_api import Flatmates
api = Flatmates(
sessionId="abcd",
flatmatesSessionId="abcd",
csrfToken="abcd",
)
# search people
people = api.search(location="west-end-4101", min_price=300, max_depth=1)
# send message
person = people[0]
error = api.send_message(person.get("memberId"), "H... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This file is covered by the LICENSE file in the root of this project.
from __future__ import annotations
import pathlib
import typing
import cv2
import numpy as np
from piutils.piutils import pi_log
from . import pi_dataset
from . import pi_transform
logger = pi_log... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This file is covered by the LICENSE file in the root of this project.
from __future__ import annotations
import pathlib
import typing
import cv2
import numpy as np
from piutils.piutils import pi_log
from . import pi_dataset
from . import pi_transform
logger = pi_log... |
import logging
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pixels.constants import Ratelimits, Sizes
from pixels.models import GetSize, Message, Pixel
from pixels.utils import auth, ratelimits
log = logging.getLogger(__name__)
# By only adding the JWT dependency to the submounted r... | import logging
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pixels.constants import Ratelimits, Sizes
from pixels.models import GetSize, Message, Pixel
from pixels.utils import auth, ratelimits
log = logging.getLogger(__name__)
# By only adding the JWT dependency to the submounted r... |
"""
Characterisation Plotting
=========================
Defines the characterisation plotting objects:
- :func:`colour.plotting.plot_single_colour_checker`
- :func:`colour.plotting.plot_multi_colour_checkers`
"""
from __future__ import annotations
import numpy as np
import matplotlib.pyplot as plt
from colour.... | """
Characterisation Plotting
=========================
Defines the characterisation plotting objects:
- :func:`colour.plotting.plot_single_colour_checker`
- :func:`colour.plotting.plot_multi_colour_checkers`
"""
from __future__ import annotations
import numpy as np
import matplotlib.pyplot as plt
from colour.... |
import base64
from apiclient import errors
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from parsons.notifications.sendmail import SendMail
SCOPES = 'https://www.googleapis.com/auth/gmail.send'
class Gmail(SendMail):
"""Create a Gmail object, ... | import base64
from apiclient import errors
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from parsons.notifications.sendmail import SendMail
SCOPES = 'https://www.googleapis.com/auth/gmail.send'
class Gmail(SendMail):
"""Create a Gmail object, ... |
import os
# You need to replace the next values with the appropriate values for your configuration
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_ECHO = False
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_DATABASE_URI = f"sqlite:///{os.path.join(basedir, "data", "zip.db")}" | import os
# You need to replace the next values with the appropriate values for your configuration
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_ECHO = False
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_DATABASE_URI = f"sqlite:///{os.path.join(basedir, 'data', 'zip.db')}" |
import base64
import dill
import io
import json
import os
import redis
import struct
import sys
import uuid
import nanome
from nanome.util import async_callback, Logs
from nanome.util.enums import NotificationTypes
BASE_PATH = os.path.dirname(f'{os.path.realpath(__file__)}')
MENU_PATH = os.path.join(BASE_PATH, 'defau... | import base64
import dill
import io
import json
import os
import redis
import struct
import sys
import uuid
import nanome
from nanome.util import async_callback, Logs
from nanome.util.enums import NotificationTypes
BASE_PATH = os.path.dirname(f'{os.path.realpath(__file__)}')
MENU_PATH = os.path.join(BASE_PATH, 'defau... |
import numpy as np
import time
import json
import utils
import torch
from torch.utils.data import Dataset
np.random.seed(0)
DATA_PATH = './data/'
class ToutiaoEntityLinkingDataset(Dataset):
def __init__(self, set_type, opt, char_dict, ent_dict,
is_inference=False, is_pretrain=False):
... | import numpy as np
import time
import json
import utils
import torch
from torch.utils.data import Dataset
np.random.seed(0)
DATA_PATH = './data/'
class ToutiaoEntityLinkingDataset(Dataset):
def __init__(self, set_type, opt, char_dict, ent_dict,
is_inference=False, is_pretrain=False):
... |
import json
import random
import decimal
import os
import logging
import traceback
debug=True
# on error, return nice message to bot
def fail(intent_request,error):
#don't share the full eerror in production code, it's not good to give full traceback data to users
error = error if debug else ''
intent_na... | import json
import random
import decimal
import os
import logging
import traceback
debug=True
# on error, return nice message to bot
def fail(intent_request,error):
#don't share the full eerror in production code, it's not good to give full traceback data to users
error = error if debug else ''
intent_na... |
import json
import os
import sys
import shutil
import time
import subprocess
import numpy as np
from pathlib import Path
from prettytable import PrettyTable, ORGMODE
from fate_test.flow_test.flow_process import get_dict_from_file, serving_connect
class TestModel(object):
def __init__(self, data_base_dir, fate_fl... | import json
import os
import sys
import shutil
import time
import subprocess
import numpy as np
from pathlib import Path
from prettytable import PrettyTable, ORGMODE
from fate_test.flow_test.flow_process import get_dict_from_file, serving_connect
class TestModel(object):
def __init__(self, data_base_dir, fate_fl... |
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import os
import json
from torchvision import datasets, transforms
from torchvision.datasets.folder import ImageFolder, default_loader
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.data import create_transform
... | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import os
import json
from torchvision import datasets, transforms
from torchvision.datasets.folder import ImageFolder, default_loader
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.data import create_transform
... |
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
from enum import Enum
from typing import Dict, List
REPLACE_KEYS = [
('base_values_to_search', 'base_additional_values'),
('base_fields_to_search', 'base_additional_fields'),
('base_field_state', 'base_additional_fi... | import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
from enum import Enum
from typing import Dict, List
REPLACE_KEYS = [
('base_values_to_search', 'base_additional_values'),
('base_fields_to_search', 'base_additional_fields'),
('base_field_state', 'base_additional_fi... |
import datetime
import discord
import re
import time
from discord.ext import commands
from subprocess import call
from typing import Union
from utils import utils, crud, models
from utils.checks import is_staff, check_staff_id, check_bot_or_staff
class Mod(commands.Cog):
"""
Staff commands.
"""
def ... | import datetime
import discord
import re
import time
from discord.ext import commands
from subprocess import call
from typing import Union
from utils import utils, crud, models
from utils.checks import is_staff, check_staff_id, check_bot_or_staff
class Mod(commands.Cog):
"""
Staff commands.
"""
def ... |
import json
from collections import defaultdict
import time
import brickschema
from tqdm import tqdm
from rdflib import URIRef, Graph
from .util import make_readable
import sys
sys.path.append("..")
from bricksrc.version import BRICK_VERSION # noqa: E402
from bricksrc.namespaces import BRICK # noqa: E402
"""
This s... | import json
from collections import defaultdict
import time
import brickschema
from tqdm import tqdm
from rdflib import URIRef, Graph
from .util import make_readable
import sys
sys.path.append("..")
from bricksrc.version import BRICK_VERSION # noqa: E402
from bricksrc.namespaces import BRICK # noqa: E402
"""
This s... |
import asyncio
import math
import datetime
import logging
from typing import Union
import pytz
import discord
from discord.ext import commands
from database.database_setup import DbHandler
import utils.discord_utils as du
import utils.account as acc
import utils.matches as ma
import utils.bets as bets
import utils.ex... | import asyncio
import math
import datetime
import logging
from typing import Union
import pytz
import discord
from discord.ext import commands
from database.database_setup import DbHandler
import utils.discord_utils as du
import utils.account as acc
import utils.matches as ma
import utils.bets as bets
import utils.ex... |
import re
import hashlib
import logging
from urllib.parse import urlparse
from defusedxml.ElementTree import parse
from dojo.models import Endpoint, Finding
logger = logging.getLogger(__name__)
class WapitiParser(object):
"""The web-application vulnerability scanner
see: https://wapiti.sourceforge.io/
... | import re
import hashlib
import logging
from urllib.parse import urlparse
from defusedxml.ElementTree import parse
from dojo.models import Endpoint, Finding
logger = logging.getLogger(__name__)
class WapitiParser(object):
"""The web-application vulnerability scanner
see: https://wapiti.sourceforge.io/
... |
"""
Collection of functions for sending and decoding request to or from the slack API
"""
import cgi
import hmac
import json
import time
import base64
import hashlib
import logging
from typing import Tuple, Union, Optional, MutableMapping
from . import HOOK_URL, ROOT_URL, events, methods, exceptions
LOG = logging.ge... | """
Collection of functions for sending and decoding request to or from the slack API
"""
import cgi
import hmac
import json
import time
import base64
import hashlib
import logging
from typing import Tuple, Union, Optional, MutableMapping
from . import HOOK_URL, ROOT_URL, events, methods, exceptions
LOG = logging.ge... |
'''
Multicast->Serial Server by: JOR
Reads multicast packets from a particular set of addresses and ports.
Test with McSimulator
Alpha: 08MAR22
'''
import socket, serial
import settings.mc as settings
# Swiches for selecting sources
enable_base_gga = 1
enable_heading_gga = 1
enable_heading_hdt = 1
# Set multicast inf... | '''
Multicast->Serial Server by: JOR
Reads multicast packets from a particular set of addresses and ports.
Test with McSimulator
Alpha: 08MAR22
'''
import socket, serial
import settings.mc as settings
# Swiches for selecting sources
enable_base_gga = 1
enable_heading_gga = 1
enable_heading_hdt = 1
# Set multicast inf... |
'''
Schema of stimulation information.
'''
import re
import os
from datetime import datetime
import numpy as np
import scipy.io as sio
import datajoint as dj
import h5py as h5
from . import reference, subject, utilities, stimulation, acquisition, analysis
schema = dj.schema(dj.config['custom'].get('database.prefix',... | '''
Schema of stimulation information.
'''
import re
import os
from datetime import datetime
import numpy as np
import scipy.io as sio
import datajoint as dj
import h5py as h5
from . import reference, subject, utilities, stimulation, acquisition, analysis
schema = dj.schema(dj.config['custom'].get('database.prefix',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.