edited_code stringlengths 17 978k | original_code stringlengths 17 978k |
|---|---|
import warnings
import torch
from torch.nn import GroupNorm, LayerNorm
from torch.nn.modules.batchnorm import _BatchNorm
from torch.nn.modules.instancenorm import _InstanceNorm
from ..utils import build_from_cfg
from .builder import OPTIMIZER_BUILDERS, OPTIMIZERS
@OPTIMIZER_BUILDERS.register_module
class DefaultOpt... | import warnings
import torch
from torch.nn import GroupNorm, LayerNorm
from torch.nn.modules.batchnorm import _BatchNorm
from torch.nn.modules.instancenorm import _InstanceNorm
from ..utils import build_from_cfg
from .builder import OPTIMIZER_BUILDERS, OPTIMIZERS
@OPTIMIZER_BUILDERS.register_module
class DefaultOpt... |
from pathlib import Path
import shutil
import os
import sys
def convert_repo_to_fork(path2repo):
path_fork = path2repo.parent / "yolov5-icevision" # path of our fork
if path_fork.is_dir():
shutil.rmtree(path_fork)
path_fork.mkdir(exist_ok=True)
_ = shutil.copytree(path2repo, path_fork, dir... | from pathlib import Path
import shutil
import os
import sys
def convert_repo_to_fork(path2repo):
path_fork = path2repo.parent / "yolov5-icevision" # path of our fork
if path_fork.is_dir():
shutil.rmtree(path_fork)
path_fork.mkdir(exist_ok=True)
_ = shutil.copytree(path2repo, path_fork, dir... |
from pandac.PandaModules import Point3, VBase3, Vec4, Vec3
objectStruct = {'Objects': {'1149705583.09Shochet': {'Type': 'Island','Name': 'VegasIsland','File': '','Environment': 'Interior','Minimap': False,'Objects': {'1149705605.5Shochet': {'Type': 'Locator Node','Name': 'portal_exterior_1','Hpr': VBase3(-18.331, 0.0, ... | from pandac.PandaModules import Point3, VBase3, Vec4, Vec3
objectStruct = {'Objects': {'1149705583.09Shochet': {'Type': 'Island','Name': 'VegasIsland','File': '','Environment': 'Interior','Minimap': False,'Objects': {'1149705605.5Shochet': {'Type': 'Locator Node','Name': 'portal_exterior_1','Hpr': VBase3(-18.331, 0.0, ... |
"""
Various ugly utility functions for twill.
Apart from various simple utility functions, twill's robust parsing
code is implemented in the ConfigurableParsingFactory class.
"""
import os
import re
from collections import namedtuple
from lxml import html
try:
import tidylib
except (ImportError, OSError):
... | """
Various ugly utility functions for twill.
Apart from various simple utility functions, twill's robust parsing
code is implemented in the ConfigurableParsingFactory class.
"""
import os
import re
from collections import namedtuple
from lxml import html
try:
import tidylib
except (ImportError, OSError):
... |
# Copyright 2020 Ram Rachum and collaborators.
# This program is distributed under the MIT license.
from __future__ import annotations
import math
import inspect
import re
import abc
import random
import itertools
import collections.abc
import statistics
import concurrent.futures
import enum
import functools
import n... | # Copyright 2020 Ram Rachum and collaborators.
# This program is distributed under the MIT license.
from __future__ import annotations
import math
import inspect
import re
import abc
import random
import itertools
import collections.abc
import statistics
import concurrent.futures
import enum
import functools
import n... |
from typing import Dict, TextIO
from utils.file import write_enum
from utils.string import to_pascal_case
def read_template() -> str:
template_file: TextIO = open("./file_templates/csharp-enum.cs", "r")
return template_file.read()
def as_enum_row(key: object, json: object) -> str:
enum_name = to_pascal... | from typing import Dict, TextIO
from utils.file import write_enum
from utils.string import to_pascal_case
def read_template() -> str:
template_file: TextIO = open("./file_templates/csharp-enum.cs", "r")
return template_file.read()
def as_enum_row(key: object, json: object) -> str:
enum_name = to_pascal... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from typi... | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from typi... |
import sys
import click
import os
import datetime
from unittest import TestCase, main
from frigate.video import process_frames, start_or_restart_ffmpeg, capture_frames, get_frame_shape
from frigate.util import DictFrameManager, EventsPerSecond, draw_box_with_label
from frigate.motion import MotionDetector
from frigate.... | import sys
import click
import os
import datetime
from unittest import TestCase, main
from frigate.video import process_frames, start_or_restart_ffmpeg, capture_frames, get_frame_shape
from frigate.util import DictFrameManager, EventsPerSecond, draw_box_with_label
from frigate.motion import MotionDetector
from frigate.... |
# 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 ... |
"""create DOEs and execute design workflow
Caution:
This module requires fa_pytuils and delismm!
Please contatct the developers for these additional packages.
"""
import os
from collections import OrderedDict
import datetime
import numpy as np
import matplotlib.pyplot as plt
from delismm.model.doe import LatinizedCe... | """create DOEs and execute design workflow
Caution:
This module requires fa_pytuils and delismm!
Please contatct the developers for these additional packages.
"""
import os
from collections import OrderedDict
import datetime
import numpy as np
import matplotlib.pyplot as plt
from delismm.model.doe import LatinizedCe... |
"""
This module controls defines celery tasks and their applicable schedules. The celery beat server and workers will start
when invoked. Please add internal-only celery tasks to the celery_tasks plugin.
When ran in development mode (CONFIG_LOCATION=<location of development.yaml configuration file. To run both the cel... | """
This module controls defines celery tasks and their applicable schedules. The celery beat server and workers will start
when invoked. Please add internal-only celery tasks to the celery_tasks plugin.
When ran in development mode (CONFIG_LOCATION=<location of development.yaml configuration file. To run both the cel... |
import pathlib
import os
from typing import Optional
import vswhere
def find_cmake() -> Optional[pathlib.Path]:
# search in PATH
for p in os.getenv('PATH').split(';'):
cmake = pathlib.Path(p) / 'cmake.exe'
if cmake.exists():
return cmake
# default path
cmake = pathlib.Path... | import pathlib
import os
from typing import Optional
import vswhere
def find_cmake() -> Optional[pathlib.Path]:
# search in PATH
for p in os.getenv('PATH').split(';'):
cmake = pathlib.Path(p) / 'cmake.exe'
if cmake.exists():
return cmake
# default path
cmake = pathlib.Path... |
"""Script to check the configuration file."""
import argparse
import asyncio
from collections import OrderedDict
from collections.abc import Mapping, Sequence
from glob import glob
import logging
import os
from typing import Any, Callable, Dict, List, Tuple
from unittest.mock import patch
from homeassistant import boo... | """Script to check the configuration file."""
import argparse
import asyncio
from collections import OrderedDict
from collections.abc import Mapping, Sequence
from glob import glob
import logging
import os
from typing import Any, Callable, Dict, List, Tuple
from unittest.mock import patch
from homeassistant import boo... |
"""
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 os.path as osp
from copy import deepcopy
from datetime import datetime
import ignite.distributed as idist
import mmcv
from functools import partial
from ignite.contrib.handlers import ProgressBar
from ignite.contrib.metrics import ROC_AUC, AveragePrecision
from ignite.engine import Engine, Events
from ignite.ha... | import os.path as osp
from copy import deepcopy
from datetime import datetime
import ignite.distributed as idist
import mmcv
from functools import partial
from ignite.contrib.handlers import ProgressBar
from ignite.contrib.metrics import ROC_AUC, AveragePrecision
from ignite.engine import Engine, Events
from ignite.ha... |
"""Test Home Assistant template helper methods."""
from datetime import datetime
import math
import random
import pytest
import pytz
from homeassistant.components import group
from homeassistant.const import (
LENGTH_METERS,
MASS_GRAMS,
MATCH_ALL,
PRESSURE_PA,
TEMP_CELSIUS,
VOLUME_LITERS,
)
fr... | """Test Home Assistant template helper methods."""
from datetime import datetime
import math
import random
import pytest
import pytz
from homeassistant.components import group
from homeassistant.const import (
LENGTH_METERS,
MASS_GRAMS,
MATCH_ALL,
PRESSURE_PA,
TEMP_CELSIUS,
VOLUME_LITERS,
)
fr... |
#!/usr/bin/env python
# Copyright 2020 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | #!/usr/bin/env python
# Copyright 2020 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
import json
import os
from .config import API_KEY
import requests
from datetime import date
from w3lib.html import remove_tags
def save_data_to_json(file_name, data):
"""Save data to a json file creating it if it does not already exist
:parameter: file_name -> 'example' do not add the '.json'
:parameter:... | import json
import os
from .config import API_KEY
import requests
from datetime import date
from w3lib.html import remove_tags
def save_data_to_json(file_name, data):
"""Save data to a json file creating it if it does not already exist
:parameter: file_name -> 'example' do not add the '.json'
:parameter:... |
# AutoTransform
# Large scale, component based code modification library
#
# Licensed under the MIT License <http://opensource.org/licenses/MIT>
# SPDX-License-Identifier: MIT
# Copyright (c) 2022-present Nathan Rockenbach <http://github.com/nathro>
# @black_format
"""The settings command is used to update AutoTransf... | # AutoTransform
# Large scale, component based code modification library
#
# Licensed under the MIT License <http://opensource.org/licenses/MIT>
# SPDX-License-Identifier: MIT
# Copyright (c) 2022-present Nathan Rockenbach <http://github.com/nathro>
# @black_format
"""The settings command is used to update AutoTransf... |
import boto3
from datetime import datetime, timedelta
from os import environ
from src.functions.csv_dump import send_sql
rds_client = boto3.client("rds-data")
ddb_resource = boto3.resource("dynamodb")
shub_table = ddb_resource.Table(environ.get("TABLE_SHUB"))
shub_index = environ.get("SHUB_INDEX")
db_name = environ.ge... | import boto3
from datetime import datetime, timedelta
from os import environ
from src.functions.csv_dump import send_sql
rds_client = boto3.client("rds-data")
ddb_resource = boto3.resource("dynamodb")
shub_table = ddb_resource.Table(environ.get("TABLE_SHUB"))
shub_index = environ.get("SHUB_INDEX")
db_name = environ.ge... |
#!/usr/bin/env python3
"""
Common test run patterns
"""
from datetime import datetime
from clusters import NullCluster
from pre_tests import NullPreTest
from ci_tests import NullTest
from post_tests import NullPostTest
class ClusterTestSetsRunner:
"""A cluster test runner that runs multiple sets of pre, test & ... | #!/usr/bin/env python3
"""
Common test run patterns
"""
from datetime import datetime
from clusters import NullCluster
from pre_tests import NullPreTest
from ci_tests import NullTest
from post_tests import NullPostTest
class ClusterTestSetsRunner:
"""A cluster test runner that runs multiple sets of pre, test & ... |
import collections
import inspect
import logging
from typing import (
Any,
Callable,
Dict,
Optional,
Tuple,
Union,
overload,
)
from fastapi import APIRouter, FastAPI
from starlette.requests import Request
from uvicorn.config import Config
from uvicorn.lifespan.on import LifespanOn
from ray... | import collections
import inspect
import logging
from typing import (
Any,
Callable,
Dict,
Optional,
Tuple,
Union,
overload,
)
from fastapi import APIRouter, FastAPI
from starlette.requests import Request
from uvicorn.config import Config
from uvicorn.lifespan.on import LifespanOn
from ray... |
import tempfile
import argparse
import logging
import datetime
import threading
import os
import re
from botocore.exceptions import ClientError
from ocs_ci.framework import config
from ocs_ci.ocs.constants import CLEANUP_YAML, TEMPLATE_CLEANUP_DIR
from ocs_ci.ocs.exceptions import CommandFailed
from ocs_ci.utility.u... | import tempfile
import argparse
import logging
import datetime
import threading
import os
import re
from botocore.exceptions import ClientError
from ocs_ci.framework import config
from ocs_ci.ocs.constants import CLEANUP_YAML, TEMPLATE_CLEANUP_DIR
from ocs_ci.ocs.exceptions import CommandFailed
from ocs_ci.utility.u... |
from typing import List, Tuple
import logging
import pytest
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s test %(levelname)s: %(message)s",
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger("ambassador")
from ambassador import Cache, IR
from ambassador.compile import Compile
def ... | from typing import List, Tuple
import logging
import pytest
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s test %(levelname)s: %(message)s",
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger("ambassador")
from ambassador import Cache, IR
from ambassador.compile import Compile
def ... |
from os import environ
def get_program(environment_variable: str, backup: str) -> str:
return environ.get(environment_variable, default=backup)
def get_terminal_program(program: str) -> str:
return f"{PROGRAMS["terminal"]} -e {program}"
def get_site(url: str) -> str:
return f'{PROGRAMS['browser']} {ur... | from os import environ
def get_program(environment_variable: str, backup: str) -> str:
return environ.get(environment_variable, default=backup)
def get_terminal_program(program: str) -> str:
return f"{PROGRAMS['terminal']} -e {program}"
def get_site(url: str) -> str:
return f'{PROGRAMS["browser"]} {ur... |
import sqlite3
from util.constants import DATABASE
class DBManager:
def __init__(self):
self.connection = None
self.cursor = None
def connect(self):
self.connection = sqlite3.connect(DATABASE["path"])
self.cursor = self.connection.cursor()
return self
def create_t... | import sqlite3
from util.constants import DATABASE
class DBManager:
def __init__(self):
self.connection = None
self.cursor = None
def connect(self):
self.connection = sqlite3.connect(DATABASE["path"])
self.cursor = self.connection.cursor()
return self
def create_t... |
# -*- coding: utf-8 -*-
"""
Run method, and save results.
Run as:
python main.py --dataset <ds> --method <met>
where dataset name should be in UCI_Datasets folder
and method is piven, qd, deep-ens, mid or only-rmse.
"""
import argparse
import json
import datetime
import tensorflow as tf
# import tensorflow.... | # -*- coding: utf-8 -*-
"""
Run method, and save results.
Run as:
python main.py --dataset <ds> --method <met>
where dataset name should be in UCI_Datasets folder
and method is piven, qd, deep-ens, mid or only-rmse.
"""
import argparse
import json
import datetime
import tensorflow as tf
# import tensorflow.... |
import os
import logging
import copy
from tqdm import trange
from datetime import datetime
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
from torchvision.utils import save_image
from utils import ema
from lib.dataset import DataLooper
from lib.sde import VPSDE
from lib.model.ddpm i... | import os
import logging
import copy
from tqdm import trange
from datetime import datetime
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
from torchvision.utils import save_image
from utils import ema
from lib.dataset import DataLooper
from lib.sde import VPSDE
from lib.model.ddpm i... |
import json
import os
import sys
import argparse
import shutil
import uuid
import prettytable
import glob
import requests
import logging
from datetime import datetime
from zipfile import ZipFile
from typing import Any, Tuple, Union
from Tests.Marketplace.marketplace_services import init_storage_client, init_bigquery_cl... | import json
import os
import sys
import argparse
import shutil
import uuid
import prettytable
import glob
import requests
import logging
from datetime import datetime
from zipfile import ZipFile
from typing import Any, Tuple, Union
from Tests.Marketplace.marketplace_services import init_storage_client, init_bigquery_cl... |
import shutil
from typing import Dict
from covid_shared import workflow
import covid_model_seiir_pipeline
from covid_model_seiir_pipeline.pipeline.parameter_fit.specification import FIT_JOBS, FitScenario
class BetaFitTaskTemplate(workflow.TaskTemplate):
tool = workflow.get_jobmon_tool(covid_model_seiir_pipeline... | import shutil
from typing import Dict
from covid_shared import workflow
import covid_model_seiir_pipeline
from covid_model_seiir_pipeline.pipeline.parameter_fit.specification import FIT_JOBS, FitScenario
class BetaFitTaskTemplate(workflow.TaskTemplate):
tool = workflow.get_jobmon_tool(covid_model_seiir_pipeline... |
# ___________________________________________________________________________
#
# Prescient
# Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain rights in this software.
# This software is ... | # ___________________________________________________________________________
#
# Prescient
# Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain rights in this software.
# This software is ... |
"""A mixing that extends a HasDriver class with Galaxy-specific utilities.
Implementer must provide a self.build_url method to target Galaxy.
"""
import collections
import contextlib
import random
import string
import time
from abc import abstractmethod
from functools import (
partial,
wraps,
)
from typing im... | """A mixing that extends a HasDriver class with Galaxy-specific utilities.
Implementer must provide a self.build_url method to target Galaxy.
"""
import collections
import contextlib
import random
import string
import time
from abc import abstractmethod
from functools import (
partial,
wraps,
)
from typing im... |
import logging
import os
import warnings
from abc import ABC, abstractmethod
from collections import defaultdict
from os.path import join
from typing import Iterable, List, Optional, Tuple, Union
import torch
from torch import nn
from .composition import AdapterCompositionBlock, Fuse, Stack, parse_composition
from .c... | import logging
import os
import warnings
from abc import ABC, abstractmethod
from collections import defaultdict
from os.path import join
from typing import Iterable, List, Optional, Tuple, Union
import torch
from torch import nn
from .composition import AdapterCompositionBlock, Fuse, Stack, parse_composition
from .c... |
import numpy as np
import torch
from dataclasses import dataclass
from typing import List
from jiant.tasks.core import (
BaseExample,
BaseTokenizedExample,
BaseDataRow,
BatchMixin,
Task,
TaskTypes,
)
from jiant.tasks.lib.templates.shared import double_sentence_featurize, labels_to_bimap
from ji... | import numpy as np
import torch
from dataclasses import dataclass
from typing import List
from jiant.tasks.core import (
BaseExample,
BaseTokenizedExample,
BaseDataRow,
BatchMixin,
Task,
TaskTypes,
)
from jiant.tasks.lib.templates.shared import double_sentence_featurize, labels_to_bimap
from ji... |
import click
import logging
from os.path import basename, exists
from shutil import rmtree
from helper.aws import AwsApiHelper
logging.getLogger().setLevel(logging.DEBUG)
class Helper(AwsApiHelper):
def __init__(self, sql_file):
super().__init__()
self._sql_file = sql_file
with open(sql_f... | import click
import logging
from os.path import basename, exists
from shutil import rmtree
from helper.aws import AwsApiHelper
logging.getLogger().setLevel(logging.DEBUG)
class Helper(AwsApiHelper):
def __init__(self, sql_file):
super().__init__()
self._sql_file = sql_file
with open(sql_f... |
import os
import csv
import genanki
from gtts import gTTS
from mnemocards import ASSETS_DIR
from mnemocards.utils import get_hash_id, NoteID, generate_furigana
from mnemocards.builders.vocabulary_builder import VocabularyBuilder
from mnemocards.builders.vocabulary_builder import remove_parentheses, remove_spaces
fr... | import os
import csv
import genanki
from gtts import gTTS
from mnemocards import ASSETS_DIR
from mnemocards.utils import get_hash_id, NoteID, generate_furigana
from mnemocards.builders.vocabulary_builder import VocabularyBuilder
from mnemocards.builders.vocabulary_builder import remove_parentheses, remove_spaces
fr... |
import time
import logging
from spaceone.inventory.libs.manager import GoogleCloudManager
from spaceone.inventory.libs.schema.base import ReferenceModel
from spaceone.inventory.connector.instance_group import InstanceGroupConnector
from spaceone.inventory.model.instance_group.data import *
from spaceone.inventory.mode... | import time
import logging
from spaceone.inventory.libs.manager import GoogleCloudManager
from spaceone.inventory.libs.schema.base import ReferenceModel
from spaceone.inventory.connector.instance_group import InstanceGroupConnector
from spaceone.inventory.model.instance_group.data import *
from spaceone.inventory.mode... |
# 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... |
########################################################################################################################
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
if sys.version_info[0] < 3:
raise EnvironmentError("Hey, caveman, use Python 3.")
__doc__ = \
"""
PDB minimization for different... | ########################################################################################################################
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
if sys.version_info[0] < 3:
raise EnvironmentError("Hey, caveman, use Python 3.")
__doc__ = \
"""
PDB minimization for different... |
import requests
import sys
import re
def get_merged_pull_reqs_since_last_release(token):
"""
Get all the merged pull requests since the last release.
"""
stopPattern = r"^(r|R)elease v"
pull_reqs = []
found_last_release = False
page = 1
print("Getting PRs since last release.")
whi... | import requests
import sys
import re
def get_merged_pull_reqs_since_last_release(token):
"""
Get all the merged pull requests since the last release.
"""
stopPattern = r"^(r|R)elease v"
pull_reqs = []
found_last_release = False
page = 1
print("Getting PRs since last release.")
whi... |
# !/usr/bin/env python
"""
ExcisionFinder identifies allele-specific excision sites. Written in Python version 3.6.1.
Kathleen Keough et al 2017-2018.
Note: This version of the script is intended only for analysis of large cohorts, particularly the
1000 Genomes cohort. There is a more general purpose script for small... | # !/usr/bin/env python
"""
ExcisionFinder identifies allele-specific excision sites. Written in Python version 3.6.1.
Kathleen Keough et al 2017-2018.
Note: This version of the script is intended only for analysis of large cohorts, particularly the
1000 Genomes cohort. There is a more general purpose script for small... |
import sys
from pathlib import Path
import h5py
import numpy as np
import matplotlib.pyplot as plt
TWOTHETA_KEYS = ["2th", "2theta", "twotheta"]
Q_KEYS = ["q"]
INTENSITY_KEYS = ["i", "intensity", "int"]
STACK_INDICES_KEY = "stack_indices"
DPI = 300
FIGSIZE = (12,4)
FONTSIZE_LABELS = 20
FONTSIZE_TICKS = 14
LINEWIDTH ... | import sys
from pathlib import Path
import h5py
import numpy as np
import matplotlib.pyplot as plt
TWOTHETA_KEYS = ["2th", "2theta", "twotheta"]
Q_KEYS = ["q"]
INTENSITY_KEYS = ["i", "intensity", "int"]
STACK_INDICES_KEY = "stack_indices"
DPI = 300
FIGSIZE = (12,4)
FONTSIZE_LABELS = 20
FONTSIZE_TICKS = 14
LINEWIDTH ... |
import json
import os
import time
import uuid
from copy import deepcopy
from datetime import datetime, timedelta, timezone
from random import randint
from urllib.parse import parse_qs, urlparse, urlsplit
import pystac
from pydantic.datetime_parse import parse_datetime
from pystac.utils import datetime_to_str
from shap... | import json
import os
import time
import uuid
from copy import deepcopy
from datetime import datetime, timedelta, timezone
from random import randint
from urllib.parse import parse_qs, urlparse, urlsplit
import pystac
from pydantic.datetime_parse import parse_datetime
from pystac.utils import datetime_to_str
from shap... |
import copy
import time
from collections import OrderedDict
import torch
from data.dataloader import local_client_dataset, test_dataset
from models.utils import *
from utils.train_helper import validate_one_model
from utils.sampling import *
import numpy as np
from multiprocessing import Process
import time
def re... | import copy
import time
from collections import OrderedDict
import torch
from data.dataloader import local_client_dataset, test_dataset
from models.utils import *
from utils.train_helper import validate_one_model
from utils.sampling import *
import numpy as np
from multiprocessing import Process
import time
def re... |
class BatmanQuotes(object):
def get_quote(quotes, hero):
return f"{("Batman", "Joker", "Robin")["BJR".index(hero[0])]}: {quotes[int(min(hero))]}" | class BatmanQuotes(object):
def get_quote(quotes, hero):
return f"{('Batman', 'Joker', 'Robin')['BJR'.index(hero[0])]}: {quotes[int(min(hero))]}" |
# Concord
#
# Copyright (c) 2020-2021 VMware, Inc. All Rights Reserved.
#
# This product is licensed to you under the Apache 2.0 license (the "License").
# You may not use this product except in compliance with the Apache 2.0 License.
#
# This product may include a number of subcomponents with separate copyright
# noti... | # Concord
#
# Copyright (c) 2020-2021 VMware, Inc. All Rights Reserved.
#
# This product is licensed to you under the Apache 2.0 license (the "License").
# You may not use this product except in compliance with the Apache 2.0 License.
#
# This product may include a number of subcomponents with separate copyright
# noti... |
import os
import dataset
from stuf import stuf
'''HELPER FUNCTIONS'''
def init_local_db(local_db = os.path.expanduser(r'~/scripts/leavesdb.db'), src_db = r'/media/data_cifs/irodri15/data/db/leavesdb.db'):
'''
Whenever working on a new machine, run this function in order to make sure the main leavesdb.db file is sto... | import os
import dataset
from stuf import stuf
'''HELPER FUNCTIONS'''
def init_local_db(local_db = os.path.expanduser(r'~/scripts/leavesdb.db'), src_db = r'/media/data_cifs/irodri15/data/db/leavesdb.db'):
'''
Whenever working on a new machine, run this function in order to make sure the main leavesdb.db file is sto... |
from functools import reduce
import io
import json
import logging
import os
import platform
import random
import re
import shlex
import smtplib
import string
import subprocess
import time
import traceback
import stat
from copy import deepcopy
from email.mime.multipart import MIMEMultipart
from email.mime.text import MI... | from functools import reduce
import io
import json
import logging
import os
import platform
import random
import re
import shlex
import smtplib
import string
import subprocess
import time
import traceback
import stat
from copy import deepcopy
from email.mime.multipart import MIMEMultipart
from email.mime.text import MI... |
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import json
import re
from ....trello import TrelloClient
from ...console import abort, echo_info
class RCBuildCardsUpdater:
version_regex = r'(\d*)\.(\d*)\.(\d*)([-~])rc([\.-])(\d*)'
def __in... | # (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import json
import re
from ....trello import TrelloClient
from ...console import abort, echo_info
class RCBuildCardsUpdater:
version_regex = r'(\d*)\.(\d*)\.(\d*)([-~])rc([\.-])(\d*)'
def __in... |
from requests import get
from re import findall
import os
import glob
from rubika.client import Bot
import requests
from rubika.tools import Tools
from rubika.encryption import encryption
from gtts import gTTS
from mutagen.mp3 import MP3
import time
import random
import urllib
import io
bot = Bot("ssnakxcydoxdtheauejq... | from requests import get
from re import findall
import os
import glob
from rubika.client import Bot
import requests
from rubika.tools import Tools
from rubika.encryption import encryption
from gtts import gTTS
from mutagen.mp3 import MP3
import time
import random
import urllib
import io
bot = Bot("ssnakxcydoxdtheauejq... |
import dash
from dash.dependencies import Input, Output
from dash import dash_table
from dash import dcc
from dash import html
import pandas as pd
# Import data into pandas
df = pd.read_csv("data.csv")
df["Condition"] = df["Condition Category"]
df = df.drop(["Condition Category", "Missed Prices", "Index", "SKU"], axis... | import dash
from dash.dependencies import Input, Output
from dash import dash_table
from dash import dcc
from dash import html
import pandas as pd
# Import data into pandas
df = pd.read_csv("data.csv")
df["Condition"] = df["Condition Category"]
df = df.drop(["Condition Category", "Missed Prices", "Index", "SKU"], axis... |
#!/usr/bin/env python3
#
# Copyright (c) 2019 Nordic Semiconductor ASA
#
# SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
import argparse
import yaml
from os import path
import sys
from pprint import pformat
PERMITTED_STR_KEYS = ['size', 'region']
END_TO_START = 'end_to_start'
START_TO_END = 'start_to_end'
C... | #!/usr/bin/env python3
#
# Copyright (c) 2019 Nordic Semiconductor ASA
#
# SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
import argparse
import yaml
from os import path
import sys
from pprint import pformat
PERMITTED_STR_KEYS = ['size', 'region']
END_TO_START = 'end_to_start'
START_TO_END = 'start_to_end'
C... |
import pandas as pd
from pathlib import Path
from collections import Counter
import datetime
from collections import defaultdict
from faker import Factory
import faker
from preprocessing.nfeProvider import Invoice
import csv
def convert_to_numeric(num):
"""
Converte strings que representam valores monetários ... | import pandas as pd
from pathlib import Path
from collections import Counter
import datetime
from collections import defaultdict
from faker import Factory
import faker
from preprocessing.nfeProvider import Invoice
import csv
def convert_to_numeric(num):
"""
Converte strings que representam valores monetários ... |
from typing import Any, Dict, Iterable, cast
from openslides_backend.action.actions.meeting.shared_meeting import (
meeting_projector_default_replacements,
)
from openslides_backend.permissions.management_levels import (
CommitteeManagementLevel,
OrganizationManagementLevel,
)
from tests.system.action.base... | from typing import Any, Dict, Iterable, cast
from openslides_backend.action.actions.meeting.shared_meeting import (
meeting_projector_default_replacements,
)
from openslides_backend.permissions.management_levels import (
CommitteeManagementLevel,
OrganizationManagementLevel,
)
from tests.system.action.base... |
import os
import sqlite3
import traceback
class GeneralDB:
''' basic sqlite3 db which can be used for many purposes
this isnt very safe probably but i dont really care'''
def __init__(self, sessionName):
self.connection = None
self.cursor = None
self.sessionName = sessionName ... | import os
import sqlite3
import traceback
class GeneralDB:
''' basic sqlite3 db which can be used for many purposes
this isnt very safe probably but i dont really care'''
def __init__(self, sessionName):
self.connection = None
self.cursor = None
self.sessionName = sessionName ... |
#!/usr/bin/env python
'''
Advent of Code 2021 - Day 9: Smoke Basin (Part 1)
https://adventofcode.com/2021/day/9
'''
import numpy as np
class HeightMap():
def __init__(self) -> None:
self._grid = np.array([])
def add_row(self, row):
np_row = np.array(row)
if self._grid.size != 0:
... | #!/usr/bin/env python
'''
Advent of Code 2021 - Day 9: Smoke Basin (Part 1)
https://adventofcode.com/2021/day/9
'''
import numpy as np
class HeightMap():
def __init__(self) -> None:
self._grid = np.array([])
def add_row(self, row):
np_row = np.array(row)
if self._grid.size != 0:
... |
import argparse
from ast import literal_eval
from astropy.io import fits
from astropy.visualization import (
AsymmetricPercentileInterval,
LinearStretch,
LogStretch,
ImageNormalize,
)
import base64
from bson.json_util import loads
import confluent_kafka
from copy import deepcopy
import dask.distributed
... | import argparse
from ast import literal_eval
from astropy.io import fits
from astropy.visualization import (
AsymmetricPercentileInterval,
LinearStretch,
LogStretch,
ImageNormalize,
)
import base64
from bson.json_util import loads
import confluent_kafka
from copy import deepcopy
import dask.distributed
... |
import os
import copy
import ray
import argparse
import tqdm
import logging
import pandas as pd
from pathlib import Path
from datetime import datetime
import shutil
import uuid as uu_id
from typing import ClassVar, Dict, Generator, Tuple, List, Any
from proseco.evaluator.remote import run
from proseco.evaluator.progre... | import os
import copy
import ray
import argparse
import tqdm
import logging
import pandas as pd
from pathlib import Path
from datetime import datetime
import shutil
import uuid as uu_id
from typing import ClassVar, Dict, Generator, Tuple, List, Any
from proseco.evaluator.remote import run
from proseco.evaluator.progre... |
"""Support for the Netatmo cameras."""
import logging
import aiohttp
import pyatmo
import voluptuous as vol
from openpeerpower.components.camera import SUPPORT_STREAM, Camera
from openpeerpower.core import callback
from openpeerpower.exceptions import PlatformNotReady
from openpeerpower.helpers import config_validati... | """Support for the Netatmo cameras."""
import logging
import aiohttp
import pyatmo
import voluptuous as vol
from openpeerpower.components.camera import SUPPORT_STREAM, Camera
from openpeerpower.core import callback
from openpeerpower.exceptions import PlatformNotReady
from openpeerpower.helpers import config_validati... |
import os
import re
import math
import json
import tempfile
import zipfile
import bagit
import asyncio
from datetime import datetime
from asyncio import events
from ratelimit import sleep_and_retry
from ratelimit.exception import RateLimitException
from aiohttp import ClientSession, http_exceptions
import internetarch... | import os
import re
import math
import json
import tempfile
import zipfile
import bagit
import asyncio
from datetime import datetime
from asyncio import events
from ratelimit import sleep_and_retry
from ratelimit.exception import RateLimitException
from aiohttp import ClientSession, http_exceptions
import internetarch... |
import re
import smtplib
from email.message import EmailMessage
from collections import defaultdict
from datetime import datetime, timedelta
from typing import Union, List, Dict
# for 3.7 we need typing.List, typing.Dict, etc...
RebuiltLogLines = List[str]
ResultData = Union[int, RebuiltLogLines]
PerDayDict = Dict[str... | import re
import smtplib
from email.message import EmailMessage
from collections import defaultdict
from datetime import datetime, timedelta
from typing import Union, List, Dict
# for 3.7 we need typing.List, typing.Dict, etc...
RebuiltLogLines = List[str]
ResultData = Union[int, RebuiltLogLines]
PerDayDict = Dict[str... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @NetflixMovieslk
import re
import pyrogram
from pyrogram import (
filters,
Client
)
from pyrogram.types import (
InlineKeyboardButton,
InlineKeyboardMarkup,
Message,
CallbackQuery
)
from bot import Bot
from script import script
from databas... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @NetflixMovieslk
import re
import pyrogram
from pyrogram import (
filters,
Client
)
from pyrogram.types import (
InlineKeyboardButton,
InlineKeyboardMarkup,
Message,
CallbackQuery
)
from bot import Bot
from script import script
from databas... |
import json
import discord
from discord.ext import commands, tasks
from utils import *
class HelpCmd(commands.HelpCommand):
async def send_bot_help(self, mapping):
ctx = self.context
bot = ctx.bot
commands = bot.commands
result = []
for cmd in commands:
sign ... | import json
import discord
from discord.ext import commands, tasks
from utils import *
class HelpCmd(commands.HelpCommand):
async def send_bot_help(self, mapping):
ctx = self.context
bot = ctx.bot
commands = bot.commands
result = []
for cmd in commands:
sign ... |
import requests
from urllib.parse import urlparse
from bs4 import BeautifulSoup as bs
from presscontrol.utils import tprint, read_cookies
from presscontrol.config import config
import pandas as pd
import random
import urllib
import newspaper
from urllib.parse import urlparse
import datetime
from googlesearch import sea... | import requests
from urllib.parse import urlparse
from bs4 import BeautifulSoup as bs
from presscontrol.utils import tprint, read_cookies
from presscontrol.config import config
import pandas as pd
import random
import urllib
import newspaper
from urllib.parse import urlparse
import datetime
from googlesearch import sea... |
"""Exercício Python 088: Faça um programa que ajude um jogador da MEGA SENA a criar palpites.
O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo,
cadastrando tudo em uma lista composta."""
print('-=' * 25)
print(f'{'JOGO DA MEGA SENA':^50}')
print('-=' * 25)
total_j... | """Exercício Python 088: Faça um programa que ajude um jogador da MEGA SENA a criar palpites.
O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo,
cadastrando tudo em uma lista composta."""
print('-=' * 25)
print(f'{"JOGO DA MEGA SENA":^50}')
print('-=' * 25)
total_j... |
#!/usr/bin/env python3
import os
import subprocess
import json
# Text styling class
class Text:
HEADER = '\033[1;34m'
SUCCESS = '\033[1;32m'
FAIL = '\033[1;21m'
ENDC = '\033[0m'
# Shell commands class
class Commands:
INSTALL_PY_DEPS = 'sudo apt-get install -y python3 python3-distutils python3-pip ... | #!/usr/bin/env python3
import os
import subprocess
import json
# Text styling class
class Text:
HEADER = '\033[1;34m'
SUCCESS = '\033[1;32m'
FAIL = '\033[1;21m'
ENDC = '\033[0m'
# Shell commands class
class Commands:
INSTALL_PY_DEPS = 'sudo apt-get install -y python3 python3-distutils python3-pip ... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
# ReCode by @mrismanaziz
# FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot>
# t.me/SharingUserbot & t.me/L... | # Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
# ReCode by @mrismanaziz
# FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot>
# t.me/SharingUserbot & t.me/L... |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
"""OData service implementation
Details regarding batch requests and changesets:
http://www.odata.org/documentation/odata-version-2-0/batch-processing/
"""
# pylint: disable=too-many-lines
import logging
from functools import partial
import json
import random
from email.parser import Parser
from http.client im... | """OData service implementation
Details regarding batch requests and changesets:
http://www.odata.org/documentation/odata-version-2-0/batch-processing/
"""
# pylint: disable=too-many-lines
import logging
from functools import partial
import json
import random
from email.parser import Parser
from http.client im... |
from dataclasses import dataclass, field, asdict
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
@dataclass
class ComposeFile:
version: str = "3.9"
services: dict[str, dict] = field(default_factory=dict)
volumes: dict[str, None] = field(default_factory=d... | from dataclasses import dataclass, field, asdict
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
@dataclass
class ComposeFile:
version: str = "3.9"
services: dict[str, dict] = field(default_factory=dict)
volumes: dict[str, None] = field(default_factory=d... |
import discord
import os
import sys
import random
import sqlite3
from requests import get
from discord.ext.commands import Cog, command
from time import sleep
class Fun(Cog):
def __init__(self, bot):
self.bot = bot
@command(aliases=['dankmeme'])
async def meme(self, ctx):
await ctx.send(... | import discord
import os
import sys
import random
import sqlite3
from requests import get
from discord.ext.commands import Cog, command
from time import sleep
class Fun(Cog):
def __init__(self, bot):
self.bot = bot
@command(aliases=['dankmeme'])
async def meme(self, ctx):
await ctx.send(... |
from fsspec import AbstractFileSystem
from fsspec.callbacks import _DEFAULT_CALLBACK
import io
import natsort
import flywheel
class FlywheelFileSystem(AbstractFileSystem):
cachable = True
_cached = False
protocol = "flywheel"
async_impl = False
root_marker = "/"
def __init__(self, hostname, a... | from fsspec import AbstractFileSystem
from fsspec.callbacks import _DEFAULT_CALLBACK
import io
import natsort
import flywheel
class FlywheelFileSystem(AbstractFileSystem):
cachable = True
_cached = False
protocol = "flywheel"
async_impl = False
root_marker = "/"
def __init__(self, hostname, a... |
"""Alembic generated code to run database migrations."""
from logging.config import fileConfig
from os import environ
from alembic import context
from sqlalchemy import engine_from_config, pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.co... | """Alembic generated code to run database migrations."""
from logging.config import fileConfig
from os import environ
from alembic import context
from sqlalchemy import engine_from_config, pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.co... |
from datetime import datetime, timedelta
from typing import Dict
from discord import Embed
from discord.ext import commands
from .debug import generate_debug_embed
from .hyperion import (
currency_details,
hyperion_base_url,
hyperion_session,
resolve_account_id,
)
for name, id_ in [("Reoccuring Payou... | from datetime import datetime, timedelta
from typing import Dict
from discord import Embed
from discord.ext import commands
from .debug import generate_debug_embed
from .hyperion import (
currency_details,
hyperion_base_url,
hyperion_session,
resolve_account_id,
)
for name, id_ in [("Reoccuring Payou... |
from logging import error
from dotenv import dotenv_values
from main import father
import json
import discord
config = dotenv_values(".env")
# SECRET_KEY = os.getenv("TOKEN")
SECRET_KEY = config["TOKEN"]
params = None
countries = None
# with open("./../../params.json", "r") as read_file:
with open("params.json", ... | from logging import error
from dotenv import dotenv_values
from main import father
import json
import discord
config = dotenv_values(".env")
# SECRET_KEY = os.getenv("TOKEN")
SECRET_KEY = config["TOKEN"]
params = None
countries = None
# with open("./../../params.json", "r") as read_file:
with open("params.json", ... |
# Copyright 2021 Elshan Agaev
#
# 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 agr... | # Copyright 2021 Elshan Agaev
#
# 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 agr... |
import argparse
import io
import logging
import sys
from collections import OrderedDict
from dataclasses import dataclass
from pathlib import Path
from typing import List, Dict, Set, Union, Optional, TextIO
import pandas as pd
from jinja2 import Template, Environment, FileSystemLoader
from kyoto_reader import KyotoRea... | import argparse
import io
import logging
import sys
from collections import OrderedDict
from dataclasses import dataclass
from pathlib import Path
from typing import List, Dict, Set, Union, Optional, TextIO
import pandas as pd
from jinja2 import Template, Environment, FileSystemLoader
from kyoto_reader import KyotoRea... |
import logging
from typing import Dict, List, Iterable
import asyncio
import discord
from discord.ext import commands
import emoji
from .game import RideTheBus, GameState
from .result import Result
from utils import playingcards
logger = logging.getLogger(__name__)
COLOR = 0xFFFF00
ROUND_RULES = {
GameState.RE... | import logging
from typing import Dict, List, Iterable
import asyncio
import discord
from discord.ext import commands
import emoji
from .game import RideTheBus, GameState
from .result import Result
from utils import playingcards
logger = logging.getLogger(__name__)
COLOR = 0xFFFF00
ROUND_RULES = {
GameState.RE... |
# Tweepy
# Copyright 2009-2022 Joshua Roesslein
# See LICENSE for details.
import requests
class TweepyException(Exception):
"""Base exception for Tweepy
.. versionadded:: 4.0
"""
pass
class HTTPException(TweepyException):
"""HTTPException()
Exception raised when an HTTP request fails
... | # Tweepy
# Copyright 2009-2022 Joshua Roesslein
# See LICENSE for details.
import requests
class TweepyException(Exception):
"""Base exception for Tweepy
.. versionadded:: 4.0
"""
pass
class HTTPException(TweepyException):
"""HTTPException()
Exception raised when an HTTP request fails
... |
from collections import defaultdict
import csv
from logging import Logger
import logging
import os
import sys
from typing import Callable, Dict, List, Tuple
import numpy as np
import pandas as pd
from .run_training import run_training
from chemprop.args import TrainArgs
from chemprop.constants import TEST_SCORES_FILE... | from collections import defaultdict
import csv
from logging import Logger
import logging
import os
import sys
from typing import Callable, Dict, List, Tuple
import numpy as np
import pandas as pd
from .run_training import run_training
from chemprop.args import TrainArgs
from chemprop.constants import TEST_SCORES_FILE... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import timeit
import pickle
import os
import errno
import datetime
import shutil
import warnings
import traceback
import pstats
import io
import sys
import gc
import inspect
import importlib
import re
import pathlib
import types
import operator
import subprocess
import shlex
import json
import contextlib
import stat
im... | import timeit
import pickle
import os
import errno
import datetime
import shutil
import warnings
import traceback
import pstats
import io
import sys
import gc
import inspect
import importlib
import re
import pathlib
import types
import operator
import subprocess
import shlex
import json
import contextlib
import stat
im... |
#!/usr/bin/env python3
import sys
from functools import reduce
tree_encounter_check = lambda pos: 1 if pos == "#" else 0
def main(forest):
slope_mode = [
(1, 1),
(3, 1),
(5, 1),
(7, 1),
(1, 2),
]
mode_to_result = [(mode, resolve_encounters(forest, *mode)) for mode ... | #!/usr/bin/env python3
import sys
from functools import reduce
tree_encounter_check = lambda pos: 1 if pos == "#" else 0
def main(forest):
slope_mode = [
(1, 1),
(3, 1),
(5, 1),
(7, 1),
(1, 2),
]
mode_to_result = [(mode, resolve_encounters(forest, *mode)) for mode ... |
from collections import defaultdict
from datetime import date, datetime, timedelta
from dateutil.relativedelta import relativedelta
from typing import Callable
from itertools import product
from functools import lru_cache
from time import time
import platform
import multiprocessing
#empyrical风险指标计算模块
from empyrical imp... | from collections import defaultdict
from datetime import date, datetime, timedelta
from dateutil.relativedelta import relativedelta
from typing import Callable
from itertools import product
from functools import lru_cache
from time import time
import platform
import multiprocessing
#empyrical风险指标计算模块
from empyrical imp... |
# %% Imports
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier, GradientBoostingClassifier
from sklearn.metrics import r2_score, roc_curve, roc_auc_sco... |
# %% Imports
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier, GradientBoostingClassifier
from sklearn.metrics import r2_score, roc_curve, roc_auc_sco... |
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import click
import os
import string
import random
from jina.flow import Flow
RANDOM_SEED = 10 # 5
os.environ['PARALLEL'] = str(2)
os.environ['SHARDS'] = str(2)
def get_random_ws(workspace_path, length=8):
ra... | __copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import click
import os
import string
import random
from jina.flow import Flow
RANDOM_SEED = 10 # 5
os.environ['PARALLEL'] = str(2)
os.environ['SHARDS'] = str(2)
def get_random_ws(workspace_path, length=8):
ra... |
import itertools as itt
import pathlib as pl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.io import loadmat
import src.data.rasters
from src.data import dPCA as cdPCA
from src.metrics import dprime as cDP
from src.data.load import load, get_site_ids
from src.data.cache... | import itertools as itt
import pathlib as pl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.io import loadmat
import src.data.rasters
from src.data import dPCA as cdPCA
from src.metrics import dprime as cDP
from src.data.load import load, get_site_ids
from src.data.cache... |
import argparse
import logging
import os
import re
import statistics
import sys
import time
from datetime import timedelta, datetime
from threading import Thread
from typing import Dict, Tuple, Optional, List, Iterable
from tqdm import tqdm
from .env import H2TestEnv, H2Conf
from pyhttpd.result import ExecResult
log... | import argparse
import logging
import os
import re
import statistics
import sys
import time
from datetime import timedelta, datetime
from threading import Thread
from typing import Dict, Tuple, Optional, List, Iterable
from tqdm import tqdm
from .env import H2TestEnv, H2Conf
from pyhttpd.result import ExecResult
log... |
# ------------------------------------------------------------------------
# Copyright (c) 2021 megvii-model. All Rights Reserved.
# ------------------------------------------------------------------------
# Modified from BasicSR (https://github.com/xinntao/BasicSR)
# Copyright 2018-2020 BasicSR Authors
# -------------... | # ------------------------------------------------------------------------
# Copyright (c) 2021 megvii-model. All Rights Reserved.
# ------------------------------------------------------------------------
# Modified from BasicSR (https://github.com/xinntao/BasicSR)
# Copyright 2018-2020 BasicSR Authors
# -------------... |
import os
import sys
import re
import json
import platform
try:
from pathlib import Path
from colorclass import Color
from terminaltables import SingleTable
import semver
except ImportError:
print("ERROR: Need to install required modules.")
print("python3 -m pip install colorclass terminaltable... | import os
import sys
import re
import json
import platform
try:
from pathlib import Path
from colorclass import Color
from terminaltables import SingleTable
import semver
except ImportError:
print("ERROR: Need to install required modules.")
print("python3 -m pip install colorclass terminaltable... |
"""
Merges the 3 Tesla Dashcam and Sentry camera video files into 1 video. If
then further concatenates the files together to make 1 movie.
"""
import argparse
import logging
import os
import sys
from datetime import datetime, timedelta, timezone
from fnmatch import fnmatch
from glob import glob
from pathlib import Pat... | """
Merges the 3 Tesla Dashcam and Sentry camera video files into 1 video. If
then further concatenates the files together to make 1 movie.
"""
import argparse
import logging
import os
import sys
from datetime import datetime, timedelta, timezone
from fnmatch import fnmatch
from glob import glob
from pathlib import Pat... |
# coding=utf-8
from time import sleep
import readchar
import math
import numpy
import json
import pigpio
from turtle_draw import BrachioGraphTurtle
try:
pigpio.exceptions = False
rpi = pigpio.pi()
rpi.set_PWM_frequency(18, 50)
pigpio.exceptions = True
force_virtual = False
except:
print("pig... | # coding=utf-8
from time import sleep
import readchar
import math
import numpy
import json
import pigpio
from turtle_draw import BrachioGraphTurtle
try:
pigpio.exceptions = False
rpi = pigpio.pi()
rpi.set_PWM_frequency(18, 50)
pigpio.exceptions = True
force_virtual = False
except:
print("pig... |
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import itertools
import logging
from dataclasses import dataclass
from typing import Iterable
from pants.backend.python.goals import lockfile
from pant... | # Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import itertools
import logging
from dataclasses import dataclass
from typing import Iterable
from pants.backend.python.goals import lockfile
from pant... |
import click
from . import cli
from .params import project
from meltano.core.db import project_engine
from meltano.core.project import Project
from meltano.core.config_service import ConfigService
from meltano.core.plugin.settings_service import PluginSettingsService
@cli.group(invoke_without_command=True)
@click.ar... | import click
from . import cli
from .params import project
from meltano.core.db import project_engine
from meltano.core.project import Project
from meltano.core.config_service import ConfigService
from meltano.core.plugin.settings_service import PluginSettingsService
@cli.group(invoke_without_command=True)
@click.ar... |
import argparse
import os
import collections
from os import system
import re
from collections import defaultdict
parser = argparse.ArgumentParser()
parser.add_argument(
"-f",
"--folder",
default=".",
help="Specifies which folder to make the naviagtable bat file",
)
parser.add_argument(
"-n",
... | import argparse
import os
import collections
from os import system
import re
from collections import defaultdict
parser = argparse.ArgumentParser()
parser.add_argument(
"-f",
"--folder",
default=".",
help="Specifies which folder to make the naviagtable bat file",
)
parser.add_argument(
"-n",
... |
# -*- coding: utf-8 -*-
# Copyright © 2022, Neuroethology Lab Uni Tuebingen
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted under the terms of the BSD License. See
# LICENSE file in the root of the Project.
import re
import os
import glob
imp... | # -*- coding: utf-8 -*-
# Copyright © 2022, Neuroethology Lab Uni Tuebingen
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted under the terms of the BSD License. See
# LICENSE file in the root of the Project.
import re
import os
import glob
imp... |
import bs4
import requests
from typing import Union, List
from .Infopage import info, InfoPage
class SearchResult:
def __init__(self, urls: dict):
self.names = tuple(urls.keys())
self.urls = urls
def __getitem__(self, item):
if type(item) == str:
return self.urls[item]
... | import bs4
import requests
from typing import Union, List
from .Infopage import info, InfoPage
class SearchResult:
def __init__(self, urls: dict):
self.names = tuple(urls.keys())
self.urls = urls
def __getitem__(self, item):
if type(item) == str:
return self.urls[item]
... |
'''Contains helper function for this project filenames
and example band dictionary and list'''
def dirname(measurement):
'''Returns directory of .asc file in CMIP5 dataset'''
_dirname_prefix = 'bcc_csm1_1_m_rcp8_5_2080s'
_dirname_postfix = '10min_r1i1p1_no_tile_asc'
_dirname_global = './data/CMIP5'
... | '''Contains helper function for this project filenames
and example band dictionary and list'''
def dirname(measurement):
'''Returns directory of .asc file in CMIP5 dataset'''
_dirname_prefix = 'bcc_csm1_1_m_rcp8_5_2080s'
_dirname_postfix = '10min_r1i1p1_no_tile_asc'
_dirname_global = './data/CMIP5'
... |
import datetime
from email.headerregistry import Address
from typing import Any, Dict, Iterable, List, Mapping, Optional, TypeVar, Union
from unittest import mock
import orjson
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError... | import datetime
from email.headerregistry import Address
from typing import Any, Dict, Iterable, List, Mapping, Optional, TypeVar, Union
from unittest import mock
import orjson
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError... |
import subprocess
import argparse
import re
from datetime import datetime, timedelta
from time import sleep
import socket
import requests
import scapy.all as scapy
from concurrent.futures import ThreadPoolExecutor
MONITOR_INTERVAL = 60
DISCOVERY_INTERVAL = 300
parser = argparse.ArgumentParser(description="Host Monito... | import subprocess
import argparse
import re
from datetime import datetime, timedelta
from time import sleep
import socket
import requests
import scapy.all as scapy
from concurrent.futures import ThreadPoolExecutor
MONITOR_INTERVAL = 60
DISCOVERY_INTERVAL = 300
parser = argparse.ArgumentParser(description="Host Monito... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.