edited_code stringlengths 17 978k | original_code stringlengths 17 978k |
|---|---|
import os
import sys
from enum import Enum, auto
from importlib.metadata import PackageNotFoundError, metadata
from pathlib import Path
from tempfile import gettempdir
from typing import Callable, Dict, List, Optional, Sequence, Tuple
from npe2 import PackageMetadata, PluginManager
from qtpy.QtCore import (
QEvent... | import os
import sys
from enum import Enum, auto
from importlib.metadata import PackageNotFoundError, metadata
from pathlib import Path
from tempfile import gettempdir
from typing import Callable, Dict, List, Optional, Sequence, Tuple
from npe2 import PackageMetadata, PluginManager
from qtpy.QtCore import (
QEvent... |
import collections
import sys
from conda.base.context import context
from conda_build import utils
from conda_build.config import get_or_merge_config
from conda_build.variants import find_config_files, parse_config_file
from conda_build import __version__ as cb_version
from rich.console import Console
console = Cons... | import collections
import sys
from conda.base.context import context
from conda_build import utils
from conda_build.config import get_or_merge_config
from conda_build.variants import find_config_files, parse_config_file
from conda_build import __version__ as cb_version
from rich.console import Console
console = Cons... |
import uuid
from textwrap import dedent
from jumpscale.loader import j
from jumpscale.sals.chatflows.chatflows import GedisChatBot, chatflow_step, StopChatFlow
from jumpscale.sals.reservation_chatflow import deployer, solutions, deployment_context, DeploymentFailed
kinds = {
"minio": solutions.list_minio_solutions... | import uuid
from textwrap import dedent
from jumpscale.loader import j
from jumpscale.sals.chatflows.chatflows import GedisChatBot, chatflow_step, StopChatFlow
from jumpscale.sals.reservation_chatflow import deployer, solutions, deployment_context, DeploymentFailed
kinds = {
"minio": solutions.list_minio_solutions... |
"""utilities to handle markdown
"""
import re
from d2lbook import common
from typing import List, Dict
import logging
def split_markdown(source: str) -> List[Dict[str, str]]:
"""Split markdown into a list of text and code cells.
A cell has three fields:
1. type: either code or markdown
2. class: code ... | """utilities to handle markdown
"""
import re
from d2lbook import common
from typing import List, Dict
import logging
def split_markdown(source: str) -> List[Dict[str, str]]:
"""Split markdown into a list of text and code cells.
A cell has three fields:
1. type: either code or markdown
2. class: code ... |
# encoding: utf-8
"""
@author: l1aoxingyu
@contact: sherlockliao01@gmail.com
"""
import os
import shutil
import time
import random
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
# Changed by Xinchen Liu
from data import get_dataloader_mask
from data.datasets.eval_reid import e... | # encoding: utf-8
"""
@author: l1aoxingyu
@contact: sherlockliao01@gmail.com
"""
import os
import shutil
import time
import random
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
# Changed by Xinchen Liu
from data import get_dataloader_mask
from data.datasets.eval_reid import e... |
import tkinter as tk
import threading
import time
import asyncio
from notifications_provider import NotificationsProvider
from load_configuration import getConfig, updateValue
from overlay_components import *
fg_colour = '#FEFEFE'
#Transparency will only work on windows
class App():
"""In charge of displaying inf... | import tkinter as tk
import threading
import time
import asyncio
from notifications_provider import NotificationsProvider
from load_configuration import getConfig, updateValue
from overlay_components import *
fg_colour = '#FEFEFE'
#Transparency will only work on windows
class App():
"""In charge of displaying inf... |
import hashlib
import logging
import os
import os.path as osp
import sys
cur_dir = osp.dirname(osp.abspath(__file__))
PROJ_ROOT = osp.normpath(osp.join(cur_dir, "../../.."))
sys.path.insert(0, PROJ_ROOT)
import time
from collections import OrderedDict
import mmcv
import numpy as np
from tqdm import tqdm
from transform... | import hashlib
import logging
import os
import os.path as osp
import sys
cur_dir = osp.dirname(osp.abspath(__file__))
PROJ_ROOT = osp.normpath(osp.join(cur_dir, "../../.."))
sys.path.insert(0, PROJ_ROOT)
import time
from collections import OrderedDict
import mmcv
import numpy as np
from tqdm import tqdm
from transform... |
# Copyright 2020-present NAVER Corp. Under BSD 3-clause license
"""
OpenSfM to kapture import functions.
"""
import logging
import os
import os.path as path
import numpy as np
import quaternion
import gzip
import pickle
import json
from tqdm import tqdm
from typing import Any, Dict, Optional, Tuple
# kapture
import k... | # Copyright 2020-present NAVER Corp. Under BSD 3-clause license
"""
OpenSfM to kapture import functions.
"""
import logging
import os
import os.path as path
import numpy as np
import quaternion
import gzip
import pickle
import json
from tqdm import tqdm
from typing import Any, Dict, Optional, Tuple
# kapture
import k... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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 ... | # -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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 ... |
# pylint:disable=line-too-long
import logging
from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool
from ...calling... | # pylint:disable=line-too-long
import logging
from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool
from ...calling... |
import os, configparser
from celery import Celery
from celery.schedules import crontab
from parse import default
from parse import custom
__version__ = "2.0.0"
config = configparser.RawConfigParser()
config.read(os.environ.get("CFG_PATH"))
default_config = dict(config.items("DEFAULT"))
app = Celery("tasks")
app.... | import os, configparser
from celery import Celery
from celery.schedules import crontab
from parse import default
from parse import custom
__version__ = "2.0.0"
config = configparser.RawConfigParser()
config.read(os.environ.get("CFG_PATH"))
default_config = dict(config.items("DEFAULT"))
app = Celery("tasks")
app.... |
from typing import Iterable, Optional, Dict, Collection, Tuple, Sequence, Iterator, Any
import operator
from collections import namedtuple
from enum import Enum
from re import finditer
from pyimath.annotations import BaseField, BaseNumber, Operand
from pyimath.functions import gcd, reduce_to_gcd, power
__all__ = ['... | from typing import Iterable, Optional, Dict, Collection, Tuple, Sequence, Iterator, Any
import operator
from collections import namedtuple
from enum import Enum
from re import finditer
from pyimath.annotations import BaseField, BaseNumber, Operand
from pyimath.functions import gcd, reduce_to_gcd, power
__all__ = ['... |
import datetime
from enum import Enum
from itertools import islice
from logging import getLogger
from typing import Any, Dict, List, Optional, Tuple, Type, TypedDict
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.indexes import GinIndex
from django.db import IntegrityError, models
f... | import datetime
from enum import Enum
from itertools import islice
from logging import getLogger
from typing import Any, Dict, List, Optional, Tuple, Type, TypedDict
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.indexes import GinIndex
from django.db import IntegrityError, models
f... |
#!/usr/bin/env python3
#
# MIT License
#
# Copyright (c) 2020-2021 EntySec
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to... | #!/usr/bin/env python3
#
# MIT License
#
# Copyright (c) 2020-2021 EntySec
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to... |
import copy
import datetime
import inspect
import json
import logging
import traceback
import warnings
from collections import defaultdict, namedtuple
from collections.abc import Hashable
from typing import Any, Dict, Iterable, List, Optional, Set
import pandas as pd
from dateutil.parser import parse
from tqdm.auto im... | import copy
import datetime
import inspect
import json
import logging
import traceback
import warnings
from collections import defaultdict, namedtuple
from collections.abc import Hashable
from typing import Any, Dict, Iterable, List, Optional, Set
import pandas as pd
from dateutil.parser import parse
from tqdm.auto im... |
"""
BSD 3-Clause License
Copyright (c) 2021, Netskope OSS
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of condi... | """
BSD 3-Clause License
Copyright (c) 2021, Netskope OSS
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of condi... |
"""
Digirule assembler support.
:author: Athanasios Anastasiou
:date: June 2020
"""
from .digirule import Digirule
from .exceptions import DgtoolsErrorSymbolAlreadyDefined, DgtoolsErrorSymbolUndefined, DgtoolsErrorASMSyntaxError
import pyparsing
import functools
class DgAssembler:
def __init__(self, digiru... | """
Digirule assembler support.
:author: Athanasios Anastasiou
:date: June 2020
"""
from .digirule import Digirule
from .exceptions import DgtoolsErrorSymbolAlreadyDefined, DgtoolsErrorSymbolUndefined, DgtoolsErrorASMSyntaxError
import pyparsing
import functools
class DgAssembler:
def __init__(self, digiru... |
import numpy as np
import pandas as pd
import json
import requests
from shapely.geometry import LineString
from sklearn.cluster import KMeans
import time
import os
from geocoding.config import Config
def query_api(query, fpath):
"""
Queries Overpass API for *query*.
Args:
query (str): The query ... | import numpy as np
import pandas as pd
import json
import requests
from shapely.geometry import LineString
from sklearn.cluster import KMeans
import time
import os
from geocoding.config import Config
def query_api(query, fpath):
"""
Queries Overpass API for *query*.
Args:
query (str): The query ... |
import logging
import smtplib
import urllib.parse
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from itsdangerous import URLSafeTimedSerializer
from flask import current_app
from server.services.messaging.template_service import get_template
class SMTPService:
@staticmethod
... | import logging
import smtplib
import urllib.parse
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from itsdangerous import URLSafeTimedSerializer
from flask import current_app
from server.services.messaging.template_service import get_template
class SMTPService:
@staticmethod
... |
"""Module for initializing data sources."""
from datetime import datetime
from typing import Optional, Union, List, Tuple, Dict
from uta_tools import logger
from uta_tools.schemas import Assembly, GenomicData, TranscriptExonData, ResidueMode, \
GenomicDataResponse, ServiceMeta, TranscriptExonDataResponse
from uta_... | """Module for initializing data sources."""
from datetime import datetime
from typing import Optional, Union, List, Tuple, Dict
from uta_tools import logger
from uta_tools.schemas import Assembly, GenomicData, TranscriptExonData, ResidueMode, \
GenomicDataResponse, ServiceMeta, TranscriptExonDataResponse
from uta_... |
"""This is a cog for a discord.py bot.
It will add some management commands to a bot.
Commands:
version show the hash of the latest commit
load load an extension / cog
unload unload an extension / cog
reload reload an extension / cog
cogs show current... | """This is a cog for a discord.py bot.
It will add some management commands to a bot.
Commands:
version show the hash of the latest commit
load load an extension / cog
unload unload an extension / cog
reload reload an extension / cog
cogs show current... |
from importlib import import_module
from app.objects.secondclass.c_fact import Fact
from app.objects.secondclass.c_relationship import Relationship
from app.objects.secondclass.c_rule import Rule
from app.service.interfaces.i_knowledge_svc import KnowledgeServiceInterface
from app.utility.base_knowledge_svc import Bas... | from importlib import import_module
from app.objects.secondclass.c_fact import Fact
from app.objects.secondclass.c_relationship import Relationship
from app.objects.secondclass.c_rule import Rule
from app.service.interfaces.i_knowledge_svc import KnowledgeServiceInterface
from app.utility.base_knowledge_svc import Bas... |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 Lice... | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 Lice... |
import abc
import importlib
import json
import math
import os
import random
import sys
import time
import datetime
import colorama
import click
import infirunner.capsule
import numpy as np
import scipy.stats as sps
from colorama import Style, Fore
from statsmodels.nonparametric.api import KDEMultivariate
from infiru... | import abc
import importlib
import json
import math
import os
import random
import sys
import time
import datetime
import colorama
import click
import infirunner.capsule
import numpy as np
import scipy.stats as sps
from colorama import Style, Fore
from statsmodels.nonparametric.api import KDEMultivariate
from infiru... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import speech_recognition as sr
from blessed import Terminal
from texttable import Texttable
from spacy.matcher import Matcher
import en_core_web_sm
from inference import *
import json
nlp = en_core_web_sm.load()
nlp.Defaults.stop_words -= {'give', ... | #!/usr/bin/env python
import rospy
from std_msgs.msg import String
import speech_recognition as sr
from blessed import Terminal
from texttable import Texttable
from spacy.matcher import Matcher
import en_core_web_sm
from inference import *
import json
nlp = en_core_web_sm.load()
nlp.Defaults.stop_words -= {'give', ... |
import json
import logging
import os
import sys
import tarfile
from contextlib import contextmanager
from ipaddress import ip_address
from json import JSONDecodeError
from pathlib import Path
from random import randint
from socket import getaddrinfo
from tempfile import SpooledTemporaryFile, TemporaryDirectory
from tim... | import json
import logging
import os
import sys
import tarfile
from contextlib import contextmanager
from ipaddress import ip_address
from json import JSONDecodeError
from pathlib import Path
from random import randint
from socket import getaddrinfo
from tempfile import SpooledTemporaryFile, TemporaryDirectory
from tim... |
"""
TODO:
- glaring unresolved ambiguity between selecting from mats and tbls
- ** NOT NECESSARILY FORCED TO REFRESH ALL MATERIALIZATIONS TOGETHER... **
- baked anns? materializations <-> rows?
table -> invalidation -> rows -> refresh -> ...
|
V
materializations
"""
import logging
import typing as ta
from omni... | """
TODO:
- glaring unresolved ambiguity between selecting from mats and tbls
- ** NOT NECESSARILY FORCED TO REFRESH ALL MATERIALIZATIONS TOGETHER... **
- baked anns? materializations <-> rows?
table -> invalidation -> rows -> refresh -> ...
|
V
materializations
"""
import logging
import typing as ta
from omni... |
# Standard library
import io
import logging
import math
import os
import time
# Third party
import azure.functions as func
import pandas as pd
import psycopg2
from shapely.geometry import Polygon
import xarray
# Local
from .utils import batches, human_readable, mean_step_size
class Processor:
def __init__(self,... | # Standard library
import io
import logging
import math
import os
import time
# Third party
import azure.functions as func
import pandas as pd
import psycopg2
from shapely.geometry import Polygon
import xarray
# Local
from .utils import batches, human_readable, mean_step_size
class Processor:
def __init__(self,... |
"""Partial derivatives for the torch.nn.RNN layer."""
from typing import List, Tuple
from torch import Tensor, cat, einsum, zeros
from torch.nn import RNN
from backpack.core.derivatives.basederivatives import BaseParameterDerivatives
from backpack.utils.subsampling import subsample
class RNNDerivatives(BaseParamete... | """Partial derivatives for the torch.nn.RNN layer."""
from typing import List, Tuple
from torch import Tensor, cat, einsum, zeros
from torch.nn import RNN
from backpack.core.derivatives.basederivatives import BaseParameterDerivatives
from backpack.utils.subsampling import subsample
class RNNDerivatives(BaseParamete... |
# https://docs.scrapy.org/en/latest/topics/settings.html
import logging
from pathlib import Path
from datetime import datetime
BOT_NAME = "ebk"
SPIDER_MODULES = ["ebk.spiders"]
NEWSPIDER_MODULE = "ebk.spiders"
# Crawl responsibly by identifying yourself (and your website) on the user-agent
# USER_AGENT = "Mozilla/... | # https://docs.scrapy.org/en/latest/topics/settings.html
import logging
from pathlib import Path
from datetime import datetime
BOT_NAME = "ebk"
SPIDER_MODULES = ["ebk.spiders"]
NEWSPIDER_MODULE = "ebk.spiders"
# Crawl responsibly by identifying yourself (and your website) on the user-agent
# USER_AGENT = "Mozilla/... |
import random, pickle, pyglet
from tkinter import *
from PIL import Image, ImageTk
# ||||||||||||||||||||||||||||||||||||||||||||||||||| #
# ||||||||||||||||||||||||||||||||||||||||||||||||||| #
# ||| ||||| #
# ||| FUNCTIONS ||||| #
# ... | import random, pickle, pyglet
from tkinter import *
from PIL import Image, ImageTk
# ||||||||||||||||||||||||||||||||||||||||||||||||||| #
# ||||||||||||||||||||||||||||||||||||||||||||||||||| #
# ||| ||||| #
# ||| FUNCTIONS ||||| #
# ... |
"""Solvent accessible surface area code."""
import functools
import typing
from typing import Any, Dict, Iterable, List, Optional, Union
import numpy as np
import scipy.spatial
from morfeus.data import atomic_symbols, jmol_colors
from morfeus.geometry import Atom, Sphere
from morfeus.io import read_geometry
from mor... | """Solvent accessible surface area code."""
import functools
import typing
from typing import Any, Dict, Iterable, List, Optional, Union
import numpy as np
import scipy.spatial
from morfeus.data import atomic_symbols, jmol_colors
from morfeus.geometry import Atom, Sphere
from morfeus.io import read_geometry
from mor... |
# ====================================================
# Library #
# ====================================================
import os
import gc
import sys
import math
import time
import random
import shutil
from requests import get
from pathlib import Path
from contextlib import contextmanager
from collections import def... | # ====================================================
# Library #
# ====================================================
import os
import gc
import sys
import math
import time
import random
import shutil
from requests import get
from pathlib import Path
from contextlib import contextmanager
from collections import def... |
from tap_slack.streams.base import BaseStream
import singer
import datetime
import time
LOGGER = singer.get_logger() # noqa
class AccessLogsStream(BaseStream):
API_METHOD = 'team_accessLogs'
TABLE = 'access_logs'
KEY_PROPERTIES = ['user_id', 'ip', 'user_agent']
TIMEOUT = 3
def response_key(self... | from tap_slack.streams.base import BaseStream
import singer
import datetime
import time
LOGGER = singer.get_logger() # noqa
class AccessLogsStream(BaseStream):
API_METHOD = 'team_accessLogs'
TABLE = 'access_logs'
KEY_PROPERTIES = ['user_id', 'ip', 'user_agent']
TIMEOUT = 3
def response_key(self... |
__version__ = '1.0.0'
import csv
import datetime
import importlib
from abc import abstractmethod
from collections import defaultdict
from typing import Dict, List, Set
import numpy as np
import pandas as pd
from dateutil import relativedelta as rdelta
import logging
from functools import partial
import calendar
f... | __version__ = '1.0.0'
import csv
import datetime
import importlib
from abc import abstractmethod
from collections import defaultdict
from typing import Dict, List, Set
import numpy as np
import pandas as pd
from dateutil import relativedelta as rdelta
import logging
from functools import partial
import calendar
f... |
# -*- coding: utf-8 -*-
# :Project: pglast -- Wrap PG nodes into a Python AST
# :Created: sab 27 feb 2021, 19:47:11
# :Author: Lele Gaifax <lele@metapensiero.it>
# :License: GNU General Public License version 3 or later
# :Copyright: © 2021 Lele Gaifax
#
from datetime import date
import json
from keyword impo... | # -*- coding: utf-8 -*-
# :Project: pglast -- Wrap PG nodes into a Python AST
# :Created: sab 27 feb 2021, 19:47:11
# :Author: Lele Gaifax <lele@metapensiero.it>
# :License: GNU General Public License version 3 or later
# :Copyright: © 2021 Lele Gaifax
#
from datetime import date
import json
from keyword impo... |
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
from datetime import datetime, timezone
from typing import Union, Any, Dict
from dateparser import parse
import urllib3
import traceback
# Disable insecure warnings
urllib3.disable_warnings()
''' GLOBAL VARIABLES '''
... | import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
from datetime import datetime, timezone
from typing import Union, Any, Dict
from dateparser import parse
import urllib3
import traceback
# Disable insecure warnings
urllib3.disable_warnings()
''' GLOBAL VARIABLES '''
... |
"""
The :mod:`sklearn.model_selection._validation` module includes classes and
functions to validate the model.
"""
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Gael Varoquaux <gael.varoquaux@normalesup.org>
# Olivier Grisel <olivier.grisel@ensta.org>
# Raghav RV <rvragh... | """
The :mod:`sklearn.model_selection._validation` module includes classes and
functions to validate the model.
"""
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Gael Varoquaux <gael.varoquaux@normalesup.org>
# Olivier Grisel <olivier.grisel@ensta.org>
# Raghav RV <rvragh... |
#!/usr/bin/env python3
import os
import re
import logging
import botocore.credentials
import botocore.session
import boto3
logger = logging.getLogger("ssm-session")
class InstanceResolver():
def __init__(self, args):
# aws-cli compatible MFA cache
cli_cache = os.path.join(os.path.expanduser('~'),... | #!/usr/bin/env python3
import os
import re
import logging
import botocore.credentials
import botocore.session
import boto3
logger = logging.getLogger("ssm-session")
class InstanceResolver():
def __init__(self, args):
# aws-cli compatible MFA cache
cli_cache = os.path.join(os.path.expanduser('~'),... |
import discord
from discord.ext import commands
import sys
import traceback
class ErrorHander(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def __build_error_embed(self, title, description=discord.Embed.Empty, color=discord.Color.red()):
e = discord.Embed(title... | import discord
from discord.ext import commands
import sys
import traceback
class ErrorHander(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def __build_error_embed(self, title, description=discord.Embed.Empty, color=discord.Color.red()):
e = discord.Embed(title... |
import torch,cv2
from torch.utils.data import Dataset
import json
from tqdm import tqdm
import os
from PIL import Image
from torchvision import transforms as T
from .ray_utils import *
class YourOwnDataset(Dataset):
def __init__(self, datadir, split='train', downsample=1.0, is_stack=False, N_vis=-1):
s... | import torch,cv2
from torch.utils.data import Dataset
import json
from tqdm import tqdm
import os
from PIL import Image
from torchvision import transforms as T
from .ray_utils import *
class YourOwnDataset(Dataset):
def __init__(self, datadir, split='train', downsample=1.0, is_stack=False, N_vis=-1):
s... |
"""
Credits:
This file was adopted from: https://github.com/pydata/xarray # noqa
Source file: https://github.com/pydata/xarray/blob/1d7bcbdc75b6d556c04e2c7d7a042e4379e15303/xarray/backends/rasterio_.py # noqa
"""
import os
import re
import warnings
from collections import OrderedDict
from distutils.version import Lo... | """
Credits:
This file was adopted from: https://github.com/pydata/xarray # noqa
Source file: https://github.com/pydata/xarray/blob/1d7bcbdc75b6d556c04e2c7d7a042e4379e15303/xarray/backends/rasterio_.py # noqa
"""
import os
import re
import warnings
from collections import OrderedDict
from distutils.version import Lo... |
import os
from django.db import models
from django.utils.text import slugify
from django.contrib.postgres.fields import ArrayField
from django.db.models.signals import post_save
from django.dispatch import receiver
from notifications.signals import notify
from django.utils.http import urlsafe_base64_encode, urlsafe_ba... | import os
from django.db import models
from django.utils.text import slugify
from django.contrib.postgres.fields import ArrayField
from django.db.models.signals import post_save
from django.dispatch import receiver
from notifications.signals import notify
from django.utils.http import urlsafe_base64_encode, urlsafe_ba... |
import os
from typing import Tuple
import boto3
from botocore.exceptions import ClientError
from dotenv import load_dotenv
load_dotenv()
AWS_REGION = 'eu-west-1'
def handler(event, context):
subject, message = parse_params(event, context)
sender = os.getenv('SENDER_EMAIL')
recipient = os.getenv('RECIPI... | import os
from typing import Tuple
import boto3
from botocore.exceptions import ClientError
from dotenv import load_dotenv
load_dotenv()
AWS_REGION = 'eu-west-1'
def handler(event, context):
subject, message = parse_params(event, context)
sender = os.getenv('SENDER_EMAIL')
recipient = os.getenv('RECIPI... |
import datetime
import logging
import math
import time
import torch
from os import path as osp
from basicsr.data import build_dataloader, build_dataset
from basicsr.data.data_sampler import EnlargedSampler
from basicsr.data.prefetch_dataloader import CPUPrefetcher, CUDAPrefetcher
from basicsr.models import build_model... | import datetime
import logging
import math
import time
import torch
from os import path as osp
from basicsr.data import build_dataloader, build_dataset
from basicsr.data.data_sampler import EnlargedSampler
from basicsr.data.prefetch_dataloader import CPUPrefetcher, CUDAPrefetcher
from basicsr.models import build_model... |
#
# 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... |
import dataclasses
import datetime
import json
import logging
import re
from typing import Iterable
import discord
from bot.consts import Colors, DesignatedChannels, OwnerDesignatedChannels
from bot.messaging.events import Events
from bot.services.base_service import BaseService
log = logging.getLogger(__name__)
ME... | import dataclasses
import datetime
import json
import logging
import re
from typing import Iterable
import discord
from bot.consts import Colors, DesignatedChannels, OwnerDesignatedChannels
from bot.messaging.events import Events
from bot.services.base_service import BaseService
log = logging.getLogger(__name__)
ME... |
import contextlib
import ipaddress
import json
import os
import random
import re
import time
import warnings
from collections import Counter
from typing import Any, Dict, List, Optional, Set, Union
import requests
import test_infra.utils.waiting
import waiting
import yaml
from assisted_service_client import models
fro... | import contextlib
import ipaddress
import json
import os
import random
import re
import time
import warnings
from collections import Counter
from typing import Any, Dict, List, Optional, Set, Union
import requests
import test_infra.utils.waiting
import waiting
import yaml
from assisted_service_client import models
fro... |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2021, Ontario Institute for Cancer Research (OICR).
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... | # -*- coding: utf-8 -*-
"""
Copyright (c) 2021, Ontario Institute for Cancer Research (OICR).
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... |
import os
import sys
import re
import logging
from packaging import version
from configparser import ConfigParser
from tempfile import mkstemp
from shutil import move, copymode
from os import fdopen, remove
from pathlib import Path
from git import Repo
from datetime import datetime
from rich import print
from mlf_core... | import os
import sys
import re
import logging
from packaging import version
from configparser import ConfigParser
from tempfile import mkstemp
from shutil import move, copymode
from os import fdopen, remove
from pathlib import Path
from git import Repo
from datetime import datetime
from rich import print
from mlf_core... |
import pytest
import vcr
from app import APP, cli
RUNNER = APP.test_cli_runner()
# https://flask.palletsprojects.com/en/1.1.x/testing/#testing-cli-commands
@vcr.use_cassette('tests/fixtures/vcr_cassettes/import_data.yml')
def _test_import_data():
result = RUNNER.invoke(cli.import_data, ['--date', APP.config.ge... | import pytest
import vcr
from app import APP, cli
RUNNER = APP.test_cli_runner()
# https://flask.palletsprojects.com/en/1.1.x/testing/#testing-cli-commands
@vcr.use_cassette('tests/fixtures/vcr_cassettes/import_data.yml')
def _test_import_data():
result = RUNNER.invoke(cli.import_data, ['--date', APP.config.ge... |
"""Utilities for submitting and starting Work Queue workers.
"""
import argparse
import os
import re
import subprocess
from shadho.configuration import ShadhoConfig
def parse_args(args=None):
p = argparse.ArgumentParser(
description='Start a Work Queue worker and connect to SHADHO.')
p.add_argumen... | """Utilities for submitting and starting Work Queue workers.
"""
import argparse
import os
import re
import subprocess
from shadho.configuration import ShadhoConfig
def parse_args(args=None):
p = argparse.ArgumentParser(
description='Start a Work Queue worker and connect to SHADHO.')
p.add_argumen... |
from Funcoes.banco import conexao
from Model.Veiculo import Veiculo
from Model.Vendas_Header import Vendas_Header
from Model.Cliente import Cliente
class Pendencias:
def __init__(self, pend_id="", cliente: Cliente = "", venda: Vendas_Header = "", veiculo: Veiculo = "",
datahora="", valor=""):
... | from Funcoes.banco import conexao
from Model.Veiculo import Veiculo
from Model.Vendas_Header import Vendas_Header
from Model.Cliente import Cliente
class Pendencias:
def __init__(self, pend_id="", cliente: Cliente = "", venda: Vendas_Header = "", veiculo: Veiculo = "",
datahora="", valor=""):
... |
import logging
from .common import extract_typed_props, PropertyMeta
from ..builders.external_doc import ExternalDocBuilder
from ..specification import Tag
logger = logging.getLogger(__name__)
class TagBuilder:
_external_doc_builder: ExternalDocBuilder
def __init__(self, external_doc_builder: ExternalDocBu... | import logging
from .common import extract_typed_props, PropertyMeta
from ..builders.external_doc import ExternalDocBuilder
from ..specification import Tag
logger = logging.getLogger(__name__)
class TagBuilder:
_external_doc_builder: ExternalDocBuilder
def __init__(self, external_doc_builder: ExternalDocBu... |
########
#GRADED: 24/25
# Homework 3
#
# MAKE SURE YOU ARE RUNNING THIS WITH PYTHON 3!
# Python 2 will give a "Non-ASCII character" error
#
# Either use workon/mkvirtualenv to create an
# environment or use the python3 command
#
########
########
#
# Here is a programmer!
#
########
programmer = {
'name': 'Christin... | ########
#GRADED: 24/25
# Homework 3
#
# MAKE SURE YOU ARE RUNNING THIS WITH PYTHON 3!
# Python 2 will give a "Non-ASCII character" error
#
# Either use workon/mkvirtualenv to create an
# environment or use the python3 command
#
########
########
#
# Here is a programmer!
#
########
programmer = {
'name': 'Christin... |
import numpy as np
from sklearn.metrics import average_precision_score
from sklearn.metrics import roc_auc_score
def _fast_hist(label_true, label_pred, n_class):
mask = (label_true >= 0) & (label_true < n_class)
hist = np.bincount(
n_class * label_true[mask].astype(int) + label_pred[mask], minlength=n... | import numpy as np
from sklearn.metrics import average_precision_score
from sklearn.metrics import roc_auc_score
def _fast_hist(label_true, label_pred, n_class):
mask = (label_true >= 0) & (label_true < n_class)
hist = np.bincount(
n_class * label_true[mask].astype(int) + label_pred[mask], minlength=n... |
"""
cartesian grid
"""
from __future__ import annotations
import logging
import typing as T
import numpy as np
from .. import read
from ..coord import geog2geomag, geomag2geog
from .uniform import altitude_grid, grid1d
def cart3d(p: dict[str, T.Any]) -> dict[str, T.Any]:
"""make cartesian grid
Parameters
... | """
cartesian grid
"""
from __future__ import annotations
import logging
import typing as T
import numpy as np
from .. import read
from ..coord import geog2geomag, geomag2geog
from .uniform import altitude_grid, grid1d
def cart3d(p: dict[str, T.Any]) -> dict[str, T.Any]:
"""make cartesian grid
Parameters
... |
"""
Plotting helpers
================
"""
import os
import joblib
import logging
import sklearn.metrics
import pandas as pd
from .list_runs import ListRuns
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import math
logger = logging.getLogger(__name__)
def plot_confusion_matrix(
run... | """
Plotting helpers
================
"""
import os
import joblib
import logging
import sklearn.metrics
import pandas as pd
from .list_runs import ListRuns
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import math
logger = logging.getLogger(__name__)
def plot_confusion_matrix(
run... |
from __future__ import annotations
import re
from functools import wraps
from typing import Callable, Any, TypeVar
from warepy import format_message, snakefy
from puft.core.db.model_not_found_error import ModelNotFoundError
from puft.tools.log import log
from flask import Flask
import flask_migrate
from flask_sqlalche... | from __future__ import annotations
import re
from functools import wraps
from typing import Callable, Any, TypeVar
from warepy import format_message, snakefy
from puft.core.db.model_not_found_error import ModelNotFoundError
from puft.tools.log import log
from flask import Flask
import flask_migrate
from flask_sqlalche... |
"""Classes to manage credentials."""
import asyncio
import json
import logging
from typing import Mapping, Tuple
from ....cache.base import BaseCache
from ....core.error import BaseError
from ....core.profile import Profile
from ....indy.holder import IndyHolder, IndyHolderError
from ....indy.issuer import IndyIssue... | """Classes to manage credentials."""
import asyncio
import json
import logging
from typing import Mapping, Tuple
from ....cache.base import BaseCache
from ....core.error import BaseError
from ....core.profile import Profile
from ....indy.holder import IndyHolder, IndyHolderError
from ....indy.issuer import IndyIssue... |
"""
Manager and Serializer for libraries.
"""
import logging
from typing import (
Any,
Dict,
List,
Optional,
)
from sqlalchemy import and_, false, not_, or_, true
from sqlalchemy.orm.exc import MultipleResultsFound
from sqlalchemy.orm.exc import NoResultFound
from galaxy import (
exceptions,
u... | """
Manager and Serializer for libraries.
"""
import logging
from typing import (
Any,
Dict,
List,
Optional,
)
from sqlalchemy import and_, false, not_, or_, true
from sqlalchemy.orm.exc import MultipleResultsFound
from sqlalchemy.orm.exc import NoResultFound
from galaxy import (
exceptions,
u... |
import curses
import sys
import time
import subprocess
import select
import collections
import datetime
import apache_log_parser
from apache_log_parser import LineDoesntMatchException
from src import logreporter
class HttpLogParser:
def c_main(stdscr: 'curses._CursesWindow', log_file, alert_window, alert_thresh... | import curses
import sys
import time
import subprocess
import select
import collections
import datetime
import apache_log_parser
from apache_log_parser import LineDoesntMatchException
from src import logreporter
class HttpLogParser:
def c_main(stdscr: 'curses._CursesWindow', log_file, alert_window, alert_thresh... |
"""
Container, Well, WellGroup objects and associated functions
:copyright: 2020 by The Autoprotocol Development Team, see AUTHORS
for more details.
:license: BSD, see LICENSE for more details
"""
import json
import warnings
from .constants import SBS_FORMAT_SHAPES
from .unit import Unit
SEAL_TYPES... | """
Container, Well, WellGroup objects and associated functions
:copyright: 2020 by The Autoprotocol Development Team, see AUTHORS
for more details.
:license: BSD, see LICENSE for more details
"""
import json
import warnings
from .constants import SBS_FORMAT_SHAPES
from .unit import Unit
SEAL_TYPES... |
import asyncio
import dataclasses
import logging
from pathlib import Path
from typing import Callable, Dict, List, Optional, Tuple, Set, Any
from blspy import PrivateKey, G1Element
from chia.consensus.block_rewards import calculate_base_farmer_reward
from chia.pools.pool_wallet import PoolWallet
from chia.pools.pool_... | import asyncio
import dataclasses
import logging
from pathlib import Path
from typing import Callable, Dict, List, Optional, Tuple, Set, Any
from blspy import PrivateKey, G1Element
from chia.consensus.block_rewards import calculate_base_farmer_reward
from chia.pools.pool_wallet import PoolWallet
from chia.pools.pool_... |
#!/usr/bin/env python
# Modules
from pygnmi.client import gNMIclient
# Variables
from inventory import hosts
# Body
if __name__ == "__main__":
paths = ['openconfig-interfaces:interfaces', 'openconfig-network-instance:network-instances']
for host in hosts:
with gNMIclient(target=(host["ip_address"], ... | #!/usr/bin/env python
# Modules
from pygnmi.client import gNMIclient
# Variables
from inventory import hosts
# Body
if __name__ == "__main__":
paths = ['openconfig-interfaces:interfaces', 'openconfig-network-instance:network-instances']
for host in hosts:
with gNMIclient(target=(host["ip_address"], ... |
from discord_webhook import DiscordWebhook
import mysql.connector
import sys
import argparse
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from dateutil.parser import pars... | from discord_webhook import DiscordWebhook
import mysql.connector
import sys
import argparse
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from dateutil.parser import pars... |
"""Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra “A”, em que posição ela
aparece a primeira vez e em que posição ela aparece a última vez"""
frase = input('Digite algo: ').strip().upper()
print(f'\nA letras A aparece {frase.count('A')} vezes')
print(f'´A´ aparece a primeira v... | """Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra “A”, em que posição ela
aparece a primeira vez e em que posição ela aparece a última vez"""
frase = input('Digite algo: ').strip().upper()
print(f'\nA letras A aparece {frase.count("A")} vezes')
print(f'´A´ aparece a primeira v... |
import argparse
import datetime
import os
import pprint
import numpy as np
import torch
from atari_network import DQN
from atari_wrapper import make_atari_env
from torch.utils.tensorboard import SummaryWriter
from tianshou.data import Collector, VectorReplayBuffer
from tianshou.policy import DQNPolicy
from tianshou.p... | import argparse
import datetime
import os
import pprint
import numpy as np
import torch
from atari_network import DQN
from atari_wrapper import make_atari_env
from torch.utils.tensorboard import SummaryWriter
from tianshou.data import Collector, VectorReplayBuffer
from tianshou.policy import DQNPolicy
from tianshou.p... |
import logging
import os
from typing import Any, Dict
from src.helpers.logging import add_logging
from src.helpers.types import AnyEntity
@add_logging(level=logging.DEBUG)
def parse_entity(text: str, entity_info: AnyEntity, logger: logging.Logger) -> str:
"""Extracts the entity substring from the given text, bas... | import logging
import os
from typing import Any, Dict
from src.helpers.logging import add_logging
from src.helpers.types import AnyEntity
@add_logging(level=logging.DEBUG)
def parse_entity(text: str, entity_info: AnyEntity, logger: logging.Logger) -> str:
"""Extracts the entity substring from the given text, bas... |
import copy
import logging
import re
from markupsafe import escape
from galaxy import model, util
from galaxy.web.framework.helpers import grids, iff, time_ago
from galaxy.webapps.base.controller import BaseUIController, web
log = logging.getLogger(__name__)
VALID_FIELDNAME_RE = re.compile(r"^[a-zA-Z0-9\_]+$")
cl... | import copy
import logging
import re
from markupsafe import escape
from galaxy import model, util
from galaxy.web.framework.helpers import grids, iff, time_ago
from galaxy.webapps.base.controller import BaseUIController, web
log = logging.getLogger(__name__)
VALID_FIELDNAME_RE = re.compile(r"^[a-zA-Z0-9\_]+$")
cl... |
import copy
from operator import itemgetter
from typing import Tuple, Callable
import demistomock as demisto # noqa: F401
import urllib3
from CommonServerPython import * # noqa: F401
# Disable insecure warnings
urllib3.disable_warnings()
TIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
NONCE_LENGTH = 64
API_KEY_LENGTH = 128
INT... | import copy
from operator import itemgetter
from typing import Tuple, Callable
import demistomock as demisto # noqa: F401
import urllib3
from CommonServerPython import * # noqa: F401
# Disable insecure warnings
urllib3.disable_warnings()
TIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
NONCE_LENGTH = 64
API_KEY_LENGTH = 128
INT... |
import csv
import json
import logging
import time
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
import shared
# time pipenv run python estimate_personal_coefficients.py
race_type = shared.race_type()
year = shared.forecast_year()
startTime = time.time()
ideal_paces = pd.r... | import csv
import json
import logging
import time
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
import shared
# time pipenv run python estimate_personal_coefficients.py
race_type = shared.race_type()
year = shared.forecast_year()
startTime = time.time()
ideal_paces = pd.r... |
# Copyright 2020 - 2021 MONAI Consortium
# 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 wri... | # Copyright 2020 - 2021 MONAI Consortium
# 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 wri... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import time
from abc import ABC, abstractmethod
from copy import deepcopy
from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Union
from urllib import parse
import requests
from airbyte_cdk.models import SyncMode
from airbyte_cdk.sour... | #
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import time
from abc import ABC, abstractmethod
from copy import deepcopy
from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Union
from urllib import parse
import requests
from airbyte_cdk.models import SyncMode
from airbyte_cdk.sour... |
#!/usr/bin/env python3
# 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.
"""
Allows a model to self-chat on a given task.
"""
from parlai.core.params import ParlaiParser
from parlai.core.agents ... | #!/usr/bin/env python3
# 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.
"""
Allows a model to self-chat on a given task.
"""
from parlai.core.params import ParlaiParser
from parlai.core.agents ... |
import asyncio
import logging
from datetime import datetime
from typing import List
from heisenbridge.command_parse import CommandParser
from heisenbridge.private_room import PrivateRoom
class NetworkRoom:
pass
class ChannelRoom(PrivateRoom):
key: str
names_buffer: List[str]
bans_buffer: List[str]
... | import asyncio
import logging
from datetime import datetime
from typing import List
from heisenbridge.command_parse import CommandParser
from heisenbridge.private_room import PrivateRoom
class NetworkRoom:
pass
class ChannelRoom(PrivateRoom):
key: str
names_buffer: List[str]
bans_buffer: List[str]
... |
import multiprocessing
import telegram
from flask import (
abort,
Flask,
jsonify,
redirect,
request,
)
from spotigram.authorization import retrieve_token_info
def user_link(user):
return f'[{user}](https://open.spotify.com/user/{user})'
def _build_app_and_bot_for(bot_cls):
app = Flask(... | import multiprocessing
import telegram
from flask import (
abort,
Flask,
jsonify,
redirect,
request,
)
from spotigram.authorization import retrieve_token_info
def user_link(user):
return f'[{user}](https://open.spotify.com/user/{user})'
def _build_app_and_bot_for(bot_cls):
app = Flask(... |
import re
import pandas as pd
from shutil import copyfile
from chinese_shadowing.config import path_data
from chinese_shadowing.config import path_temporary
if __name__ == '__main__':
folder_name = 'HSK 1-6 2012'
media_location = path_temporary / folder_name
path_notes = path_temporary.joinpath('notes').w... | import re
import pandas as pd
from shutil import copyfile
from chinese_shadowing.config import path_data
from chinese_shadowing.config import path_temporary
if __name__ == '__main__':
folder_name = 'HSK 1-6 2012'
media_location = path_temporary / folder_name
path_notes = path_temporary.joinpath('notes').w... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import json
import os
import random
import re
import shutil
import socket
import string
import subprocess
import sys
import threading
import time
from typing import Any, Dict, List
from normalization.destination_type import DestinationType
from normalizati... | #
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import json
import os
import random
import re
import shutil
import socket
import string
import subprocess
import sys
import threading
import time
from typing import Any, Dict, List
from normalization.destination_type import DestinationType
from normalizati... |
# ---------------------------------------------------------------------------#
# DRACOON API Python examples
# Perform bulk edit permissions on data rooms one can manage
# Requires dracoon package
# Author: Octavio Simone, 03.08.2021
# ---------------------------------------------------------------------------#
from ... | # ---------------------------------------------------------------------------#
# DRACOON API Python examples
# Perform bulk edit permissions on data rooms one can manage
# Requires dracoon package
# Author: Octavio Simone, 03.08.2021
# ---------------------------------------------------------------------------#
from ... |
import h3
import json
from fuzzywuzzy import fuzz
from pyspark.sql.functions import udf
from pyspark.sql.types import ArrayType, DoubleType, FloatType, IntegerType, StringType, StructField, StructType
from shapely.geometry import shape
DEFAULT_RESOLUTION = 11
# Get H3 index for coordinates pair
@udf(returnType=Strin... | import h3
import json
from fuzzywuzzy import fuzz
from pyspark.sql.functions import udf
from pyspark.sql.types import ArrayType, DoubleType, FloatType, IntegerType, StringType, StructField, StructType
from shapely.geometry import shape
DEFAULT_RESOLUTION = 11
# Get H3 index for coordinates pair
@udf(returnType=Strin... |
"""Kamereon API."""
import logging
from json import dumps as json_dumps
from typing import Any
from typing import cast
from typing import Dict
from typing import List
from typing import Optional
from warnings import warn
import aiohttp
from marshmallow.schema import Schema
from . import models
from . import schemas
... | """Kamereon API."""
import logging
from json import dumps as json_dumps
from typing import Any
from typing import cast
from typing import Dict
from typing import List
from typing import Optional
from warnings import warn
import aiohttp
from marshmallow.schema import Schema
from . import models
from . import schemas
... |
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import warnings
from abc import ABCMeta
from collections import defaultdict
from logging import FileHandler
import torch.nn as nn
from mmcv.runner.dist_utils import master_only
from mmcv.utils.logging import get_logger, logger_initialized, print_log
class ... | # Copyright (c) OpenMMLab. All rights reserved.
import copy
import warnings
from abc import ABCMeta
from collections import defaultdict
from logging import FileHandler
import torch.nn as nn
from mmcv.runner.dist_utils import master_only
from mmcv.utils.logging import get_logger, logger_initialized, print_log
class ... |
import argparse
import glob
import importlib
import os
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import gym
import stable_baselines3 as sb3 # noqa: F401
import torch as th # noqa: F401
import yaml
from sb3_contrib import QRDQN, TQC
from stable_baselines3 import A2C, DDPG, DQN, PPO, SAC, TD... | import argparse
import glob
import importlib
import os
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import gym
import stable_baselines3 as sb3 # noqa: F401
import torch as th # noqa: F401
import yaml
from sb3_contrib import QRDQN, TQC
from stable_baselines3 import A2C, DDPG, DQN, PPO, SAC, TD... |
import os
import sys
import time
from collections import namedtuple
import pendulum
from dagster import check, seven
from dagster.core.definitions.run_request import InstigatorType
from dagster.core.definitions.sensor_definition import DefaultSensorStatus, SensorExecutionData
from dagster.core.errors import DagsterEr... | import os
import sys
import time
from collections import namedtuple
import pendulum
from dagster import check, seven
from dagster.core.definitions.run_request import InstigatorType
from dagster.core.definitions.sensor_definition import DefaultSensorStatus, SensorExecutionData
from dagster.core.errors import DagsterEr... |
import argparse
import asyncio
import copy
import json
from argparse import Namespace
from contextlib import ExitStack
from typing import Optional, Sequence, Dict
import os
from .... import __default_host__, __resources_path__
from ....enums import replace_enum_to_str
from ....importer import ImportExtensions
from ..... | import argparse
import asyncio
import copy
import json
from argparse import Namespace
from contextlib import ExitStack
from typing import Optional, Sequence, Dict
import os
from .... import __default_host__, __resources_path__
from ....enums import replace_enum_to_str
from ....importer import ImportExtensions
from ..... |
import datetime
import re
import sys
import time
import types
import yaml
from botocore.exceptions import ClientError
from ..cluster.object import AWSCluster
from ..eks.service import DEFAULT_KUBERNETES_VERSION, SUPPORTED_KUBERNETES_VERSIONS
from ..exceptions import AwsClusterSharePermissionError, AwsPermissionsError... | import datetime
import re
import sys
import time
import types
import yaml
from botocore.exceptions import ClientError
from ..cluster.object import AWSCluster
from ..eks.service import DEFAULT_KUBERNETES_VERSION, SUPPORTED_KUBERNETES_VERSIONS
from ..exceptions import AwsClusterSharePermissionError, AwsPermissionsError... |
# type: ignore
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ---------------------------------------------... | # type: ignore
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ---------------------------------------------... |
from datetime import datetime
from typing import Dict, List, Union
from urllib.parse import quote
from .woql_library import WOQLLib
from .woql_query import WOQLQuery
WOQLTYPE_TO_PYTYPE = {
"string": str,
"boolean": bool,
"integer": int,
"decimal": float,
"dateTime": datetime,
}
class WOQLClass:
... | from datetime import datetime
from typing import Dict, List, Union
from urllib.parse import quote
from .woql_library import WOQLLib
from .woql_query import WOQLQuery
WOQLTYPE_TO_PYTYPE = {
"string": str,
"boolean": bool,
"integer": int,
"decimal": float,
"dateTime": datetime,
}
class WOQLClass:
... |
import os
import shutil
import subprocess
import yaml
from typing import List, Optional
def get_unity_executable_path():
UNITY_VERSION = os.environ["UNITY_VERSION"]
BOKKEN_UNITY = f"/Users/bokken/{UNITY_VERSION}/Unity.app/Contents/MacOS/Unity"
HUB_UNITY = (
f"/Applications/Unity/Hub/Editor/{UNITY_... | import os
import shutil
import subprocess
import yaml
from typing import List, Optional
def get_unity_executable_path():
UNITY_VERSION = os.environ["UNITY_VERSION"]
BOKKEN_UNITY = f"/Users/bokken/{UNITY_VERSION}/Unity.app/Contents/MacOS/Unity"
HUB_UNITY = (
f"/Applications/Unity/Hub/Editor/{UNITY_... |
import mysql.connector
def main():
connection = mysql.connector.connect(
host='lahman.csw1rmup8ri6.us-east-1.rds.amazonaws.com',
user='python',
passwd='python',
db='lahmansbaseballdb'
)
cursor = connection.cursor(prepared=True)
query = """SELECT p.nameFirst, p.nameLast... | import mysql.connector
def main():
connection = mysql.connector.connect(
host='lahman.csw1rmup8ri6.us-east-1.rds.amazonaws.com',
user='python',
passwd='python',
db='lahmansbaseballdb'
)
cursor = connection.cursor(prepared=True)
query = """SELECT p.nameFirst, p.nameLast... |
import argparse
import json
parser = argparse.ArgumentParser(description="Configuration Generator")
parser.add_argument(
"-f",
"--file-location",
help="The configuration location to be stored in. Must be "
"a json file. Example: 'bfb11.json'",
type=argparse.FileType("w+"),
default="config.json"... | import argparse
import json
parser = argparse.ArgumentParser(description="Configuration Generator")
parser.add_argument(
"-f",
"--file-location",
help="The configuration location to be stored in. Must be "
"a json file. Example: 'bfb11.json'",
type=argparse.FileType("w+"),
default="config.json"... |
"Самотестирование сети"
import speedtest
import sys
from colorama import init
from rich.panel import Panel
from rich.style import Style as STL
from rich.console import Console
init(autoreset=True)
console2 = Console()
def nettest():
with console2.status("[cyan]Ожидайте, идёт самотестирование сети..."):
... | "Самотестирование сети"
import speedtest
import sys
from colorama import init
from rich.panel import Panel
from rich.style import Style as STL
from rich.console import Console
init(autoreset=True)
console2 = Console()
def nettest():
with console2.status("[cyan]Ожидайте, идёт самотестирование сети..."):
... |
# Task Inference based meta-rl algorithm using Gaussian mixture models and gated Recurrent units (TIGR)
import os
import numpy as np
import click
import json
import torch
import copy
from rlkit.envs import ENVS
from rlkit.envs.wrappers import NormalizedBoxEnv
from rlkit.torch.sac.policies import TanhGaussianPolicy
fr... | # Task Inference based meta-rl algorithm using Gaussian mixture models and gated Recurrent units (TIGR)
import os
import numpy as np
import click
import json
import torch
import copy
from rlkit.envs import ENVS
from rlkit.envs.wrappers import NormalizedBoxEnv
from rlkit.torch.sac.policies import TanhGaussianPolicy
fr... |
# -*- encoding: utf-8 -*-
#
# 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, so... | # -*- encoding: utf-8 -*-
#
# 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, so... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 3.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... | # Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 3.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... |
import codecs
from functools import partial
import json
import os
from typing import Any, List, Match, Tuple, Union # pylint: disable=unused-import
from urllib.parse import urljoin, urlencode, quote as urlquote
from jinja2 import Environment, PackageLoader, select_autoescape, Markup, escape
import thor
from redbot ... | import codecs
from functools import partial
import json
import os
from typing import Any, List, Match, Tuple, Union # pylint: disable=unused-import
from urllib.parse import urljoin, urlencode, quote as urlquote
from jinja2 import Environment, PackageLoader, select_autoescape, Markup, escape
import thor
from redbot ... |
import logging
import clamd
import sys
from rest_framework.exceptions import ValidationError
from django.conf import settings
logger = logging.getLogger(__name__)
def file_scan_validation(file):
"""
This validator sends the file to ClamAV for scanning and returns returns to the form. By default, if antiviru... | import logging
import clamd
import sys
from rest_framework.exceptions import ValidationError
from django.conf import settings
logger = logging.getLogger(__name__)
def file_scan_validation(file):
"""
This validator sends the file to ClamAV for scanning and returns returns to the form. By default, if antiviru... |
#!/usr/bin/python3
import json
import re
from pathlib import Path
from textwrap import TextWrapper
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union
import eth_abi
from eth_hash.auto import keccak
from eth_utils import remove_0x_prefix
from hexbytes import HexBytes
from brownie._config i... | #!/usr/bin/python3
import json
import re
from pathlib import Path
from textwrap import TextWrapper
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union
import eth_abi
from eth_hash.auto import keccak
from eth_utils import remove_0x_prefix
from hexbytes import HexBytes
from brownie._config i... |
import datetime
import functools
import json
import os
import re
import tempfile
from collections import OrderedDict, namedtuple
from django.conf import settings
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.http.response import Http404, JsonResponse
from dj... | import datetime
import functools
import json
import os
import re
import tempfile
from collections import OrderedDict, namedtuple
from django.conf import settings
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.http.response import Http404, JsonResponse
from dj... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.