edited_code stringlengths 17 978k | original_code stringlengths 17 978k |
|---|---|
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from lib.basics import *
from lib.prepping import get_base_data
# Showing the data
def get_country_data_to_show(date_, plots, *countries, length=1000):
"""Returns the data from day date_ for the categories and variants defined
in t... | import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from lib.basics import *
from lib.prepping import get_base_data
# Showing the data
def get_country_data_to_show(date_, plots, *countries, length=1000):
"""Returns the data from day date_ for the categories and variants defined
in t... |
dict = dict()
lista = list()
dict['nome'] = str(input('Nome: '))
dict['media'] = int(input(f'Media de {dict['nome']}: '))
lista.append(dict.copy())
print('-='*30)
print(f' - nome é igual á {dict['nome']}')
print(f' - media é igual á {dict['media']}')
if dict['media'] < 5:
print(' - e a situação é igual a rep... | dict = dict()
lista = list()
dict['nome'] = str(input('Nome: '))
dict['media'] = int(input(f'Media de {dict["nome"]}: '))
lista.append(dict.copy())
print('-='*30)
print(f' - nome é igual á {dict["nome"]}')
print(f' - media é igual á {dict["media"]}')
if dict['media'] < 5:
print(' - e a situação é igual a rep... |
import hashlib
import hmac
import json
import logging
import platform
import sys
from time import time
from fastapi import APIRouter, BackgroundTasks, Depends, Header, HTTPException
from sqlalchemy.orm import Session
from starlette.requests import Request
from starlette.responses import Response
from dispatch.data... | import hashlib
import hmac
import json
import logging
import platform
import sys
from time import time
from fastapi import APIRouter, BackgroundTasks, Depends, Header, HTTPException
from sqlalchemy.orm import Session
from starlette.requests import Request
from starlette.responses import Response
from dispatch.data... |
import http.server
import socketserver
from settings import PORT, TITLE, AUTHOR, DESCRIPTION
from logic import get_post_titles
from utils import date_to_str
posts = [f'<p><a href="">{date_to_str(e['date'])} - {e['title']}</a></p>' for e in get_post_titles()]
main_template = f"""
<!doctype html>
<html lang="en">
<h... | import http.server
import socketserver
from settings import PORT, TITLE, AUTHOR, DESCRIPTION
from logic import get_post_titles
from utils import date_to_str
posts = [f'<p><a href="">{date_to_str(e["date"])} - {e["title"]}</a></p>' for e in get_post_titles()]
main_template = f"""
<!doctype html>
<html lang="en">
<h... |
import os
import logging
from auth0.v3.management import Auth0
from auth0.v3.authentication import GetToken
logger = logging.getLogger(__name__)
def create_client(jupyterhub_endpoint, project_name, reuse_existing=True):
for variable in {"AUTH0_DOMAIN", "AUTH0_CLIENT_ID", "AUTH0_CLIENT_SECRET"}:
if varia... | import os
import logging
from auth0.v3.management import Auth0
from auth0.v3.authentication import GetToken
logger = logging.getLogger(__name__)
def create_client(jupyterhub_endpoint, project_name, reuse_existing=True):
for variable in {"AUTH0_DOMAIN", "AUTH0_CLIENT_ID", "AUTH0_CLIENT_SECRET"}:
if varia... |
from typing import List, TypeVar, Sequence, Dict, Tuple
from polyhedral_analysis.coordination_polyhedron import CoordinationPolyhedron
T = TypeVar('T')
"""
Utility functions
"""
def flatten(this_list: Sequence[Sequence[T]]) -> List[T]:
"""Flattens a nested list.
Args:
(list): A list of lists.
... | from typing import List, TypeVar, Sequence, Dict, Tuple
from polyhedral_analysis.coordination_polyhedron import CoordinationPolyhedron
T = TypeVar('T')
"""
Utility functions
"""
def flatten(this_list: Sequence[Sequence[T]]) -> List[T]:
"""Flattens a nested list.
Args:
(list): A list of lists.
... |
#
# 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 io import StringIO
from itertools import chain, product
from typing import List, Tuple, Type
from unittest import TestCase, TextTestRunner, defaultTestLoader, mock
from parametrize import parametrize
from parametrize.parametrize import UnparametrizedMethod
def run_unittests(case: Type[TestCase]):
suite = de... | from io import StringIO
from itertools import chain, product
from typing import List, Tuple, Type
from unittest import TestCase, TextTestRunner, defaultTestLoader, mock
from parametrize import parametrize
from parametrize.parametrize import UnparametrizedMethod
def run_unittests(case: Type[TestCase]):
suite = de... |
import sys
import socket
import argparse
import threading
from queue import Queue
from datetime import datetime
from multiprocessing import cpu_count
DEFAULT_THREAD = 2 * cpu_count()
DEFAULT_TIMEOUT = 0.05
DEFAULT_RETRIES = 4
PRINT_LOCK = threading.Lock()
TCP_SCAN_METHOD = {
"DONTFRAG": (socket.IPV6_D... | import sys
import socket
import argparse
import threading
from queue import Queue
from datetime import datetime
from multiprocessing import cpu_count
DEFAULT_THREAD = 2 * cpu_count()
DEFAULT_TIMEOUT = 0.05
DEFAULT_RETRIES = 4
PRINT_LOCK = threading.Lock()
TCP_SCAN_METHOD = {
"DONTFRAG": (socket.IPV6_D... |
# -*- coding: utf-8 -*-
import os
import sqlite3
from collections import namedtuple
from src.function.db.sqlite_abc import SqliteBasic
_author_ = 'luwt'
_date_ = '2021/11/12 16:56'
# item_name:打开的项目名称,在树结构中展示的名称,ext_info:一些其他信息,item_order:展示顺序,is_current:是否是当前项
# expanded:是否展开,parent_id:父id,level:在树结构中的级别,树结构:(0,1,2... | # -*- coding: utf-8 -*-
import os
import sqlite3
from collections import namedtuple
from src.function.db.sqlite_abc import SqliteBasic
_author_ = 'luwt'
_date_ = '2021/11/12 16:56'
# item_name:打开的项目名称,在树结构中展示的名称,ext_info:一些其他信息,item_order:展示顺序,is_current:是否是当前项
# expanded:是否展开,parent_id:父id,level:在树结构中的级别,树结构:(0,1,2... |
import io
import json
import logging
import os
import re
from contextlib import contextmanager
from textwrap import indent, wrap
from typing import Any, Dict, Iterator, List, Optional, Sequence, Union, cast
from .fastjsonschema_exceptions import JsonSchemaValueException
_logger = logging.getLogger(__name__)
_MESSAGE... | import io
import json
import logging
import os
import re
from contextlib import contextmanager
from textwrap import indent, wrap
from typing import Any, Dict, Iterator, List, Optional, Sequence, Union, cast
from .fastjsonschema_exceptions import JsonSchemaValueException
_logger = logging.getLogger(__name__)
_MESSAGE... |
#!/usr/bin/python3
import logging
import re
from collections import deque
from copy import deepcopy
from hashlib import sha1
from typing import Any, Dict, List, Optional, Set, Tuple, Union
import solcast
import solcx
from requests.exceptions import ConnectionError
from semantic_version import NpmSpec, Version
from so... | #!/usr/bin/python3
import logging
import re
from collections import deque
from copy import deepcopy
from hashlib import sha1
from typing import Any, Dict, List, Optional, Set, Tuple, Union
import solcast
import solcx
from requests.exceptions import ConnectionError
from semantic_version import NpmSpec, Version
from so... |
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and re... | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and re... |
import os
import matplotlib.pyplot as plt
import numpy as np
import strax
import straxen
@straxen.mini_analysis(requires=('raw_records',), warn_beyond_sec=5)
def plot_pulses_tpc(context, raw_records, run_id, time_range=None,
plot_hits=False, plot_median=False,
max_plots=20, st... | import os
import matplotlib.pyplot as plt
import numpy as np
import strax
import straxen
@straxen.mini_analysis(requires=('raw_records',), warn_beyond_sec=5)
def plot_pulses_tpc(context, raw_records, run_id, time_range=None,
plot_hits=False, plot_median=False,
max_plots=20, st... |
import os
from pathlib import Path
from pprint import pprint
from datetime import datetime
from xml.dom import minidom
import xml.etree.ElementTree as ET
import re
def get_all_txt_file_path():
txt_files_paths = list()
for root, dirs, files in os.walk(os.getcwd()):
for file in files:
if fil... | import os
from pathlib import Path
from pprint import pprint
from datetime import datetime
from xml.dom import minidom
import xml.etree.ElementTree as ET
import re
def get_all_txt_file_path():
txt_files_paths = list()
for root, dirs, files in os.walk(os.getcwd()):
for file in files:
if fil... |
import json
from operator import itemgetter
from contextlib import ExitStack
from textwrap import dedent
class TestAddPallet:
def test_no_pallet(self, host):
# Call add pallet with nothing mounted and no pallets passed in
result = host.run('stack add pallet')
assert result.rc == 255
assert result.stderr == 'e... | import json
from operator import itemgetter
from contextlib import ExitStack
from textwrap import dedent
class TestAddPallet:
def test_no_pallet(self, host):
# Call add pallet with nothing mounted and no pallets passed in
result = host.run('stack add pallet')
assert result.rc == 255
assert result.stderr == 'e... |
from pathlib import Path
from alphafold.Data.Tools import utils
from typing import Optional, Callable, Any, Mapping, Sequence
import subprocess
class Jackhammer:
def __init__(self,
binary_path:Path, database_path:Path,
n_cpu:int=8, n_iter:int=1,
e_value:float=1e-4, z_value:Optional[float]=None, filter_f1... | from pathlib import Path
from alphafold.Data.Tools import utils
from typing import Optional, Callable, Any, Mapping, Sequence
import subprocess
class Jackhammer:
def __init__(self,
binary_path:Path, database_path:Path,
n_cpu:int=8, n_iter:int=1,
e_value:float=1e-4, z_value:Optional[float]=None, filter_f1... |
from flask import Flask, request
import json
import requests as req
from config import config
from services.fb import FbApp
app = Flask(__name__)
Fb = None
def configure_fb_app():
global Fb
Fb = FbApp(config['fb_page_access_token'], config['fb_graph_url'])
@app.route('/webhook', methods = ['POST'])
def ... | from flask import Flask, request
import json
import requests as req
from config import config
from services.fb import FbApp
app = Flask(__name__)
Fb = None
def configure_fb_app():
global Fb
Fb = FbApp(config['fb_page_access_token'], config['fb_graph_url'])
@app.route('/webhook', methods = ['POST'])
def ... |
# Copyright 2020 The TensorFlow 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | # Copyright 2020 The TensorFlow 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
import sys
import argparse
import socket
import re
import requests
import json
import collections
version = "2.0 on Kivy" #Prepared to use in Kivy
'''
Information about the author of this module:
Author: Darko Sancanin
Twitter: @darkosan
GitHub: https://github.com/darkosancanin
'''
'''
You can find original (not ... | import sys
import argparse
import socket
import re
import requests
import json
import collections
version = "2.0 on Kivy" #Prepared to use in Kivy
'''
Information about the author of this module:
Author: Darko Sancanin
Twitter: @darkosan
GitHub: https://github.com/darkosancanin
'''
'''
You can find original (not ... |
import pandas as pd
from autor import Author
from excel import ExcelFile
from individuos import Student, Egress
from verifica_autores import em_lista_autores, trata_exceçoes
from valores import ND, quadrennium
from PyscopusModified import ScopusModified
from pprint import pprint
from excecoes import excecoes_artigos_sc... | import pandas as pd
from autor import Author
from excel import ExcelFile
from individuos import Student, Egress
from verifica_autores import em_lista_autores, trata_exceçoes
from valores import ND, quadrennium
from PyscopusModified import ScopusModified
from pprint import pprint
from excecoes import excecoes_artigos_sc... |
import contextlib
import inspect
import random
from typing import Optional
from redbot.core import commands
from redbot.core.utils.chat_formatting import bold, box
class Editor(str):
"""A main class used for the helper functions."""
def _charcount(self, count_spaces: bool):
if count_spaces:
... | import contextlib
import inspect
import random
from typing import Optional
from redbot.core import commands
from redbot.core.utils.chat_formatting import bold, box
class Editor(str):
"""A main class used for the helper functions."""
def _charcount(self, count_spaces: bool):
if count_spaces:
... |
# The bullet points associated with this set of tests in the evaluation document
test_set_id = "2.1"
# User friendly name of the tests
test_set_name = "Cap. Statement"
# Mem cache to avoid having to redo the same thing over and over
_capability_statement = None
_resources = None
import logging
logger = logging.get... |
# The bullet points associated with this set of tests in the evaluation document
test_set_id = "2.1"
# User friendly name of the tests
test_set_name = "Cap. Statement"
# Mem cache to avoid having to redo the same thing over and over
_capability_statement = None
_resources = None
import logging
logger = logging.get... |
#!/usr/bin/python3
import shutil
import os
import base64
from time import sleep
import flask
import requests.exceptions
import blueprint
from flask_cors import CORS
from confhttpproxy import ProxyRouter, ProxyRouterException
from flask import Flask, jsonify
import rest_routes
from lmsrvcore.utilities.migrate import... | #!/usr/bin/python3
import shutil
import os
import base64
from time import sleep
import flask
import requests.exceptions
import blueprint
from flask_cors import CORS
from confhttpproxy import ProxyRouter, ProxyRouterException
from flask import Flask, jsonify
import rest_routes
from lmsrvcore.utilities.migrate import... |
"""
This module represents a UNet experiment and contains a class that handles
the experiment lifecycle
"""
import os
import time
import numpy as np
import torch
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from ... | """
This module represents a UNet experiment and contains a class that handles
the experiment lifecycle
"""
import os
import time
import numpy as np
import torch
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from ... |
# @ author: Minyi Zhao
import os
os.environ['CUDA_VISIBLE_DEVICES'] = "0"
import time
import yaml
import argparse
import torch
import os.path as op
import numpy as np
from collections import OrderedDict
from tqdm import tqdm
import utils
import dataset
from net_rfda import RFDA
from skimage.metrics import peak_signal_... | # @ author: Minyi Zhao
import os
os.environ['CUDA_VISIBLE_DEVICES'] = "0"
import time
import yaml
import argparse
import torch
import os.path as op
import numpy as np
from collections import OrderedDict
from tqdm import tqdm
import utils
import dataset
from net_rfda import RFDA
from skimage.metrics import peak_signal_... |
# -*- coding: utf-8 -*-
""" core_model.py - define coure model API"""
import os
import abc
import yaml
import pandas as pd
import numpy as np
import logging
import subprocess
import warnings
from contextlib import contextmanager
from typing import Union, Mapping
from ..workbench.em_framework.model import AbstractModel ... | # -*- coding: utf-8 -*-
""" core_model.py - define coure model API"""
import os
import abc
import yaml
import pandas as pd
import numpy as np
import logging
import subprocess
import warnings
from contextlib import contextmanager
from typing import Union, Mapping
from ..workbench.em_framework.model import AbstractModel ... |
from default_config import basic_cfg
import albumentations as A
import os
import pandas as pd
import cv2
cfg = basic_cfg
cfg.debug = True
# paths
cfg.name = os.path.basename(__file__).split(".")[0]
cfg.data_dir = "/raid/landmark-recognition-2019/"
cfg.train
cfg.data_folder = cfg.data_dir + "train/"
cfg.train_df = "/... | from default_config import basic_cfg
import albumentations as A
import os
import pandas as pd
import cv2
cfg = basic_cfg
cfg.debug = True
# paths
cfg.name = os.path.basename(__file__).split(".")[0]
cfg.data_dir = "/raid/landmark-recognition-2019/"
cfg.train
cfg.data_folder = cfg.data_dir + "train/"
cfg.train_df = "/... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*- ########################################################
# ____ _ __ #
# ___ __ __/ / /__ ___ ______ ______(_) /___ __ #
# / _ \/ // / / (_-</ -_) __/ // / __/ / __/ // / ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*- ########################################################
# ____ _ __ #
# ___ __ __/ / /__ ___ ______ ______(_) /___ __ #
# / _ \/ // / / (_-</ -_) __/ // / __/ / __/ // / ... |
#!/usr/bin/env python3
# -*- config: utf-8 -*-
from functools import lru_cache
import timeit
@lru_cache
def fib(n):
if n == 0 or n == 1:
return n
else:
return fib(n - 2) + fib(n - 1)
@lru_cache
def factorial(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
... | #!/usr/bin/env python3
# -*- config: utf-8 -*-
from functools import lru_cache
import timeit
@lru_cache
def fib(n):
if n == 0 or n == 1:
return n
else:
return fib(n - 2) + fib(n - 1)
@lru_cache
def factorial(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from future.utils import tobytes
from past.builtins import basestring
from future.moves.urllib.parse import urlparse, urlsplit
import os
import logging
import xml.sax
impor... | from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from future.utils import tobytes
from past.builtins import basestring
from future.moves.urllib.parse import urlparse, urlsplit
import os
import logging
import xml.sax
impor... |
import os
import copy
import json
import time
import urllib
from pathlib import Path
import drms
import numpy as np
import astropy.table
import astropy.time
import astropy.units as u
from astropy.utils.misc import isiterable
from sunpy import config, log
from sunpy.net.attr import and_
from sunpy.net.base_client imp... | import os
import copy
import json
import time
import urllib
from pathlib import Path
import drms
import numpy as np
import astropy.table
import astropy.time
import astropy.units as u
from astropy.utils.misc import isiterable
from sunpy import config, log
from sunpy.net.attr import and_
from sunpy.net.base_client imp... |
from datetime import datetime
import time
import requests
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from discord_slash import SlashContext, cog_ext
from discord_slash.utils.manage_commands import create_option
# MongoDB handle
from lib.util import command_decorator, subcomm... | from datetime import datetime
import time
import requests
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from discord_slash import SlashContext, cog_ext
from discord_slash.utils.manage_commands import create_option
# MongoDB handle
from lib.util import command_decorator, subcomm... |
from typing import Optional
import click
from click.exceptions import Exit
from urllib.parse import urlparse
from valohai_cli import __version__
from valohai_cli.api import APISession
from valohai_cli.consts import default_app_host, yes_option
from valohai_cli.exceptions import APIError
from valohai_cli.messages impo... | from typing import Optional
import click
from click.exceptions import Exit
from urllib.parse import urlparse
from valohai_cli import __version__
from valohai_cli.api import APISession
from valohai_cli.consts import default_app_host, yes_option
from valohai_cli.exceptions import APIError
from valohai_cli.messages impo... |
from datetime import datetime
from pathlib import Path
from sepal_ui import sepalwidgets as sw
from sepal_ui.scripts import utils as su
import ipyvuetify as v
from component import scripts as cs
from component.message import cm
from component import widget as cw
from component import parameter as cp
class Validation... | from datetime import datetime
from pathlib import Path
from sepal_ui import sepalwidgets as sw
from sepal_ui.scripts import utils as su
import ipyvuetify as v
from component import scripts as cs
from component.message import cm
from component import widget as cw
from component import parameter as cp
class Validation... |
from datetime import datetime
from osmium import SimpleWriter
from osmium.osm.mutable import Way, Node
OSM_ID_START = 10**10
def transform_plazas(plazas, node_file, way_file, footway_tags):
""" transforms plazas to OSM and write them to a file """
node_writer = SimpleWriter(node_file)
way_writer = Simpl... | from datetime import datetime
from osmium import SimpleWriter
from osmium.osm.mutable import Way, Node
OSM_ID_START = 10**10
def transform_plazas(plazas, node_file, way_file, footway_tags):
""" transforms plazas to OSM and write them to a file """
node_writer = SimpleWriter(node_file)
way_writer = Simpl... |
import logging
import functools
import sqlalchemy
from connexion import problem
from dateutil.parser import isoparse as date_parse
from rhub.lab import SHAREDCLUSTER_USER
from rhub.lab import model
from rhub.api import db, di, DEFAULT_PAGE_LIMIT
from rhub.auth import ADMIN_ROLE
from rhub.auth.utils import route_requi... | import logging
import functools
import sqlalchemy
from connexion import problem
from dateutil.parser import isoparse as date_parse
from rhub.lab import SHAREDCLUSTER_USER
from rhub.lab import model
from rhub.api import db, di, DEFAULT_PAGE_LIMIT
from rhub.auth import ADMIN_ROLE
from rhub.auth.utils import route_requi... |
'''
Builder for Skills HTML
'''
# ----- Local Imports -----
import importlib
common = importlib.import_module('src.python.common')
# ----- Local Helpers -----
# Build HTML from JSON
def build(fType, fName, j):
t = "skills"
html = f"<script>i.{t} = {str(len(j))};</script><p class='iconHeader'>"+t.capitalize()... | '''
Builder for Skills HTML
'''
# ----- Local Imports -----
import importlib
common = importlib.import_module('src.python.common')
# ----- Local Helpers -----
# Build HTML from JSON
def build(fType, fName, j):
t = "skills"
html = f"<script>i.{t} = {str(len(j))};</script><p class='iconHeader'>"+t.capitalize()... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
"""
Support for running a tool in Galaxy via an internal job management system
"""
import copy
import datetime
import errno
import json
import logging
import os
import pwd
import shutil
import string
import sys
import time
import traceback
from abc import (
ABCMeta,
abstractmethod,
)
from json import loads
from... | """
Support for running a tool in Galaxy via an internal job management system
"""
import copy
import datetime
import errno
import json
import logging
import os
import pwd
import shutil
import string
import sys
import time
import traceback
from abc import (
ABCMeta,
abstractmethod,
)
from json import loads
from... |
import hedfpy
from . import glm, plotting, preproc, utils
import matplotlib.pyplot as plt
import nibabel as nb
from nilearn.signal import clean
import numpy as np
import os
import pandas as pd
from scipy import io, stats
import warnings
opj = os.path.join
pd.options.mode.chained_assignment = None # disable warning thr... | import hedfpy
from . import glm, plotting, preproc, utils
import matplotlib.pyplot as plt
import nibabel as nb
from nilearn.signal import clean
import numpy as np
import os
import pandas as pd
from scipy import io, stats
import warnings
opj = os.path.join
pd.options.mode.chained_assignment = None # disable warning thr... |
# -*- coding: UTF-8 -*-
import os
import traceback
import simplejson as json
from django.conf import settings
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.models import Group
from django.core.exceptions import PermissionDenied
from django.shortcuts import render, get_object_... | # -*- coding: UTF-8 -*-
import os
import traceback
import simplejson as json
from django.conf import settings
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.models import Group
from django.core.exceptions import PermissionDenied
from django.shortcuts import render, get_object_... |
from algorithms.genetic import Genome
from collections import namedtuple
Thing = namedtuple('Thing', ['name', 'value', 'weight'])
first_example = [
Thing('Laptop', 500, 2200),
Thing('Headphones', 150, 160),
Thing('Coffee Mug', 60, 350),
Thing('Notepad', 40, 333),
Thing('Water Bottle', 30, 192),
]
... | from algorithms.genetic import Genome
from collections import namedtuple
Thing = namedtuple('Thing', ['name', 'value', 'weight'])
first_example = [
Thing('Laptop', 500, 2200),
Thing('Headphones', 150, 160),
Thing('Coffee Mug', 60, 350),
Thing('Notepad', 40, 333),
Thing('Water Bottle', 30, 192),
]
... |
#!/usr/bin/env python3
"""
Name: Achal Kumar Garg <achalkumargarg89@gmail.com>
Date: 2020-01-30
Purpose: Abuse
"""
import argparse
import random
# ---------------------------------------------------------
def get_args():
parser = argparse.ArgumentParser(
description = 'Heap abuse',
... | #!/usr/bin/env python3
"""
Name: Achal Kumar Garg <achalkumargarg89@gmail.com>
Date: 2020-01-30
Purpose: Abuse
"""
import argparse
import random
# ---------------------------------------------------------
def get_args():
parser = argparse.ArgumentParser(
description = 'Heap abuse',
... |
import asyncio
import itertools
import os
import random
from functools import partial
from async_timeout import timeout
import youtube_dl as yt
import discord
from discord.ext import commands
from tools.locales import alias
ytdlopts = {
'format': 'bestaudio/best',
'restrictfilenames': True,
'noplaylist':... | import asyncio
import itertools
import os
import random
from functools import partial
from async_timeout import timeout
import youtube_dl as yt
import discord
from discord.ext import commands
from tools.locales import alias
ytdlopts = {
'format': 'bestaudio/best',
'restrictfilenames': True,
'noplaylist':... |
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... |
import logging
import sys
import sendgrid
import reconcile.queries as queries
from reconcile.utils.secret_reader import SecretReader
from reconcile.status import ExitCodes
LOG = logging.getLogger(__name__)
QONTRACT_INTEGRATION = 'sendgrid_teammates'
class SendGridAPIError(Exception):
pass
class Teammate:
... | import logging
import sys
import sendgrid
import reconcile.queries as queries
from reconcile.utils.secret_reader import SecretReader
from reconcile.status import ExitCodes
LOG = logging.getLogger(__name__)
QONTRACT_INTEGRATION = 'sendgrid_teammates'
class SendGridAPIError(Exception):
pass
class Teammate:
... |
import datetime
import hashlib
import logging
import os
import smtplib
from email.headerregistry import Address
from email.parser import Parser
from email.policy import default
from email.utils import formataddr, parseaddr
from typing import Any, Dict, List, Mapping, Optional, Tuple
import backoff
import orjson
from d... | import datetime
import hashlib
import logging
import os
import smtplib
from email.headerregistry import Address
from email.parser import Parser
from email.policy import default
from email.utils import formataddr, parseaddr
from typing import Any, Dict, List, Mapping, Optional, Tuple
import backoff
import orjson
from d... |
from .base import InvalidInput
from goldstone.lib.errors import Error
from .cli import (
Command,
Context,
Run,
RunningConfigCommand,
GlobalShowCommand,
ModelExists,
TechSupportCommand,
ShowCommand,
ConfigCommand,
)
from .root import Root
from .util import dig_dict, human_ber, obj... | from .base import InvalidInput
from goldstone.lib.errors import Error
from .cli import (
Command,
Context,
Run,
RunningConfigCommand,
GlobalShowCommand,
ModelExists,
TechSupportCommand,
ShowCommand,
ConfigCommand,
)
from .root import Root
from .util import dig_dict, human_ber, obj... |
# 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 json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class Origin... | # 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 json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class Origin... |
import os
from pathlib import Path
from quart import Quart, request, Response
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = './files/'
ALLOWED_EXTENSIONS = {'tar', 'txt'}
app = Quart(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['ALLOWED_EXTENSIONS'] = ALLOWED_EXTENSIONS
app.config['M... | import os
from pathlib import Path
from quart import Quart, request, Response
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = './files/'
ALLOWED_EXTENSIONS = {'tar', 'txt'}
app = Quart(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['ALLOWED_EXTENSIONS'] = ALLOWED_EXTENSIONS
app.config['M... |
import datetime
import enum
import logging
from typing import Union, Optional, TypeVar, List, Type, Callable, Dict, TYPE_CHECKING
from ravendb import constants
from ravendb.documents.commands.query import QueryCommand
from ravendb.documents.queries.index_query import IndexQuery
from ravendb.documents.queries.query imp... | import datetime
import enum
import logging
from typing import Union, Optional, TypeVar, List, Type, Callable, Dict, TYPE_CHECKING
from ravendb import constants
from ravendb.documents.commands.query import QueryCommand
from ravendb.documents.queries.index_query import IndexQuery
from ravendb.documents.queries.query imp... |
import json
import random
from danmu_abc import TcpConn, Client
from .utils import Header, Opt, Pack
class TcpDanmuClient(Client):
__slots__ = ('_room_id', '_pack_heartbeat')
def __init__(
self, room_id: int, area_id: int, loop=None):
heartbeat = 30.0
conn = TcpConn(
... | import json
import random
from danmu_abc import TcpConn, Client
from .utils import Header, Opt, Pack
class TcpDanmuClient(Client):
__slots__ = ('_room_id', '_pack_heartbeat')
def __init__(
self, room_id: int, area_id: int, loop=None):
heartbeat = 30.0
conn = TcpConn(
... |
from training_data.eddies import eddy_detection,dataframe_eddies,plot_eddies,julianh2gregorian
from tools.machine_learning import sliding_window
from matplotlib.patches import Rectangle
from tools.load_nc import load_netcdf4
from numpy import savez_compressed
import matplotlib.pyplot as plt
from tools.bfs import bfs
fr... | from training_data.eddies import eddy_detection,dataframe_eddies,plot_eddies,julianh2gregorian
from tools.machine_learning import sliding_window
from matplotlib.patches import Rectangle
from tools.load_nc import load_netcdf4
from numpy import savez_compressed
import matplotlib.pyplot as plt
from tools.bfs import bfs
fr... |
"""
Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/L... | """
Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/L... |
import requests
import threading
from random import randrange
import datetime
def getUrl(limit) :
# url = f"https://e9ea25810dfb.ngrok.io?limit={limit}"
url = f"http://localhost:3000?limit={limit}"
payload = {}
headers= {}
i=0
while i<1000:
try:
s = datetime.datetime.now()
response = reques... | import requests
import threading
from random import randrange
import datetime
def getUrl(limit) :
# url = f"https://e9ea25810dfb.ngrok.io?limit={limit}"
url = f"http://localhost:3000?limit={limit}"
payload = {}
headers= {}
i=0
while i<1000:
try:
s = datetime.datetime.now()
response = reques... |
"""
https://github.com/tseemann/prokka
"""
from SNDG import docker_wrap_command, DOCKER_MAPPINGS, execute
class Prokka:
"""
"""
DEFAULT_DOCKER_IMG = "staphb/prokka:latest"
def __init__(self):
pass
def add_spades_data(self, fasta_path, gbk_path):
pass
def annotate(self, fas... | """
https://github.com/tseemann/prokka
"""
from SNDG import docker_wrap_command, DOCKER_MAPPINGS, execute
class Prokka:
"""
"""
DEFAULT_DOCKER_IMG = "staphb/prokka:latest"
def __init__(self):
pass
def add_spades_data(self, fasta_path, gbk_path):
pass
def annotate(self, fas... |
"""Amazon Microsoft SQL Server Module."""
import importlib.util
import logging
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, TypeVar, Union
import boto3
import pandas as pd
import pyarrow as pa
from awswrangler import _data_types
from awswrangler import _databases as _db_utils
from awswra... | """Amazon Microsoft SQL Server Module."""
import importlib.util
import logging
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, TypeVar, Union
import boto3
import pandas as pd
import pyarrow as pa
from awswrangler import _data_types
from awswrangler import _databases as _db_utils
from awswra... |
def part1(fileName):
counter = 0
prev_number = 999999999
with open(f'data/{fileName}') as f:
lines = f.read().splitlines()
lines = [int(x) for x in lines]
for number in lines:
if number > prev_number:
counter +=1
prev_num... |
def part1(fileName):
counter = 0
prev_number = 999999999
with open(f'data/{fileName}') as f:
lines = f.read().splitlines()
lines = [int(x) for x in lines]
for number in lines:
if number > prev_number:
counter +=1
prev_num... |
#!/usr/bin/python3
# -*- encoding: utf-8 -*-
'''
@File : 8-a.py
@Time : 2019/11/14
@Author : Iydon Liang
@Contact : liangiydon@gmail.com
@Docstring : <no docstring>
'''
from os import get_terminal_size
columns = get_terminal_size().columns
from sympy import symbols, integrate, diff, exp, sqrt, log
from... | #!/usr/bin/python3
# -*- encoding: utf-8 -*-
'''
@File : 8-a.py
@Time : 2019/11/14
@Author : Iydon Liang
@Contact : liangiydon@gmail.com
@Docstring : <no docstring>
'''
from os import get_terminal_size
columns = get_terminal_size().columns
from sympy import symbols, integrate, diff, exp, sqrt, log
from... |
import json
import time
import logging
from datetime import datetime
from dataclasses import dataclass
from src.config_loader import ConfigLoader
from src.ochoba_api_wrapper import OchobaApiWrapper
TJ_POSTS_DIR = "/home/cyrus/Personal/blog/osnova_social/data/tj_data/posts"
VC_POSTS_DIR = "/home/cyrus/Personal/blog/os... | import json
import time
import logging
from datetime import datetime
from dataclasses import dataclass
from src.config_loader import ConfigLoader
from src.ochoba_api_wrapper import OchobaApiWrapper
TJ_POSTS_DIR = "/home/cyrus/Personal/blog/osnova_social/data/tj_data/posts"
VC_POSTS_DIR = "/home/cyrus/Personal/blog/os... |
import os
import re
import webbrowser
from typing import List, Optional, Tuple, Union
import colorama
from git import Git, GitCommandError
from gutsygit.utils import removeprefix
colorama.init(autoreset=True)
LEVEL_DEBUG = -1
LEVEL_INFO = 0
LEVEL_HEADER = 1
LEVEL_WARNING = 2
LEVEL_ERROR = 3
OUTPUT_COLORS = {
L... | import os
import re
import webbrowser
from typing import List, Optional, Tuple, Union
import colorama
from git import Git, GitCommandError
from gutsygit.utils import removeprefix
colorama.init(autoreset=True)
LEVEL_DEBUG = -1
LEVEL_INFO = 0
LEVEL_HEADER = 1
LEVEL_WARNING = 2
LEVEL_ERROR = 3
OUTPUT_COLORS = {
L... |
"""Iterate through our talks and announce them to discord when it's time to go see the talk.
TODO:
1. Decide how we want to do the actual scheduling: celery? event loop like tornado? cron job?
2. Iterate over all the talks and test it in Discord
3. Delete all the announcements before we invite anyone in
"""
from typin... | """Iterate through our talks and announce them to discord when it's time to go see the talk.
TODO:
1. Decide how we want to do the actual scheduling: celery? event loop like tornado? cron job?
2. Iterate over all the talks and test it in Discord
3. Delete all the announcements before we invite anyone in
"""
from typin... |
# -*- 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. #
# ... |
from . import lookupProdDemand as pd
# defining the sequence for the calculation from top to bottom, most complex products first
calculation_sequence = ["P1", "P2", "P3", "E26", "E31", "E51", "E56", "E16", "E17", "E30", "E50", "E55", "E4",
"E5", "E6", "E10", "E11", "E12", "E29", "E49", "E54", "... | from . import lookupProdDemand as pd
# defining the sequence for the calculation from top to bottom, most complex products first
calculation_sequence = ["P1", "P2", "P3", "E26", "E31", "E51", "E56", "E16", "E17", "E30", "E50", "E55", "E4",
"E5", "E6", "E10", "E11", "E12", "E29", "E49", "E54", "... |
import uuid
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, username, password):
"""
Created user with given email username and password
:param: email
:param: use... | import uuid
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, username, password):
"""
Created user with given email username and password
:param: email
:param: use... |
import logging
import os
import shutil
from django.conf import settings
from django.db import models
from django import forms
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django.utils.datetime_safe import datetime
logger = logging.getLogger('web')
class BooleanFieldExper... | import logging
import os
import shutil
from django.conf import settings
from django.db import models
from django import forms
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django.utils.datetime_safe import datetime
logger = logging.getLogger('web')
class BooleanFieldExper... |
import PIL.Image
import itertools
import random
import subprocess
import io
import os.path
from telegram import (
InlineKeyboardMarkup,
InlineKeyboardButton,
InputMediaPhoto,
InputMediaVideo,
User,
Message,
)
import cv2
import numpy
IDSAMPLE = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX... | import PIL.Image
import itertools
import random
import subprocess
import io
import os.path
from telegram import (
InlineKeyboardMarkup,
InlineKeyboardButton,
InputMediaPhoto,
InputMediaVideo,
User,
Message,
)
import cv2
import numpy
IDSAMPLE = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX... |
#! /usr/bin/env python
import asyncio
import aiohttp
import configparser
import logging
import time
from urllib.parse import urljoin
from pathlib import Path
log = logging.getLogger('gbackup-async')
# log.setLevel(logging.DEBUG)
# Gitlab API v4 base URL.
BASE_GITLAB_URL = 'https://gitlab.com/api/v4/'
# Time to sle... | #! /usr/bin/env python
import asyncio
import aiohttp
import configparser
import logging
import time
from urllib.parse import urljoin
from pathlib import Path
log = logging.getLogger('gbackup-async')
# log.setLevel(logging.DEBUG)
# Gitlab API v4 base URL.
BASE_GITLAB_URL = 'https://gitlab.com/api/v4/'
# Time to sle... |
import os
import shutil
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import yaml
from chives import __version__
from chives.consensus.coinbase import create_puzzlehash_for_pk
from chives.ssl.create_ssl import (
ensure_ssl_dirs,
generate_ca_signed_cert,
get_chives_ca_crt_key... | import os
import shutil
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import yaml
from chives import __version__
from chives.consensus.coinbase import create_puzzlehash_for_pk
from chives.ssl.create_ssl import (
ensure_ssl_dirs,
generate_ca_signed_cert,
get_chives_ca_crt_key... |
import json
import logging
from datetime import date
from dateutil import parser
from sqlalchemy.exc import IntegrityError
from sqlalchemy.sql import func
from couchers.crypto import hash_password
from couchers.db import get_user_by_field, session_scope
from couchers.models import (
Cluster,
ClusterRole,
... | import json
import logging
from datetime import date
from dateutil import parser
from sqlalchemy.exc import IntegrityError
from sqlalchemy.sql import func
from couchers.crypto import hash_password
from couchers.db import get_user_by_field, session_scope
from couchers.models import (
Cluster,
ClusterRole,
... |
import os
import inspect
import importlib
def _not_hidden(f):
return f[0] != "_" and f[0] !='.'
def _get_files(file_):
return [
os.path.splitext(f.name)[0]
for f in os.scandir(os.path.dirname(file_))
if f.is_file() and _not_hidden(f.name)
]
def _get_dirs(file_, ignore=[]):
... | import os
import inspect
import importlib
def _not_hidden(f):
return f[0] != "_" and f[0] !='.'
def _get_files(file_):
return [
os.path.splitext(f.name)[0]
for f in os.scandir(os.path.dirname(file_))
if f.is_file() and _not_hidden(f.name)
]
def _get_dirs(file_, ignore=[]):
... |
import sys
import os
import ast
import jsonpickle
import datetime
# PyQt5
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWidgets import QTabWidget, QTabBar
from PyQt5 import uic
from PyQt5 import QtCore
# Own Modules
from NodeManager import NodeManager
from ViewManager import ViewManager
from View... | import sys
import os
import ast
import jsonpickle
import datetime
# PyQt5
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWidgets import QTabWidget, QTabBar
from PyQt5 import uic
from PyQt5 import QtCore
# Own Modules
from NodeManager import NodeManager
from ViewManager import ViewManager
from View... |
import json
import logging
import websockets
import hmac
import hashlib
import datetime
from typing import List, Callable, Any, Optional
from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bitvavo.functions import map_pair... | import json
import logging
import websockets
import hmac
import hashlib
import datetime
from typing import List, Callable, Any, Optional
from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bitvavo.functions import map_pair... |
#!/usr/bin/env python3
#
# Copyright (c) Bo Peng and the University of Texas MD Anderson Cancer Center
# Distributed under the terms of the 3-clause BSD License.
import os
import pytest
import subprocess
import unittest
from sos.parser import ParsingError, SoS_Script
from sos.targets import file_target, sos_targets, ... | #!/usr/bin/env python3
#
# Copyright (c) Bo Peng and the University of Texas MD Anderson Cancer Center
# Distributed under the terms of the 3-clause BSD License.
import os
import pytest
import subprocess
import unittest
from sos.parser import ParsingError, SoS_Script
from sos.targets import file_target, sos_targets, ... |
from django.test import TestCase
from task.models import Task, Tag
from task.serializers import TaskSerializer
from django.conf import settings
class TestFullImageUrl(TestCase):
def setUp(self) -> None:
self.path = '/media/image.png'
self.task = Task.objects.create(name='demo', image='/image.png'... | from django.test import TestCase
from task.models import Task, Tag
from task.serializers import TaskSerializer
from django.conf import settings
class TestFullImageUrl(TestCase):
def setUp(self) -> None:
self.path = '/media/image.png'
self.task = Task.objects.create(name='demo', image='/image.png'... |
"""
An integration module for the Virus Total v3 API.
API Documentation:
https://developers.virustotal.com/v3.0/reference
"""
from collections import defaultdict
from typing import Callable
from dateparser import parse
from CommonServerPython import *
INTEGRATION_NAME = "VirusTotal"
COMMAND_PREFIX = "vt"
INTEGRA... | """
An integration module for the Virus Total v3 API.
API Documentation:
https://developers.virustotal.com/v3.0/reference
"""
from collections import defaultdict
from typing import Callable
from dateparser import parse
from CommonServerPython import *
INTEGRATION_NAME = "VirusTotal"
COMMAND_PREFIX = "vt"
INTEGRA... |
import json
from hashlib import sha256
from collections import Counter
from inputimeout import inputimeout, TimeoutOccurred
import tabulate, copy, time, datetime, requests, sys, os, random
BOOKING_URL = "https://cdn-api.co-vin.in/api/v2/appointment/schedule"
BENEFICIARIES_URL = "https://cdn-api.co-vin.in/api/v2/appoin... | import json
from hashlib import sha256
from collections import Counter
from inputimeout import inputimeout, TimeoutOccurred
import tabulate, copy, time, datetime, requests, sys, os, random
BOOKING_URL = "https://cdn-api.co-vin.in/api/v2/appointment/schedule"
BENEFICIARIES_URL = "https://cdn-api.co-vin.in/api/v2/appoin... |
# -* coding: utf-8 -*-
#
# profiler : a Wi-Fi client capability analyzer tool
# Copyright : (c) 2020-2021 Josh Schmelzle
# License : BSD-3-Clause
# Maintainer : josh@joshschmelzle.com
"""
profiler.helpers
~~~~~~~~~~~~~~~~
provides init functions that are used to help setup the app.
"""
# standard library imports
imp... | # -* coding: utf-8 -*-
#
# profiler : a Wi-Fi client capability analyzer tool
# Copyright : (c) 2020-2021 Josh Schmelzle
# License : BSD-3-Clause
# Maintainer : josh@joshschmelzle.com
"""
profiler.helpers
~~~~~~~~~~~~~~~~
provides init functions that are used to help setup the app.
"""
# standard library imports
imp... |
import os
import sys
from datetime import datetime,timedelta
import logging
import pathlib
import tempfile
import subprocess
import shutil
from typing import Union
from time import time
import numpy as np
import scipy as sp
from numba import jit, prange
import netCDF4 as nc
from netCDF4 import Dataset
from matplotlib.... | import os
import sys
from datetime import datetime,timedelta
import logging
import pathlib
import tempfile
import subprocess
import shutil
from typing import Union
from time import time
import numpy as np
import scipy as sp
from numba import jit, prange
import netCDF4 as nc
from netCDF4 import Dataset
from matplotlib.... |
# The MIT License (MIT)
# Copyright (c) 2018 by the xcube development team and contributors
#
# 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 MIT License (MIT)
# Copyright (c) 2018 by the xcube development team and contributors
#
# 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... |
# 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... |
import pyforest
import os
import logging
from dataclasses import dataclass, field
from typing import Dict, List, Optional
import sys
import torch
import nlp
from transformers import T5Tokenizer, BartTokenizer, HfArgumentParser
from datasets import list_datasets, load_dataset, list_metrics, load_metric, Dataset
import ... | import pyforest
import os
import logging
from dataclasses import dataclass, field
from typing import Dict, List, Optional
import sys
import torch
import nlp
from transformers import T5Tokenizer, BartTokenizer, HfArgumentParser
from datasets import list_datasets, load_dataset, list_metrics, load_metric, Dataset
import ... |
"""This module provides a set of pytest hooks for generating Adaptavist test run results from test reports."""
from __future__ import annotations
import getpass
import logging
import os
from importlib.metadata import PackageNotFoundError, version
from typing import Any, Literal, NoReturn
import pytest
from _pytest.c... | """This module provides a set of pytest hooks for generating Adaptavist test run results from test reports."""
from __future__ import annotations
import getpass
import logging
import os
from importlib.metadata import PackageNotFoundError, version
from typing import Any, Literal, NoReturn
import pytest
from _pytest.c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
print('{0}-{1}-{0}'.format('Good', 'morning'))
print('{}-{}'.format('你', '好'))
print('{name}:{age}'.format(name='Tom', age=18))
x, y = 100, 200
print('{0}-{1}'.format(x, y))
print(f'x: {x}{{显示大括号}}') # 3.6版加入f-string方法
print('%%d x: %d' % x) # C format
print('%%(x)d x:... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
print('{0}-{1}-{0}'.format('Good', 'morning'))
print('{}-{}'.format('你', '好'))
print('{name}:{age}'.format(name='Tom', age=18))
x, y = 100, 200
print('{0}-{1}'.format(x, y))
print(f'x: {x}{{显示大括号}}') # 3.6版加入f-string方法
print('%%d x: %d' % x) # C format
print('%%(x)d x:... |
# Tau Copyright 2019-2020 The Apache Software Foundation
import asyncio
import datetime
import os
import sys
from collections.abc import Iterable
import asyncpg
import discord
from discord import Object, Permissions
from discord.ext import commands
from discord.utils import oauth_url
import ccp
import config
import ... | # Tau Copyright 2019-2020 The Apache Software Foundation
import asyncio
import datetime
import os
import sys
from collections.abc import Iterable
import asyncpg
import discord
from discord import Object, Permissions
from discord.ext import commands
from discord.utils import oauth_url
import ccp
import config
import ... |
# Copyright 2015, Aiven, https://aiven.io/
#
# This file is under the Apache License, Version 2.0.
# See the file `LICENSE` for details.
from . import argx, client
from aiven.client import envdefault
from aiven.client.cliarg import arg
from aiven.client.speller import suggest
from collections import Counter
from decima... | # Copyright 2015, Aiven, https://aiven.io/
#
# This file is under the Apache License, Version 2.0.
# See the file `LICENSE` for details.
from . import argx, client
from aiven.client import envdefault
from aiven.client.cliarg import arg
from aiven.client.speller import suggest
from collections import Counter
from decima... |
"""The hashing module contains all methods and classes related to the hashing trick."""
import sys
import hashlib
import category_encoders.utils as util
import multiprocessing
import pandas as pd
import math
import platform
__author__ = 'willmcginnis', 'LiuShulun'
class HashingEncoder(util.BaseEncoder, util.Unsuper... | """The hashing module contains all methods and classes related to the hashing trick."""
import sys
import hashlib
import category_encoders.utils as util
import multiprocessing
import pandas as pd
import math
import platform
__author__ = 'willmcginnis', 'LiuShulun'
class HashingEncoder(util.BaseEncoder, util.Unsuper... |
# -*- coding: utf-8 -*-
"""
preprocess input data into feature and stores binary as python shelve DB
each chunk is gzipped JSON string
"""
import argparse
import gzip
import json
import subprocess as sp
import shelve
import os
from os.path import dirname, exists, join
import torch
from lsp_model import GPT2Tokenizer
... | # -*- coding: utf-8 -*-
"""
preprocess input data into feature and stores binary as python shelve DB
each chunk is gzipped JSON string
"""
import argparse
import gzip
import json
import subprocess as sp
import shelve
import os
from os.path import dirname, exists, join
import torch
from lsp_model import GPT2Tokenizer
... |
"""Generate model from OpenAPI schema."""
import itertools
import typing
from . import column_factory
from . import exceptions
from . import helpers
from . import table_args
from . import types
from . import utility_base
def model_factory(
*, name: str, base: typing.Type, schemas: types.Schemas
) -> typing.Type... | """Generate model from OpenAPI schema."""
import itertools
import typing
from . import column_factory
from . import exceptions
from . import helpers
from . import table_args
from . import types
from . import utility_base
def model_factory(
*, name: str, base: typing.Type, schemas: types.Schemas
) -> typing.Type... |
# -*- coding: utf-8 -*-
"""
-----------------------------------------------------
File Name: redisClient.py
Description : 封装Redis相关操作
Author : JHao
date: 2019/8/9
------------------------------------------------------
Change Activity:
2019/08/09: 封装Redis相关操作
... | # -*- coding: utf-8 -*-
"""
-----------------------------------------------------
File Name: redisClient.py
Description : 封装Redis相关操作
Author : JHao
date: 2019/8/9
------------------------------------------------------
Change Activity:
2019/08/09: 封装Redis相关操作
... |
from dataclasses import dataclass, field
from .io_utils import process_file, save_yaml, read_yaml, data_name, patch_decorator, patch, prepend_baseurl, \
remove_ending, find_key, process_subs
from .md import build_markdown
from .content import process_content
from .jekyll import create_jekyll_home_header, create_jek... | from dataclasses import dataclass, field
from .io_utils import process_file, save_yaml, read_yaml, data_name, patch_decorator, patch, prepend_baseurl, \
remove_ending, find_key, process_subs
from .md import build_markdown
from .content import process_content
from .jekyll import create_jekyll_home_header, create_jek... |
# -*- coding: utf-8 -*-
# Authors: MNE Developers
#
# License: BSD (3-clause)
import datetime
import numpy as np
from ..io.egi.egimff import _import_mffpy
from ..io.pick import pick_types, pick_channels
from ..utils import verbose
@verbose
def export_evokeds_mff(fname, evoked, history=None, *, verbose=None):
"... | # -*- coding: utf-8 -*-
# Authors: MNE Developers
#
# License: BSD (3-clause)
import datetime
import numpy as np
from ..io.egi.egimff import _import_mffpy
from ..io.pick import pick_types, pick_channels
from ..utils import verbose
@verbose
def export_evokeds_mff(fname, evoked, history=None, *, verbose=None):
"... |
"""Generate mypy config."""
from __future__ import annotations
import configparser
import io
import os
from pathlib import Path
from typing import Final
from .model import Config, Integration
# Modules which have type hints which known to be broken.
# If you are an author of component listed here, please fix these e... | """Generate mypy config."""
from __future__ import annotations
import configparser
import io
import os
from pathlib import Path
from typing import Final
from .model import Config, Integration
# Modules which have type hints which known to be broken.
# If you are an author of component listed here, please fix these e... |
from django.db import models
from django_backblaze_b2 import BackblazeB2Storage, LoggedInStorage, PublicStorage, StaffStorage
class ModelWithFiles(models.Model):
b2StorageFile = models.FileField(
name="b2StorageFile",
upload_to="uploads",
verbose_name="B2 Storage File",
storage=Ba... | from django.db import models
from django_backblaze_b2 import BackblazeB2Storage, LoggedInStorage, PublicStorage, StaffStorage
class ModelWithFiles(models.Model):
b2StorageFile = models.FileField(
name="b2StorageFile",
upload_to="uploads",
verbose_name="B2 Storage File",
storage=Ba... |
"""
Crypto Bot running based on a given strategy
"""
import logging
import mplfinance as mpf
from common.analyst import resample_candles
from common.logger import init_logging
from common.steps import (
SetupDatabase,
ReadConfiguration,
FetchDataFromExchange,
LoadDataInDataFrame,
TradeSignal,
... | """
Crypto Bot running based on a given strategy
"""
import logging
import mplfinance as mpf
from common.analyst import resample_candles
from common.logger import init_logging
from common.steps import (
SetupDatabase,
ReadConfiguration,
FetchDataFromExchange,
LoadDataInDataFrame,
TradeSignal,
... |
# coding=utf-8
# Copyright 2020 The HuggingFace 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 required by applicable... | # coding=utf-8
# Copyright 2020 The HuggingFace 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 required by applicable... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch import Tensor
import numpy as np
from... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch import Tensor
import numpy as np
from... |
import argparse
import datetime
import logging
import os
import sys
from tqdm import tqdm
from booking.api.booking_api import LIMIT_REQUESTS_PER_MINUTE
from booking.download_hotels import download
from booking.download_test_data import download_test_data
def process_options():
parser = argparse.ArgumentParser(d... | import argparse
import datetime
import logging
import os
import sys
from tqdm import tqdm
from booking.api.booking_api import LIMIT_REQUESTS_PER_MINUTE
from booking.download_hotels import download
from booking.download_test_data import download_test_data
def process_options():
parser = argparse.ArgumentParser(d... |
import logging
from spaceone.core import utils
from spaceone.core.manager import BaseManager
from spaceone.inventory.model.server_model import Server
from spaceone.inventory.lib.resource_manager import ResourceManager
from spaceone.inventory.error import *
_LOGGER = logging.getLogger(__name__)
class ServerManager(B... | import logging
from spaceone.core import utils
from spaceone.core.manager import BaseManager
from spaceone.inventory.model.server_model import Server
from spaceone.inventory.lib.resource_manager import ResourceManager
from spaceone.inventory.error import *
_LOGGER = logging.getLogger(__name__)
class ServerManager(B... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.