edited_code stringlengths 17 978k | original_code stringlengths 17 978k |
|---|---|
import os
class NewT():
# 申请临时变量
def __init__(self, value):
global newT_num
self.value = value
self.name = 'T' + str(newT_num)
newT_num += 1
def __str__(self):
return self.name
def __repr__(self):
return '\nname:{:10}value:{:5}'.format(self.name, self.... | import os
class NewT():
# 申请临时变量
def __init__(self, value):
global newT_num
self.value = value
self.name = 'T' + str(newT_num)
newT_num += 1
def __str__(self):
return self.name
def __repr__(self):
return '\nname:{:10}value:{:5}'.format(self.name, self.... |
"""
Notification Controller Node
"""
from udi_interface import Node,LOGGER,Custom,LOG_HANDLER
from nodes import *
import logging
from node_funcs import *
from PolyglotREST import polyglotRESTServer,polyglotSession
from copy import deepcopy
import re
import time
import fnmatch
import os
class Controll... | """
Notification Controller Node
"""
from udi_interface import Node,LOGGER,Custom,LOG_HANDLER
from nodes import *
import logging
from node_funcs import *
from PolyglotREST import polyglotRESTServer,polyglotSession
from copy import deepcopy
import re
import time
import fnmatch
import os
class Controll... |
from typing import Dict, Any, List, Union
import os
import csv
from pathlib import Path
from loguru import logger
from parqser.saver import BaseSaver
class CSVSaver(BaseSaver):
def __init__(self, path: str, columns: List[str] = [], sep=','):
self._check_dir_exists(path)
self.path = path
se... | from typing import Dict, Any, List, Union
import os
import csv
from pathlib import Path
from loguru import logger
from parqser.saver import BaseSaver
class CSVSaver(BaseSaver):
def __init__(self, path: str, columns: List[str] = [], sep=','):
self._check_dir_exists(path)
self.path = path
se... |
# Standard
import json
import re
import os.path
import configparser
# Third party
import requests
import paho.mqtt.client as mqtt
from neopixel import Adafruit_NeoPixel as Matrix, Color
# Local
from topics import Topic
from leds import leds
from colors import colors
currentDirectory = os.path.dirname(__file__)
configP... | # Standard
import json
import re
import os.path
import configparser
# Third party
import requests
import paho.mqtt.client as mqtt
from neopixel import Adafruit_NeoPixel as Matrix, Color
# Local
from topics import Topic
from leds import leds
from colors import colors
currentDirectory = os.path.dirname(__file__)
configP... |
from django.apps import apps
from bsm_config.settings import site_setting, WEBSITE_CONFIG
from bsm_config.site_setting import default_get_field, default_get_schemas
def get_settins():
view_keys = []
if WEBSITE_CONFIG:
for section in WEBSITE_CONFIG:
for field in section['fields']:
... | from django.apps import apps
from bsm_config.settings import site_setting, WEBSITE_CONFIG
from bsm_config.site_setting import default_get_field, default_get_schemas
def get_settins():
view_keys = []
if WEBSITE_CONFIG:
for section in WEBSITE_CONFIG:
for field in section['fields']:
... |
import json
import warnings
import logging
import os
from types import LambdaType
from typing import Any, Dict, List, Optional, Text, Tuple
import numpy as np
import time
from rasa.core import jobs
from rasa.core.actions.action import Action
from rasa.core.actions.action import ACTION_LISTEN_NAME, ActionExecutionReje... | import json
import warnings
import logging
import os
from types import LambdaType
from typing import Any, Dict, List, Optional, Text, Tuple
import numpy as np
import time
from rasa.core import jobs
from rasa.core.actions.action import Action
from rasa.core.actions.action import ACTION_LISTEN_NAME, ActionExecutionReje... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import os
import logging
import sys
import pytest
import time
from os import path
import ly_test_tools.envir... | """
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import os
import logging
import sys
import pytest
import time
from os import path
import ly_test_tools.envir... |
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# ReFrame Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
import inspect
import traceback
import reframe.core.runtime as rt
import reframe.core.exceptions as errors
import reframe.uti... | # Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# ReFrame Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
import inspect
import traceback
import reframe.core.runtime as rt
import reframe.core.exceptions as errors
import reframe.uti... |
from core.templatetags import register
from django.utils.safestring import mark_safe
from html import escape
import re
def get_extension_icon(filename):
extension_icons = {
"docx": "doc",
"doc": "doc",
"odt": "doc",
"txt": "doc",
"pdf": "pdf",
"png": "img",
... | from core.templatetags import register
from django.utils.safestring import mark_safe
from html import escape
import re
def get_extension_icon(filename):
extension_icons = {
"docx": "doc",
"doc": "doc",
"odt": "doc",
"txt": "doc",
"pdf": "pdf",
"png": "img",
... |
#!/usr/bin/env python
## -*- coding: utf-8 -*-
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 ... | #!/usr/bin/env python
## -*- coding: utf-8 -*-
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 ... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
""" Userbot module for having some fun with people. """
from asyncio import sleep
from random import choice, getrandbits... | # Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
""" Userbot module for having some fun with people. """
from asyncio import sleep
from random import choice, getrandbits... |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... |
# import Python Modules /dependencies
import time
import torch
import argparse
import matplotlib
import numpy as np
import torch.nn.functional as F
import matplotlib.pyplot as plt
from PIL import Image
from torch import nn, optim
from collections import OrderedDict
from workspace_utils import active_session
from torch... | # import Python Modules /dependencies
import time
import torch
import argparse
import matplotlib
import numpy as np
import torch.nn.functional as F
import matplotlib.pyplot as plt
from PIL import Image
from torch import nn, optim
from collections import OrderedDict
from workspace_utils import active_session
from torch... |
from partools.utils import g
# Mandatory inputs---------------------------------------------------
# Either CNX_INFO or DB have to be input. If both are filled, CNX_INFO is taken
CNX_INFO = '' # Connection string: 'USER/PWD@HOST:PORT/SERVICE_NAME'
DB = '' # DB name from partools.conf.CONF_ORACLE
QUERY_IN = '' # Mu... | from partools.utils import g
# Mandatory inputs---------------------------------------------------
# Either CNX_INFO or DB have to be input. If both are filled, CNX_INFO is taken
CNX_INFO = '' # Connection string: 'USER/PWD@HOST:PORT/SERVICE_NAME'
DB = '' # DB name from partools.conf.CONF_ORACLE
QUERY_IN = '' # Mu... |
#-*- coding: utf-8 -*-
# if want to test can use socat to create virtual serial:
# ex: socat -d -d -v pty,rawer,echo=0,link=./reader pty,rawer,echo=0,link=./writer
# 2019/04/09 11:16:09 socat[22919] N PTY is /dev/ttys000
# 2019/04/09 11:16:09 socat[22919] N PTY is /dev/ttys006
# 2019/04/09 11:16:09 socat[2... | #-*- coding: utf-8 -*-
# if want to test can use socat to create virtual serial:
# ex: socat -d -d -v pty,rawer,echo=0,link=./reader pty,rawer,echo=0,link=./writer
# 2019/04/09 11:16:09 socat[22919] N PTY is /dev/ttys000
# 2019/04/09 11:16:09 socat[22919] N PTY is /dev/ttys006
# 2019/04/09 11:16:09 socat[2... |
from sklearn.metrics import average_precision_score, log_loss
from sklearn.model_selection import train_test_split
import dask.dataframe as dd
import os, sys
import time
import RootPath
from Scripts.utilities import start_cluster
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.ker... | from sklearn.metrics import average_precision_score, log_loss
from sklearn.model_selection import train_test_split
import dask.dataframe as dd
import os, sys
import time
import RootPath
from Scripts.utilities import start_cluster
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.ker... |
# coding=utf-8
# Copyright 2019 HuggingFace Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | # coding=utf-8
# Copyright 2019 HuggingFace Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
"""
Analyze Dig's results
"""
import argparse
import pdb
import random
import shutil
import sys
import time
from collections import Counter, defaultdict, namedtuple
from pathlib import Path
from statistics import median_low
import helpers.vcommon as CM
import infer.inv
import settings
from helpers.miscs import Miscs
... | """
Analyze Dig's results
"""
import argparse
import pdb
import random
import shutil
import sys
import time
from collections import Counter, defaultdict, namedtuple
from pathlib import Path
from statistics import median_low
import helpers.vcommon as CM
import infer.inv
import settings
from helpers.miscs import Miscs
... |
"""
粮票获取
@create:2021/04/24
@filename:ykt_score.py
@author:ReaJason
@email_addr:reajason@163.com
@blog_website:https://reajason.top
@last_modify:2021/04/26
"""
import requests
def get_task_list(token,log):
data = f"token={token}" \
"&method=makeScoreTask" \
f"¶m=%7B%22token%22%3A%22{toke... | """
粮票获取
@create:2021/04/24
@filename:ykt_score.py
@author:ReaJason
@email_addr:reajason@163.com
@blog_website:https://reajason.top
@last_modify:2021/04/26
"""
import requests
def get_task_list(token,log):
data = f"token={token}" \
"&method=makeScoreTask" \
f"¶m=%7B%22token%22%3A%22{toke... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
import os
from dataclasses import dataclass
from typing import Iterable
from pants.backend.helm.resolve import artifacts
from pants.back... | # Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
import os
from dataclasses import dataclass
from typing import Iterable
from pants.backend.helm.resolve import artifacts
from pants.back... |
"""
-*- coding: utf-8 -*-
Written by: sme30393
Date: 11/12/2020
"""
import numpy as np
import os
import scipy.ndimage as ndimage
from collections import Counter
from typing import List
from solutions.config import Config
from solutions.year_2020.utils.file_manager import read_txt_file
SEAT_TYPE = {
".": "floor",... | """
-*- coding: utf-8 -*-
Written by: sme30393
Date: 11/12/2020
"""
import numpy as np
import os
import scipy.ndimage as ndimage
from collections import Counter
from typing import List
from solutions.config import Config
from solutions.year_2020.utils.file_manager import read_txt_file
SEAT_TYPE = {
".": "floor",... |
from __future__ import annotations
from typing import List, Optional
from .. import ComplexCommand, command, subcommand, WorldMode
from amulet.api import world_loader
from amulet.api import version_loader, format_loader
from amulet.api.errors import (
FormatError,
FormatLoaderInvalidFormat,
FormatLoader... | from __future__ import annotations
from typing import List, Optional
from .. import ComplexCommand, command, subcommand, WorldMode
from amulet.api import world_loader
from amulet.api import version_loader, format_loader
from amulet.api.errors import (
FormatError,
FormatLoaderInvalidFormat,
FormatLoader... |
import os
import re
import logging
import sys
from mkdocs.plugins import BasePlugin
from mkdocs.config import config_options
from mkdocs.structure.files import File
from mkdocs.structure.pages import Page
from mkdocs.utils import write_file, copy_file, get_relative_url, warning_filter
from mkdocs.exceptions import Plu... | import os
import re
import logging
import sys
from mkdocs.plugins import BasePlugin
from mkdocs.config import config_options
from mkdocs.structure.files import File
from mkdocs.structure.pages import Page
from mkdocs.utils import write_file, copy_file, get_relative_url, warning_filter
from mkdocs.exceptions import Plu... |
import pytest
from dataclasses import dataclass
from ansys.grantami.bomanalytics_openapi import models
from ansys.grantami.bomanalytics._item_definitions import ReferenceType
from ansys.grantami.bomanalytics._item_results import ImpactedSubstance, ItemResultFactory
from .common import INDICATORS
@dataclass
class Reco... | import pytest
from dataclasses import dataclass
from ansys.grantami.bomanalytics_openapi import models
from ansys.grantami.bomanalytics._item_definitions import ReferenceType
from ansys.grantami.bomanalytics._item_results import ImpactedSubstance, ItemResultFactory
from .common import INDICATORS
@dataclass
class Reco... |
import pandas as pd
# typing
from typing import Dict, List, Union
# 🤗 Transformers
from transformers import PreTrainedTokenizer
# 🤗 Datasets
from datasets import DatasetDict, Dataset as hfDataset
# torch
from torch.utils.data import Dataset, DataLoader
import time
import numpy as np
from thesis.datasets.s2orc.m... | import pandas as pd
# typing
from typing import Dict, List, Union
# 🤗 Transformers
from transformers import PreTrainedTokenizer
# 🤗 Datasets
from datasets import DatasetDict, Dataset as hfDataset
# torch
from torch.utils.data import Dataset, DataLoader
import time
import numpy as np
from thesis.datasets.s2orc.m... |
from pyrogram import Client, filters
from utils import temp
from pyrogram.types import Message
from database.users_chats_db import db
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from info import SUPPORT_CHAT
async def banned_users(_, client, message: Message):
return (
message.from... | from pyrogram import Client, filters
from utils import temp
from pyrogram.types import Message
from database.users_chats_db import db
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from info import SUPPORT_CHAT
async def banned_users(_, client, message: Message):
return (
message.from... |
import re
from pprint import pprint
from more_itertools import split_at, split_before
from drafting.geometry import Point, Line, Rect
from drafting.sh.context import SHLookup, SHContext
SH_UNARY_SUFFIX_FUNCS = {
"~": "reverse",
"¶": "to_pen",
}
SH_UNARY_TO_STRING = {
"⊢": "w",
"⊣": "e",
"⊤": "n",... | import re
from pprint import pprint
from more_itertools import split_at, split_before
from drafting.geometry import Point, Line, Rect
from drafting.sh.context import SHLookup, SHContext
SH_UNARY_SUFFIX_FUNCS = {
"~": "reverse",
"¶": "to_pen",
}
SH_UNARY_TO_STRING = {
"⊢": "w",
"⊣": "e",
"⊤": "n",... |
import requests
from scapy.all import *
from ip2geotools.databases.noncommercial import DbIpCity
def pc(packet):
if packet.proto == 17:
udp = packet.payload
while True:
x = sniff(filter="udp and port 6672", prn=pc, store=1, count=1)# GTA V Online UDP default Port is 6672
y = x[0][IP].src
z = x[0][IP].... | import requests
from scapy.all import *
from ip2geotools.databases.noncommercial import DbIpCity
def pc(packet):
if packet.proto == 17:
udp = packet.payload
while True:
x = sniff(filter="udp and port 6672", prn=pc, store=1, count=1)# GTA V Online UDP default Port is 6672
y = x[0][IP].src
z = x[0][IP].... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... | # -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
import logging
import os
import random
import numpy as np
import pytorch_lightning as pl
import torch
from transformers import (
AdamW,
AutoConfig,
AutoModel,
AutoModelForQuestionAnswering,
AutoModelForSequenceClassification,
AutoModelWithLMHead,
AutoTokenizer,
)
from transformers.modeling... | import logging
import os
import random
import numpy as np
import pytorch_lightning as pl
import torch
from transformers import (
AdamW,
AutoConfig,
AutoModel,
AutoModelForQuestionAnswering,
AutoModelForSequenceClassification,
AutoModelWithLMHead,
AutoTokenizer,
)
from transformers.modeling... |
import torch
import torch.nn as nn
from tqdm import tqdm
import json
import os
import gc
from torch.utils.data import DataLoader
import argparse
from src.utils import setup_seed, multi_acc
from src.pixel_classifier import load_ensemble, compute_iou, predict_labels, save_predictions, save_predictions, pixel_classifie... | import torch
import torch.nn as nn
from tqdm import tqdm
import json
import os
import gc
from torch.utils.data import DataLoader
import argparse
from src.utils import setup_seed, multi_acc
from src.pixel_classifier import load_ensemble, compute_iou, predict_labels, save_predictions, save_predictions, pixel_classifie... |
def aumentar(num=0, taxa=10, formata=False):
s = num + ((num * taxa) / 100)
return s if formata is False else formatar(s)
def diminuir(num=0, taxa=10, formata=False):
s = num - ((num * taxa) / 100)
return s if formata is False else formatar(s)
def metade(num=0, formata=False):
s = num / 2
re... | def aumentar(num=0, taxa=10, formata=False):
s = num + ((num * taxa) / 100)
return s if formata is False else formatar(s)
def diminuir(num=0, taxa=10, formata=False):
s = num - ((num * taxa) / 100)
return s if formata is False else formatar(s)
def metade(num=0, formata=False):
s = num / 2
re... |
from airflow import settings
from airflow.providers.ssh.hooks.ssh import SSHHook
from airflow.models.connection import Connection
from airflow.providers.hashicorp.hooks.vault import VaultHook
def create_temp_connection(rrid, params):
host = params.get('host')
port = params.get('port', 2222)
user = params.... | from airflow import settings
from airflow.providers.ssh.hooks.ssh import SSHHook
from airflow.models.connection import Connection
from airflow.providers.hashicorp.hooks.vault import VaultHook
def create_temp_connection(rrid, params):
host = params.get('host')
port = params.get('port', 2222)
user = params.... |
########################################
# Changes compared to 20_5channel.py
# 01.
# CNN structure
########################################
import cv2
import matplotlib.pyplot as plt
import sys
import numpy as np
#import pandas as pd
import datetime
import json
from array import *
import os
import math
from random... | ########################################
# Changes compared to 20_5channel.py
# 01.
# CNN structure
########################################
import cv2
import matplotlib.pyplot as plt
import sys
import numpy as np
#import pandas as pd
import datetime
import json
from array import *
import os
import math
from random... |
#!/usr/bin/env python3
# Copyright (c) 2017-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoin-cli"""
from decimal import Decimal
import re
from test_framework.blocktools import COINB... | #!/usr/bin/env python3
# Copyright (c) 2017-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoin-cli"""
from decimal import Decimal
import re
from test_framework.blocktools import COINB... |
# Copyright New York University and the TUF contributors
# SPDX-License-Identifier: MIT OR Apache-2.0
"""TUF role metadata model.
This module provides container classes for TUF role metadata, including methods
to read and write from and to file, perform TUF-compliant metadata updates, and
create and verify signatures... | # Copyright New York University and the TUF contributors
# SPDX-License-Identifier: MIT OR Apache-2.0
"""TUF role metadata model.
This module provides container classes for TUF role metadata, including methods
to read and write from and to file, perform TUF-compliant metadata updates, and
create and verify signatures... |
import logging
from aiogram import types, Dispatcher
from aiogram.dispatcher import FSMContext
from app.const import Buttons, MessageParts
from app.general_functions import (white_list, get_providers_list,
create_iter_keyboard)
from app.settings import cur, connect
from app.states i... | import logging
from aiogram import types, Dispatcher
from aiogram.dispatcher import FSMContext
from app.const import Buttons, MessageParts
from app.general_functions import (white_list, get_providers_list,
create_iter_keyboard)
from app.settings import cur, connect
from app.states i... |
# -*- coding: utf-8 -*-
#███╗ ███╗ █████╗ ███╗ ██╗██╗ ██████╗ ██████╗ ███╗ ███╗██╗ ██████╗
#████╗ ████║██╔══██╗████╗ ██║██║██╔════╝██╔═══██╗████╗ ████║██║██╔═══██╗
#██╔████╔██║███████║██╔██╗ ██║██║██║ ██║ ██║██╔████╔██║██║██║ ██║
#██║╚██╔╝██║██╔══██║██║╚██╗██║██║██║ ██║ ██║██║╚██╔╝██║██║██║ ██║
#... | # -*- coding: utf-8 -*-
#███╗ ███╗ █████╗ ███╗ ██╗██╗ ██████╗ ██████╗ ███╗ ███╗██╗ ██████╗
#████╗ ████║██╔══██╗████╗ ██║██║██╔════╝██╔═══██╗████╗ ████║██║██╔═══██╗
#██╔████╔██║███████║██╔██╗ ██║██║██║ ██║ ██║██╔████╔██║██║██║ ██║
#██║╚██╔╝██║██╔══██║██║╚██╗██║██║██║ ██║ ██║██║╚██╔╝██║██║██║ ██║
#... |
"""
This module contains the configuration class
"""
import logging
import warnings
from copy import deepcopy
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
from freqtrade import OperationalException, constants
from freqtrade.configuration.check_exchange import check_exchange
from freq... | """
This module contains the configuration class
"""
import logging
import warnings
from copy import deepcopy
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
from freqtrade import OperationalException, constants
from freqtrade.configuration.check_exchange import check_exchange
from freq... |
import discord
from discord.ext import commands
import aiohttp
import yaml
import re
import logging
TIMINGS_CHECK = None
YAML_ERROR = None
with open("cogs/timings_check.yml", 'r', encoding="utf8") as stream:
try:
TIMINGS_CHECK = yaml.safe_load(stream)
except yaml.YAMLError as exc:
logging.info(... | import discord
from discord.ext import commands
import aiohttp
import yaml
import re
import logging
TIMINGS_CHECK = None
YAML_ERROR = None
with open("cogs/timings_check.yml", 'r', encoding="utf8") as stream:
try:
TIMINGS_CHECK = yaml.safe_load(stream)
except yaml.YAMLError as exc:
logging.info(... |
from bs4 import BeautifulSoup
import pandas as pd
import requests
state_links = pd.read_csv("statewise_links.csv")
districtwise_links = pd.DataFrame(columns=['state', 'district', 'link'])
for index, row in state_links.iterrows():
print(f"Processing state #{index} {row["state"]} at link {row["link"]}")
webpage... | from bs4 import BeautifulSoup
import pandas as pd
import requests
state_links = pd.read_csv("statewise_links.csv")
districtwise_links = pd.DataFrame(columns=['state', 'district', 'link'])
for index, row in state_links.iterrows():
print(f"Processing state #{index} {row['state']} at link {row['link']}")
webpage... |
#!/usr/bin/env python
## -*- coding: utf-8 -*-
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 ... | #!/usr/bin/env python
## -*- coding: utf-8 -*-
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 ... |
import inspect
import io
import itertools
import os
import sys
import typing
import typing as t
from gettext import gettext as _
from ._compat import isatty
from ._compat import strip_ansi
from ._compat import WIN
from .exceptions import Abort
from .exceptions import UsageError
from .globals import resolve_color_defau... | import inspect
import io
import itertools
import os
import sys
import typing
import typing as t
from gettext import gettext as _
from ._compat import isatty
from ._compat import strip_ansi
from ._compat import WIN
from .exceptions import Abort
from .exceptions import UsageError
from .globals import resolve_color_defau... |
import asyncio
import logging
import time
import sqlalchemy
from .schema import Base, Fingerprint, Song
def database_obj_to_py(obj, fingerprints_in_song=False):
"""
Recursively convert Fingerprint and Song sqlalchemy objects to native
Python types (lists and dicts).
Args:
obj (database.sche... | import asyncio
import logging
import time
import sqlalchemy
from .schema import Base, Fingerprint, Song
def database_obj_to_py(obj, fingerprints_in_song=False):
"""
Recursively convert Fingerprint and Song sqlalchemy objects to native
Python types (lists and dicts).
Args:
obj (database.sche... |
import gc
from logging import warning
from time import perf_counter
from typing import Callable, List, Optional, Tuple, Union, Set, Dict, Any
import numpy as np
import pandas as pd
from numpy import ndarray
from scipy.sparse import coo_matrix, spmatrix, csc_matrix, csr_matrix
from .coreConfig import EXTRA_L... | import gc
from logging import warning
from time import perf_counter
from typing import Callable, List, Optional, Tuple, Union, Set, Dict, Any
import numpy as np
import pandas as pd
from numpy import ndarray
from scipy.sparse import coo_matrix, spmatrix, csc_matrix, csr_matrix
from .coreConfig import EXTRA_L... |
'''
MIT License
Copyright (c) 2017 Kyb3r
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distrib... | '''
MIT License
Copyright (c) 2017 Kyb3r
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distrib... |
import logging
import os.path
import sys
from robocorp_code.protocols import (
LocalRobotMetadataInfoDict,
WorkspaceInfoDict,
ActionResult,
)
from typing import List
import time
from robocorp_code_tests.protocols import IRobocorpLanguageServerClient
import py
from robocorp_ls_core.unittest_tools.cases_fixtu... | import logging
import os.path
import sys
from robocorp_code.protocols import (
LocalRobotMetadataInfoDict,
WorkspaceInfoDict,
ActionResult,
)
from typing import List
import time
from robocorp_code_tests.protocols import IRobocorpLanguageServerClient
import py
from robocorp_ls_core.unittest_tools.cases_fixtu... |
from ..Constants.constants import *
class LexerOutputGenerator:
@staticmethod
def generate_symbol_table(token_lines: dict):
symbol_table = {}
symbol_table_set = set()
iterator = 1
for word in keywords:
symbol_table_set.add(word)
symbol_table[iterator] = ... | from ..Constants.constants import *
class LexerOutputGenerator:
@staticmethod
def generate_symbol_table(token_lines: dict):
symbol_table = {}
symbol_table_set = set()
iterator = 1
for word in keywords:
symbol_table_set.add(word)
symbol_table[iterator] = ... |
import sys
import xlrd
import yaml
import re
import unicodedata
table_path = "_data/tool_and_resource_list.xlsx"
output_path = "_data/tool_and_resource_list.yml"
main_dict_key = "Tools"
allowed_tags_yaml = "_data/tags.yml"
allowed_registries = ['biotools', 'fairsharing']
print(f"----> Converting table {table_path} to... | import sys
import xlrd
import yaml
import re
import unicodedata
table_path = "_data/tool_and_resource_list.xlsx"
output_path = "_data/tool_and_resource_list.yml"
main_dict_key = "Tools"
allowed_tags_yaml = "_data/tags.yml"
allowed_registries = ['biotools', 'fairsharing']
print(f"----> Converting table {table_path} to... |
import asyncio
import json
import os
import time
from telethon.tl.types import DocumentAttributeAudio
from youtube_dl import YoutubeDL
from youtube_dl.utils import (ContentTooShortError, DownloadError,
ExtractorError, GeoRestrictedError,
MaxDownloadsReached, ... | import asyncio
import json
import os
import time
from telethon.tl.types import DocumentAttributeAudio
from youtube_dl import YoutubeDL
from youtube_dl.utils import (ContentTooShortError, DownloadError,
ExtractorError, GeoRestrictedError,
MaxDownloadsReached, ... |
from functools import partial
import os
from matplotlib.backends.backend_pdf import PdfPages
import pandas as pd
def map_lowest(func, dct):
return {
k: map_lowest(func, v) if isinstance(v, dict) else func(v)
for k, v in dct.items()
}
def swaplevel(dct_of_dct):
keys = next(iter(dct_of_dc... | from functools import partial
import os
from matplotlib.backends.backend_pdf import PdfPages
import pandas as pd
def map_lowest(func, dct):
return {
k: map_lowest(func, v) if isinstance(v, dict) else func(v)
for k, v in dct.items()
}
def swaplevel(dct_of_dct):
keys = next(iter(dct_of_dc... |
"A `Callback` that saves tracked metrics into a persistent file."
# Contribution from devforfu: https://nbviewer.jupyter.org/gist/devforfu/ea0b3fcfe194dad323c3762492b05cae
import pandas as pd
from fastai.basic_train import Learner, LearnerCallback
from fastai_sparse.core import Any
__all__ = ['CSVLoggerIouByClass']
... | "A `Callback` that saves tracked metrics into a persistent file."
# Contribution from devforfu: https://nbviewer.jupyter.org/gist/devforfu/ea0b3fcfe194dad323c3762492b05cae
import pandas as pd
from fastai.basic_train import Learner, LearnerCallback
from fastai_sparse.core import Any
__all__ = ['CSVLoggerIouByClass']
... |
import os
# Project Name
PROJECT_NAME = os.environ.get('PROJECT')
SOURCE_PATH = os.environ.get('SOURCE_PATH')
DESTINATION_PATH = os.environ.get('DESTINATION_PATH')
src_path = SOURCE_PATH.split('//')
SOURCE_BUCKET_NAME = src_path[1]
dest_path = DESTINATION_PATH.split('//')
DESTINATION_BUCKET_NAME = dest_path[1]
KEY... | import os
# Project Name
PROJECT_NAME = os.environ.get('PROJECT')
SOURCE_PATH = os.environ.get('SOURCE_PATH')
DESTINATION_PATH = os.environ.get('DESTINATION_PATH')
src_path = SOURCE_PATH.split('//')
SOURCE_BUCKET_NAME = src_path[1]
dest_path = DESTINATION_PATH.split('//')
DESTINATION_BUCKET_NAME = dest_path[1]
KEY... |
'''
Topic : Algorithms
Subtopic : StairCase
Language : Python
Problem Statement : Write a program that prints a staircase of size 'n'.
Url : https://www.hackerrank.com/challenges/staircase/problem
'''
# Complete the staircase function below.
def staircase(n):
for i in range(1, n + 1):
p... | '''
Topic : Algorithms
Subtopic : StairCase
Language : Python
Problem Statement : Write a program that prints a staircase of size 'n'.
Url : https://www.hackerrank.com/challenges/staircase/problem
'''
# Complete the staircase function below.
def staircase(n):
for i in range(1, n + 1):
p... |
"""
An object-oriented plotting library.
A procedural interface is provided by the companion pyplot module,
which may be imported directly, e.g.::
import matplotlib.pyplot as plt
or using ipython::
ipython
at your terminal, followed by::
In [1]: %matplotlib
In [2]: import matplotlib... | """
An object-oriented plotting library.
A procedural interface is provided by the companion pyplot module,
which may be imported directly, e.g.::
import matplotlib.pyplot as plt
or using ipython::
ipython
at your terminal, followed by::
In [1]: %matplotlib
In [2]: import matplotlib... |
from colorama import Fore, Style, init; init()
from threading import Thread, Lock
import os, requests, time
lock = Lock()
def Printer(color, past, text, proxy):
lock.acquire()
print(f'{Fore.LIGHTWHITE_EX}[{color}{past}{Fore.LIGHTWHITE_EX}] {text} ~ {proxy.split('://')[1]}.')
lock.release()
class MrHook:
... | from colorama import Fore, Style, init; init()
from threading import Thread, Lock
import os, requests, time
lock = Lock()
def Printer(color, past, text, proxy):
lock.acquire()
print(f'{Fore.LIGHTWHITE_EX}[{color}{past}{Fore.LIGHTWHITE_EX}] {text} ~ {proxy.split("://")[1]}.')
lock.release()
class MrHook:
... |
from sstcam_sandbox import get_astri_2019
from os.path import join, abspath, dirname
import pandas as pd
import subprocess
DIR = abspath(dirname(__file__))
DATA = get_astri_2019("d2019-04-23_nudges")
def main():
spe_config = join(DIR, "spe_config.yml")
df_spe = pd.read_csv(join(DIR, "spe_runlist.txt"), sep=... | from sstcam_sandbox import get_astri_2019
from os.path import join, abspath, dirname
import pandas as pd
import subprocess
DIR = abspath(dirname(__file__))
DATA = get_astri_2019("d2019-04-23_nudges")
def main():
spe_config = join(DIR, "spe_config.yml")
df_spe = pd.read_csv(join(DIR, "spe_runlist.txt"), sep=... |
# -*- coding: utf8 -*-
import requests
import json
def send(content, config):
print("企业微信应用消息推送开始")
qywx_corpid = config.get('qywx_corpid')
qywx_agentid = config.get('qywx_agentid')
qywx_corpsecret = config.get('qywx_corpsecret')
qywx_touser = config.get('qywx_touser')
res = requests.get(
... | # -*- coding: utf8 -*-
import requests
import json
def send(content, config):
print("企业微信应用消息推送开始")
qywx_corpid = config.get('qywx_corpid')
qywx_agentid = config.get('qywx_agentid')
qywx_corpsecret = config.get('qywx_corpsecret')
qywx_touser = config.get('qywx_touser')
res = requests.get(
... |
from __future__ import print_function
import base64
import functools
import os
import pickle
import re
import requests
import shutil
import socket
import sys
import time
from datetime import datetime
from datetime import timezone
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from ... | from __future__ import print_function
import base64
import functools
import os
import pickle
import re
import requests
import shutil
import socket
import sys
import time
from datetime import datetime
from datetime import timezone
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from ... |
# Standard
import discord
from discord.commands import slash_command, Option
from discord.ext import commands
from difflib import get_close_matches
from datetime import datetime, timedelta
# Local
from utils.json_loader import *
from utils.view import *
from utils.cache import *
from utils.emoji import *
from utils.au... | # Standard
import discord
from discord.commands import slash_command, Option
from discord.ext import commands
from difflib import get_close_matches
from datetime import datetime, timedelta
# Local
from utils.json_loader import *
from utils.view import *
from utils.cache import *
from utils.emoji import *
from utils.au... |
#!/usr/bin/env python
import csv
from pathlib import Path
from ignite.engine import Events, create_supervised_trainer, create_supervised_evaluator
from ignite.metrics import RunningAverage
from ignite.handlers import EarlyStopping, ModelCheckpoint
class YelpTrainer(object):
def __init__(self, model_bundle, data_bu... | #!/usr/bin/env python
import csv
from pathlib import Path
from ignite.engine import Events, create_supervised_trainer, create_supervised_evaluator
from ignite.metrics import RunningAverage
from ignite.handlers import EarlyStopping, ModelCheckpoint
class YelpTrainer(object):
def __init__(self, model_bundle, data_bu... |
import enum
from json.tool import main
import pickle
from tkinter.tix import MAIN
from tokenize import group
import numpy as np
import itertools
import os
import fcntl
import json
from tqdm import tqdm
from transformers import AutoTokenizer
from tokenizers import AddedToken
from .transform_utils import m... | import enum
from json.tool import main
import pickle
from tkinter.tix import MAIN
from tokenize import group
import numpy as np
import itertools
import os
import fcntl
import json
from tqdm import tqdm
from transformers import AutoTokenizer
from tokenizers import AddedToken
from .transform_utils import m... |
import base64
import errno
import http.client
import logging
import os
import stat
import os.path as p
import pprint
import pwd
import re
import shutil
import socket
import subprocess
import time
import traceback
import urllib.parse
import shlex
import urllib3
from cassandra.policies import RoundRobinPolicy
import cas... | import base64
import errno
import http.client
import logging
import os
import stat
import os.path as p
import pprint
import pwd
import re
import shutil
import socket
import subprocess
import time
import traceback
import urllib.parse
import shlex
import urllib3
from cassandra.policies import RoundRobinPolicy
import cas... |
"""Facilities for generating error messages during type checking.
Don't add any non-trivial message construction logic to the type
checker, as it can compromise clarity and make messages less
consistent. Add such logic to this module instead. Literal messages, including those
with format args, should be defined as con... | """Facilities for generating error messages during type checking.
Don't add any non-trivial message construction logic to the type
checker, as it can compromise clarity and make messages less
consistent. Add such logic to this module instead. Literal messages, including those
with format args, should be defined as con... |
import copy
import itertools
from functools import partial
from typing import Iterable, List, Tuple
from isort.format import format_simplified
from . import parse, sorting, wrap
from .comments import add_to_line as with_comments
from .settings import DEFAULT_CONFIG, Config
STATEMENT_DECLERATIONS: Tuple[str, ...] = (... | import copy
import itertools
from functools import partial
from typing import Iterable, List, Tuple
from isort.format import format_simplified
from . import parse, sorting, wrap
from .comments import add_to_line as with_comments
from .settings import DEFAULT_CONFIG, Config
STATEMENT_DECLERATIONS: Tuple[str, ...] = (... |
import os
import sys
import math
import fire
import json
import urllib.request
import urllib.parse
import io
from tqdm import tqdm
from math import floor, log2
from random import random
from shutil import rmtree
from functools import partial
import multiprocessing
from contextlib import contextmanager, ExitStack
impo... | import os
import sys
import math
import fire
import json
import urllib.request
import urllib.parse
import io
from tqdm import tqdm
from math import floor, log2
from random import random
from shutil import rmtree
from functools import partial
import multiprocessing
from contextlib import contextmanager, ExitStack
impo... |
# -*- coding: utf-8 -*-
"""PyDNGConverter Compatibility module.
Handles platform-specific operations.
"""
import asyncio
import logging
import os
import platform
from copy import deepcopy
from enum import Enum, auto
from pathlib import Path
from typing import Union, List, Optional
from pydngconverter import utils
l... | # -*- coding: utf-8 -*-
"""PyDNGConverter Compatibility module.
Handles platform-specific operations.
"""
import asyncio
import logging
import os
import platform
from copy import deepcopy
from enum import Enum, auto
from pathlib import Path
from typing import Union, List, Optional
from pydngconverter import utils
l... |
alien_0 = {'x_position': 0,
'y_position': 25,
'speed': 'medium'
}
print(f"Original position: {alien_0["x_position"]}")
# Move the alien to the right.
# Determine how far to move the alien based on its current speed.
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['spee... | alien_0 = {'x_position': 0,
'y_position': 25,
'speed': 'medium'
}
print(f"Original position: {alien_0['x_position']}")
# Move the alien to the right.
# Determine how far to move the alien based on its current speed.
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['spee... |
import asyncio
import ast
from hfc.fabric import Client
from .interfaces import Initiator, Responder, ErrorCode
from ..transfer import Transfer
class FabricInitializer:
"""This provides the proper fabric client wrapper
"""
def __init__(self, net_profile=None, channel_name=None, cc_name=None, cc_version=N... | import asyncio
import ast
from hfc.fabric import Client
from .interfaces import Initiator, Responder, ErrorCode
from ..transfer import Transfer
class FabricInitializer:
"""This provides the proper fabric client wrapper
"""
def __init__(self, net_profile=None, channel_name=None, cc_name=None, cc_version=N... |
#!/usr/bin/env python
"""
Copyright (c) 2018-2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applica... | #!/usr/bin/env python
"""
Copyright (c) 2018-2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applica... |
#!/usr/bin/env python3
import ctypes.util
import distutils.ccompiler
import os
import platform
import sys
import tempfile
# adapted from https://github.com/tree-sitter/py-tree-sitter
def build(repo_paths, output_path="libjava-tree-sitter"):
if not repo_paths:
raise ValueError("Must provide at least one l... | #!/usr/bin/env python3
import ctypes.util
import distutils.ccompiler
import os
import platform
import sys
import tempfile
# adapted from https://github.com/tree-sitter/py-tree-sitter
def build(repo_paths, output_path="libjava-tree-sitter"):
if not repo_paths:
raise ValueError("Must provide at least one l... |
# =================================================================
#
# Authors: Sander Schaminee <sander.schaminee@geocat.net>
#
# Copyright (c) 2021 GeoCat BV
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to d... | # =================================================================
#
# Authors: Sander Schaminee <sander.schaminee@geocat.net>
#
# Copyright (c) 2021 GeoCat BV
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to d... |
import smtplib
import time
import requests
import schedule
from email.mime.text import MIMEText
from email.header import Header
session = requests.session()
length = 0
data_dict = {
}
# -------------------------------------------------以下内容需要自己填写-------------------------------------------------
# 个人信息区
username = xxxx... | import smtplib
import time
import requests
import schedule
from email.mime.text import MIMEText
from email.header import Header
session = requests.session()
length = 0
data_dict = {
}
# -------------------------------------------------以下内容需要自己填写-------------------------------------------------
# 个人信息区
username = xxxx... |
import json
import os
import re
import packaging
import boto3
import pytest
from test import test_utils
@pytest.mark.integration("dlc_major_version_label")
@pytest.mark.model("N/A")
def test_dlc_major_version_label(image, region):
"""
Test to ensure that all DLC images have the LABEL "dlc_major_version"
... | import json
import os
import re
import packaging
import boto3
import pytest
from test import test_utils
@pytest.mark.integration("dlc_major_version_label")
@pytest.mark.model("N/A")
def test_dlc_major_version_label(image, region):
"""
Test to ensure that all DLC images have the LABEL "dlc_major_version"
... |
aluno = {}
aluno['nome'] = str(input('Nome: '))
aluno['media'] = float(input(f'Média de {aluno['nome']}: '))
if aluno['media'] >= 7:
aluno['situação'] = 'Aprovado'
elif aluno['media'] >=5:
aluno['situação'] = 'Recuperação'
else:
aluno['situação'] = 'Reprovado'
print('-=' * 20)
for chave, valor in aluno.item... | aluno = {}
aluno['nome'] = str(input('Nome: '))
aluno['media'] = float(input(f'Média de {aluno["nome"]}: '))
if aluno['media'] >= 7:
aluno['situação'] = 'Aprovado'
elif aluno['media'] >=5:
aluno['situação'] = 'Recuperação'
else:
aluno['situação'] = 'Reprovado'
print('-=' * 20)
for chave, valor in aluno.item... |
from datetime import datetime
from typing import Optional, Sequence, Dict
from enum import Enum
import pytz
from vnpy.event import EventEngine
from vnpy.trader.gateway import BaseGateway
from vnpy.trader.constant import (
Exchange,
Product,
Offset,
OrderType,
Direction,
Status
)
from vnpy.trade... | from datetime import datetime
from typing import Optional, Sequence, Dict
from enum import Enum
import pytz
from vnpy.event import EventEngine
from vnpy.trader.gateway import BaseGateway
from vnpy.trader.constant import (
Exchange,
Product,
Offset,
OrderType,
Direction,
Status
)
from vnpy.trade... |
import json
import logging
import uuid
import os
from datetime import timezone, datetime
import boto3
from poe_character_exporter.character import get_character, format_item
logger = logging.getLogger(__name__)
if os.environ.get("LOG_LEVEL"):
logger.setLevel(os.environ["LOG_LEVEL"])
else:
logger.setLevel("I... | import json
import logging
import uuid
import os
from datetime import timezone, datetime
import boto3
from poe_character_exporter.character import get_character, format_item
logger = logging.getLogger(__name__)
if os.environ.get("LOG_LEVEL"):
logger.setLevel(os.environ["LOG_LEVEL"])
else:
logger.setLevel("I... |
import logging
from datetime import datetime, timedelta
from typing import List
from discord import Colour, Member, Message, Object, TextChannel
from discord.ext.commands import Bot
from bot import rules
from bot.cogs.moderation import Moderation
from bot.cogs.modlog import ModLog
from bot.constants import (
Anti... | import logging
from datetime import datetime, timedelta
from typing import List
from discord import Colour, Member, Message, Object, TextChannel
from discord.ext.commands import Bot
from bot import rules
from bot.cogs.moderation import Moderation
from bot.cogs.modlog import ModLog
from bot.constants import (
Anti... |
# -*- coding: utf-8 -*-
"""
pybit
------------------------
pybit is a lightweight and high-performance API connector for the
RESTful and WebSocket APIs of the Bybit exchange.
Documentation can be found at
https://github.com/verata-veritatis/pybit
:copyright: (c) 2020-2021 verata-veritatis
:license: MIT License
"""... | # -*- coding: utf-8 -*-
"""
pybit
------------------------
pybit is a lightweight and high-performance API connector for the
RESTful and WebSocket APIs of the Bybit exchange.
Documentation can be found at
https://github.com/verata-veritatis/pybit
:copyright: (c) 2020-2021 verata-veritatis
:license: MIT License
"""... |
class PhotoAlbum:
def __init__(self, pages: int):
self.pages = pages
self.photos: list = [[] for _ in range(pages)]
@classmethod
def from_photos_count(cls, photos_count: int):
pages = photos_count // 4
return cls(pages)
def free_slots(self):
return [page for pag... | class PhotoAlbum:
def __init__(self, pages: int):
self.pages = pages
self.photos: list = [[] for _ in range(pages)]
@classmethod
def from_photos_count(cls, photos_count: int):
pages = photos_count // 4
return cls(pages)
def free_slots(self):
return [page for pag... |
# coding=utf-8
# Copyright 2020 Microsoft and the Hugging Face Inc. 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 require... | # coding=utf-8
# Copyright 2020 Microsoft and the Hugging Face Inc. 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 require... |
import discord
from discord.ext import commands
from PIL import Image, ImageFont, ImageFilter, ImageDraw
from io import BytesIO
import os
def get_invite_by_code(invites, code):
for i in invites:
if i.code == code:
return i
class InviteTrackingSystem(commands.Cog):
def __init_... | import discord
from discord.ext import commands
from PIL import Image, ImageFont, ImageFilter, ImageDraw
from io import BytesIO
import os
def get_invite_by_code(invites, code):
for i in invites:
if i.code == code:
return i
class InviteTrackingSystem(commands.Cog):
def __init_... |
"""This module is to build functions that check if a record already existed in the database"""
from src_files.config import config
def is_exist(crit_name, crit_value, tb_name):
"""
This function check if a record already existed in the database, with single field identifier.
:param crit_name: str, the fi... | """This module is to build functions that check if a record already existed in the database"""
from src_files.config import config
def is_exist(crit_name, crit_value, tb_name):
"""
This function check if a record already existed in the database, with single field identifier.
:param crit_name: str, the fi... |
"""The main module of pyhf."""
import copy
import logging
from . import get_backend, default_backend
from . import exceptions
from . import modifiers
from . import utils
from . import events
from . import probability as prob
from .constraints import gaussian_constraint_combined, poisson_constraint_combined
from .para... | """The main module of pyhf."""
import copy
import logging
from . import get_backend, default_backend
from . import exceptions
from . import modifiers
from . import utils
from . import events
from . import probability as prob
from .constraints import gaussian_constraint_combined, poisson_constraint_combined
from .para... |
import re
import math
import logging
import discord
import datetime
import lavalink
from utils import checks
from discord.ext import commands
time_rx = re.compile('[0-9]+')
url_rx = re.compile('https?:\/\/(?:www\.)?.+')
class Audio(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.audio_... | import re
import math
import logging
import discord
import datetime
import lavalink
from utils import checks
from discord.ext import commands
time_rx = re.compile('[0-9]+')
url_rx = re.compile('https?:\/\/(?:www\.)?.+')
class Audio(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.audio_... |
"""
Test cloudshell_traffic script CLI command.
"""
import os
import shutil
from pathlib import Path
from typing import List
from zipfile import ZipFile
import pytest
import yaml
from _pytest.fixtures import SubRequest
from shellfoundry_traffic.shellfoundry_traffic_cmd import main
from shellfoundry_traffic.script_uti... | """
Test cloudshell_traffic script CLI command.
"""
import os
import shutil
from pathlib import Path
from typing import List
from zipfile import ZipFile
import pytest
import yaml
from _pytest.fixtures import SubRequest
from shellfoundry_traffic.shellfoundry_traffic_cmd import main
from shellfoundry_traffic.script_uti... |
import dataclasses
from datetime import (
datetime,
timedelta,
)
from enum import Enum
import logging
import typing
import requests
from glci import util
import version
from msal import ConfidentialClientApplication
from azure.storage.blob import (
BlobClient,
BlobType,
ContainerSasPermissions,
... | import dataclasses
from datetime import (
datetime,
timedelta,
)
from enum import Enum
import logging
import typing
import requests
from glci import util
import version
from msal import ConfidentialClientApplication
from azure.storage.blob import (
BlobClient,
BlobType,
ContainerSasPermissions,
... |
"""
Build string html elements.
The name of the function coorilates with the name of the html element
such that `element_name(text)`, where `text` is a string, returns
the f-string `f"<element_name>{text}</element_name>"`
EXCEPT FOR `<del></del>`, in which
case the function is called `delete(text)`.
"""
def a(text,... | """
Build string html elements.
The name of the function coorilates with the name of the html element
such that `element_name(text)`, where `text` is a string, returns
the f-string `f"<element_name>{text}</element_name>"`
EXCEPT FOR `<del></del>`, in which
case the function is called `delete(text)`.
"""
def a(text,... |
#
# 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... |
from aiogram import types
from .bestChange_requests import getBestChange
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton
from misc import bot, dp
from config import buttonsBestChange, admins
@dp.message_handler(lambda message: message.text == "BestChange")
asyn... | from aiogram import types
from .bestChange_requests import getBestChange
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton
from misc import bot, dp
from config import buttonsBestChange, admins
@dp.message_handler(lambda message: message.text == "BestChange")
asyn... |
# -*- coding: utf-8 -*-
# Copyright European Organization for Nuclear Research (CERN) since 2012
#
# 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-... | # -*- coding: utf-8 -*-
# Copyright European Organization for Nuclear Research (CERN) since 2012
#
# 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-... |
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class CircularLinkedList:
def __init__(self):
self.head = Node(data='head')
self.head.next = self.head
self.size = 0
def is_empty(self):
... | class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class CircularLinkedList:
def __init__(self):
self.head = Node(data='head')
self.head.next = self.head
self.size = 0
def is_empty(self):
... |
import datetime
import logging
import os
from contextlib import contextmanager
from time import sleep, time
import fsspec
import pandas as pd
from distributed import Client
from distributed.utils import format_bytes
from fsspec.implementations.local import LocalFileSystem
from . import __version__
from .datasets impo... | import datetime
import logging
import os
from contextlib import contextmanager
from time import sleep, time
import fsspec
import pandas as pd
from distributed import Client
from distributed.utils import format_bytes
from fsspec.implementations.local import LocalFileSystem
from . import __version__
from .datasets impo... |
"""
Common solar physics coordinate systems.
This submodule implements various solar physics coordinate frames for use with
the `astropy.coordinates` module.
"""
import numpy as np
import astropy.units as u
from astropy.coordinates import Attribute, ConvertError
from astropy.coordinates.baseframe import BaseCoordinat... | """
Common solar physics coordinate systems.
This submodule implements various solar physics coordinate frames for use with
the `astropy.coordinates` module.
"""
import numpy as np
import astropy.units as u
from astropy.coordinates import Attribute, ConvertError
from astropy.coordinates.baseframe import BaseCoordinat... |
from flask import jsonify, request, abort
from Status import ExecutionQueue
from Data import ExperimentDescriptor
from Scheduler.dispatcher import bp
from Helper import Log
@bp.route('/run', methods=['POST'])
def start():
try:
data = request.json
Log.I("Received execution request")
Log.D(f... | from flask import jsonify, request, abort
from Status import ExecutionQueue
from Data import ExperimentDescriptor
from Scheduler.dispatcher import bp
from Helper import Log
@bp.route('/run', methods=['POST'])
def start():
try:
data = request.json
Log.I("Received execution request")
Log.D(f... |
from gtts import gTTS
from playsound import playsound
from os import remove
from requests import get
def rand_quotes():
res = get("https://zenquotes.io/api/random").json()[0]
return f'{res['q']} by {res['a']}'
def day_quotes():
res = get("https://zenquotes.io/api/today").json()[0]
return f'{res['q']... | from gtts import gTTS
from playsound import playsound
from os import remove
from requests import get
def rand_quotes():
res = get("https://zenquotes.io/api/random").json()[0]
return f'{res["q"]} by {res["a"]}'
def day_quotes():
res = get("https://zenquotes.io/api/today").json()[0]
return f'{res["q"]... |
#!/usr/bin/env python
import sys
import argparse
import nmslib
import json
DEFAULT_HNSW_INDEX_TIME_PARAM = {'M': 20, 'efConstruction': 200, 'post': 0}
DEFAULT_QUERY_QTY=5000
from eval import *
from datasets import *
from data_utils import *
sys.path.append('.')
TestCase = collections.namedtuple('TestCase',
... | #!/usr/bin/env python
import sys
import argparse
import nmslib
import json
DEFAULT_HNSW_INDEX_TIME_PARAM = {'M': 20, 'efConstruction': 200, 'post': 0}
DEFAULT_QUERY_QTY=5000
from eval import *
from datasets import *
from data_utils import *
sys.path.append('.')
TestCase = collections.namedtuple('TestCase',
... |
#!/usr/bin/env python3
"""
Adapted from https://github.com/numba/conda-recipe-cudatoolkit
BSD 2-Clause License
Copyright (c) 2018 Onwards, Quansight, LLC
Copyright (c) 2017, Continuum Analytics, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted... | #!/usr/bin/env python3
"""
Adapted from https://github.com/numba/conda-recipe-cudatoolkit
BSD 2-Clause License
Copyright (c) 2018 Onwards, Quansight, LLC
Copyright (c) 2017, Continuum Analytics, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted... |
"""Make / Download Telegram Sticker Packs without installing Third Party applications
Available Commands:
.kangsticker [Optional Emoji]
.packinfo
.getsticker"""
from telethon import events
from io import BytesIO
from PIL import Image
import asyncio
import datetime
from collections import defaultdict
import math
impo... |
"""Make / Download Telegram Sticker Packs without installing Third Party applications
Available Commands:
.kangsticker [Optional Emoji]
.packinfo
.getsticker"""
from telethon import events
from io import BytesIO
from PIL import Image
import asyncio
import datetime
from collections import defaultdict
import math
impo... |
import os
from spirl.models.closed_loop_spirl_mdl import ClSPiRLMdl
from spirl.components.logger import Logger
from spirl.utils.general_utils import AttrDict
from spirl.configs.default_data_configs.kitchen import data_spec
from spirl.components.evaluator import TopOfNSequenceEvaluator
from spirl.data.kitchen.src.kitch... | import os
from spirl.models.closed_loop_spirl_mdl import ClSPiRLMdl
from spirl.components.logger import Logger
from spirl.utils.general_utils import AttrDict
from spirl.configs.default_data_configs.kitchen import data_spec
from spirl.components.evaluator import TopOfNSequenceEvaluator
from spirl.data.kitchen.src.kitch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.