file_path stringlengths 10 10 | code stringlengths 79 330k | code_en stringlengths 79 330k | language stringclasses 1
value | license stringclasses 0
values | token_count int32 24 158k |
|---|---|---|---|---|---|
0029662.py | import asyncio
class Right(asyncio.Protocol):
SEP = b'\n'
def __init__(self, logger, loop, left):
self.logger = logger
self.loop = loop
self.left = left
self.buffer = bytes()
self.transport = None
self.w_q = asyncio.Queue()
self.peername = (None, None)... | import asyncio
class Right(asyncio.Protocol):
SEP = b'\n'
def __init__(self, logger, loop, left):
self.logger = logger
self.loop = loop
self.left = left
self.buffer = bytes()
self.transport = None
self.w_q = asyncio.Queue()
self.peername = (None, None)... | en | null | 667 |
0012915.py | ####
# This script demonstrates how to use the Tableau Server Client
# to query extract refresh tasks and run them as needed.
#
# To run the script, you must have installed Python 3.5 or later.
####
import argparse
import getpass
import logging
import tableauserverclient as TSC
def handle_run(server, args):
tas... | ####
# This script demonstrates how to use the Tableau Server Client
# to query extract refresh tasks and run them as needed.
#
# To run the script, you must have installed Python 3.5 or later.
####
import argparse
import getpass
import logging
import tableauserverclient as TSC
def handle_run(server, args):
tas... | en | null | 666 |
0044439.py | UPDATE_EVENTS = {
'ChangePassword', 'CreateAccessKey', 'CreateLoginProfile', 'CreateUser'
}
def rule(event):
return event.get(
'eventName') in UPDATE_EVENTS and not event.get('errorCode')
def dedup(event):
return event.get('userIdentity', {}).get('userName', '<UNKNOWN_USER>')
def title(event):... | UPDATE_EVENTS = {
'ChangePassword', 'CreateAccessKey', 'CreateLoginProfile', 'CreateUser'
}
def rule(event):
return event.get(
'eventName') in UPDATE_EVENTS and not event.get('errorCode')
def dedup(event):
return event.get('userIdentity', {}).get('userName', '<UNKNOWN_USER>')
def title(event):... | en | null | 149 |
0039240.py | # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | en | null | 564 |
0007216.py | # coding=utf-8
import json
import requests
import importlib # for .reload()
from globalvars import GlobalVars
import threading
# noinspection PyPackageRequirements
import websocket
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from datetime import datetime, time... | # coding=utf-8
import json
import requests
import importlib # for .reload()
from globalvars import GlobalVars
import threading
# noinspection PyPackageRequirements
import websocket
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from datetime import datetime, time... | en | null | 8,166 |
0020683.py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
im... | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
im... | en | null | 269 |
0037098.py | from toee import *
import char_class_utils
import char_editor
###################################################
def GetConditionName(): # used by API
return "Ranger"
# def GetSpellCasterConditionName():
# return "Ranger Spellcasting"
def GetCategory():
return "Core 3.5 Ed Classes"
def GetClassDefinitionFlags(... | from toee import *
import char_class_utils
import char_editor
###################################################
def GetConditionName(): # used by API
return "Ranger"
# def GetSpellCasterConditionName():
# return "Ranger Spellcasting"
def GetCategory():
return "Core 3.5 Ed Classes"
def GetClassDefinitionFlags(... | en | null | 1,203 |
0020616.py | # This module is automatically generated by autogen.sh. DO NOT EDIT.
from . import _OnPrem
class _Proxmox(_OnPrem):
_type = "proxmox"
_icon_dir = "resources/onprem/proxmox"
class Pve(_Proxmox):
_icon = "pve.png"
# Aliases
PVE = ProxmoxVE
| # This module is automatically generated by autogen.sh. DO NOT EDIT.
from . import _OnPrem
class _Proxmox(_OnPrem):
_type = "proxmox"
_icon_dir = "resources/onprem/proxmox"
class Pve(_Proxmox):
_icon = "pve.png"
# Aliases
PVE = ProxmoxVE
| en | null | 104 |
0042386.py | from storm.variables import Variable
from spans import *
__all__ = [
"RangeVariable",
"IntRangeVariable",
"FloatRangeVariable",
"DateRangeVariable",
"DateTimeRangeVariable"
]
class RangeVariable(Variable):
"""
Extension of standard variable class to handle conversion to and from Psycopg2
... | from storm.variables import Variable
from spans import *
__all__ = [
"RangeVariable",
"IntRangeVariable",
"FloatRangeVariable",
"DateRangeVariable",
"DateTimeRangeVariable"
]
class RangeVariable(Variable):
"""
Extension of standard variable class to handle conversion to and from Psycopg2
... | en | null | 275 |
0002992.py | #!/usr/bin/python
# Copyright 2017 Google Inc. 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 ... | #!/usr/bin/python
# Copyright 2017 Google Inc. 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 ... | en | null | 7,183 |
0005278.py | from functools import total_ordering
from django.db.migrations.state import ProjectState
from .exceptions import CircularDependencyError, NodeNotFoundError
@total_ordering
class Node:
"""
A single node in the migration graph. Contains direct links to adjacent
nodes in either direction.
"""
def _... | from functools import total_ordering
from django.db.migrations.state import ProjectState
from .exceptions import CircularDependencyError, NodeNotFoundError
@total_ordering
class Node:
"""
A single node in the migration graph. Contains direct links to adjacent
nodes in either direction.
"""
def _... | en | null | 3,223 |
0011886.py | # 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 the... | # 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 the... | en | null | 1,863 |
0037803.py | #!/usr/bin/env python
from Utils.WAAgentUtil import waagent
import Utils.HandlerUtil as Util
ExtensionShortName = "SampleExtension"
def main():
#Global Variables definition
waagent.LoggerInit('/var/log/waagent.log','/dev/stdout')
waagent.Log("%s started to handle." %(ExtensionShortName))
operation =... | #!/usr/bin/env python
from Utils.WAAgentUtil import waagent
import Utils.HandlerUtil as Util
ExtensionShortName = "SampleExtension"
def main():
#Global Variables definition
waagent.LoggerInit('/var/log/waagent.log','/dev/stdout')
waagent.Log("%s started to handle." %(ExtensionShortName))
operation =... | en | null | 225 |
0018719.py | """
SPDX-License-Identifier: MIT
Copyright (c) 2021, SCANOSS
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, c... | """
SPDX-License-Identifier: MIT
Copyright (c) 2021, SCANOSS
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, c... | en | null | 2,004 |
0038368.py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | en | null | 1,991 |
0017070.py | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/gaogaotiantian/viztracer/blob/master/NOTICE.txt
from contextlib import redirect_stdout
import io
from .cmdline_tmpl import CmdlineTmpl
from viztracer import VizTracer
from viztracer.vizplugin import VizPl... | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/gaogaotiantian/viztracer/blob/master/NOTICE.txt
from contextlib import redirect_stdout
import io
from .cmdline_tmpl import CmdlineTmpl
from viztracer import VizTracer
from viztracer.vizplugin import VizPl... | en | null | 809 |
0010263.py | # coding:utf-8
import logging
from base64 import b64encode
import regex as re
import six
from flanker import _email
from flanker.mime.message import charsets, errors
_log = logging.getLogger(__name__)
_RE_FOLDING_WHITE_SPACES = re.compile(r"(?:\n\r?|\r\n?)")
# This spec refers to http://tools.ietf.org/html/rfc2047... | # coding:utf-8
import logging
from base64 import b64encode
import regex as re
import six
from flanker import _email
from flanker.mime.message import charsets, errors
_log = logging.getLogger(__name__)
_RE_FOLDING_WHITE_SPACES = re.compile(r"(?:\n\r?|\r\n?)")
# This spec refers to http://tools.ietf.org/html/rfc2047... | en | null | 1,392 |
0023020.py | # Copyright 2017-2021 TensorHub, 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 agreed to in writ... | # Copyright 2017-2021 TensorHub, 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 agreed to in writ... | en | null | 602 |
0031361.py | from os import path
from pathlib import Path as path_lib
import json
class LanguageManager(object):
def __init__(self):
self._path_to_language_file = 'config/languageConfig.json'
def get_languages(self):
languages = []
language_file_path = path.join(
path.dirname(path.... | from os import path
from pathlib import Path as path_lib
import json
class LanguageManager(object):
def __init__(self):
self._path_to_language_file = 'config/languageConfig.json'
def get_languages(self):
languages = []
language_file_path = path.join(
path.dirname(path.... | en | null | 221 |
0017151.py | #!/afs/bx.psu.edu/project/pythons/linux-i686-ucs4/bin/python2.7
"""
'Tile' the blocks of a maf file over each of a set of intervals. The
highest scoring block that covers any part of a region will be used, and
pieces not covered by any block filled with "-" or optionally "*". The list
of species to tile is specified ... | #!/afs/bx.psu.edu/project/pythons/linux-i686-ucs4/bin/python2.7
"""
'Tile' the blocks of a maf file over each of a set of intervals. The
highest scoring block that covers any part of a region will be used, and
pieces not covered by any block filled with "-" or optionally "*". The list
of species to tile is specified ... | en | null | 1,436 |
0004478.py | import json
import tempfile
import time
from collections import defaultdict
from os import path, remove
import numpy as np
import torch
import torch.distributed as dist
from PIL import Image
from pycocotools.coco import COCO as _COCO
from pycocotools.cocoeval import COCOeval
from pycocotools.mask import encode as mask... | import json
import tempfile
import time
from collections import defaultdict
from os import path, remove
import numpy as np
import torch
import torch.distributed as dist
from PIL import Image
from pycocotools.coco import COCO as _COCO
from pycocotools.cocoeval import COCOeval
from pycocotools.mask import encode as mask... | en | null | 2,505 |
0025666.py | """Utility functions shared across tasks."""
import numpy as np
import matplotlib as mpl
# For headless environments
mpl.use('Agg') # NOQA
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from rastervision.common.utils import plot_img_row
def predict_x(x, model):
batch_x = np.expand_dims(x, ... | """Utility functions shared across tasks."""
import numpy as np
import matplotlib as mpl
# For headless environments
mpl.use('Agg') # NOQA
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from rastervision.common.utils import plot_img_row
def predict_x(x, model):
batch_x = np.expand_dims(x, ... | en | null | 1,470 |
0038891.py | from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
from django.forms.utils import flatatt
import logging
import os
import os.path
import posixpath
from ..util import crc32, getdefaultattr
from ..util import log
from .base import BaseProvider
######################################... | from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
from django.forms.utils import flatatt
import logging
import os
import os.path
import posixpath
from ..util import crc32, getdefaultattr
from ..util import log
from .base import BaseProvider
######################################... | en | null | 2,153 |
0012926.py | """
Example service that prints out http context.
"""
import time
import requests
from ray import serve
from ray.serve.utils import pformat_color_json
def echo(flask_request):
return "hello " + flask_request.args.get("name", "serve!")
serve.init()
serve.create_backend("echo:v1", echo)
serve.create_endpoint(... | """
Example service that prints out http context.
"""
import time
import requests
from ray import serve
from ray.serve.utils import pformat_color_json
def echo(flask_request):
return "hello " + flask_request.args.get("name", "serve!")
serve.init()
serve.create_backend("echo:v1", echo)
serve.create_endpoint(... | en | null | 186 |
0026776.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import copy
import logging
import typing
from typing import Dict, Text, Any, Optional, Iterator
from typing import List
logger = logging.getLogger(__name__)
if typing... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import copy
import logging
import typing
from typing import Dict, Text, Any, Optional, Iterator
from typing import List
logger = logging.getLogger(__name__)
if typing... | en | null | 1,358 |
0000808.py | # 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 t... | # 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 t... | en | null | 5,126 |
0006082.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import copy
import logging
import os
import torch
from caffe2.proto import caffe2_pb2
from torch import nn
from detectron2.config import CfgNode as CN
from .caffe2_export import export_caffe2_detection_model
from .caffe2_export import export_onnx... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import copy
import logging
import os
import torch
from caffe2.proto import caffe2_pb2
from torch import nn
from detectron2.config import CfgNode as CN
from .caffe2_export import export_caffe2_detection_model
from .caffe2_export import export_onnx... | en | null | 2,810 |
0018027.py | # MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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, ... | # MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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, ... | en | null | 2,030 |
0049999.py | import copy
from PyQt5.QtWidgets import (QDialog, QLineEdit, QTextEdit, QVBoxLayout, QLabel,
QWidget, QHBoxLayout, QComboBox)
from btchip.btchip import BTChipException
from electrum.gui.qt.util import PasswordLineEdit
from electrum.i18n import _
from electrum import constants, bitcoin
f... | import copy
from PyQt5.QtWidgets import (QDialog, QLineEdit, QTextEdit, QVBoxLayout, QLabel,
QWidget, QHBoxLayout, QComboBox)
from btchip.btchip import BTChipException
from electrum.gui.qt.util import PasswordLineEdit
from electrum.i18n import _
from electrum import constants, bitcoin
f... | en | null | 2,174 |
0008313.py | # Copyright (c) 2015 CensoredUsername
# This module provides tools for safely analyizing pickle files programmatically
import sys
PY3 = sys.version_info >= (3, 0)
PY2 = not PY3
import types
import pickle
import struct
if PY3:
from io import BytesIO as StringIO
else:
from cStringIO import StringIO
__all__ ... | # Copyright (c) 2015 CensoredUsername
# This module provides tools for safely analyizing pickle files programmatically
import sys
PY3 = sys.version_info >= (3, 0)
PY2 = not PY3
import types
import pickle
import struct
if PY3:
from io import BytesIO as StringIO
else:
from cStringIO import StringIO
__all__ ... | en | null | 7,175 |
0020892.py | #!/usr/bin/env python3
import argparse
import json
import os
import subprocess
import re
import sys
import yaml
# Color codes for colored output!
BOLD = subprocess.check_output(['tput', 'bold']).decode()
GREEN = subprocess.check_output(['tput', 'setaf', '2']).decode()
NC = subprocess.check_output(['tput', 'sgr0']).de... | #!/usr/bin/env python3
import argparse
import json
import os
import subprocess
import re
import sys
import yaml
# Color codes for colored output!
BOLD = subprocess.check_output(['tput', 'bold']).decode()
GREEN = subprocess.check_output(['tput', 'setaf', '2']).decode()
NC = subprocess.check_output(['tput', 'sgr0']).de... | en | null | 3,046 |
0035832.py | # Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
class JohnDoe:
FIRST_NAME = 'John'
LAST_NAME = 'Doe'
ADDRESS = '9805 Cambridge Street'
CITY = 'NY'
STATE = 'Brooklyn'
ZIP_CODE = '11235'
PHONE = '718-437-9185'
USERNAME = 'johndoe'
PASSWOR... | # Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
class JohnDoe:
FIRST_NAME = 'John'
LAST_NAME = 'Doe'
ADDRESS = '9805 Cambridge Street'
CITY = 'NY'
STATE = 'Brooklyn'
ZIP_CODE = '11235'
PHONE = '718-437-9185'
USERNAME = 'johndoe'
PASSWOR... | en | null | 477 |
0011856.py | #!/usr/bin/env python
#
# File: llnms-scan-network.py
# Author: Marvin Smith
# Date: 6/13/2015
#
# Purpose: Scan LLNMS networks
#
__author__ = 'Marvin Smith'
# Python Libraries
import argparse, os, sys
# LLNMS Libraries
if os.environ['LLNMS_HOME'] is not None:
sys.path.append(os.environ['L... | #!/usr/bin/env python
#
# File: llnms-scan-network.py
# Author: Marvin Smith
# Date: 6/13/2015
#
# Purpose: Scan LLNMS networks
#
__author__ = 'Marvin Smith'
# Python Libraries
import argparse, os, sys
# LLNMS Libraries
if os.environ['LLNMS_HOME'] is not None:
sys.path.append(os.environ['L... | en | null | 1,056 |
0012324.py | #!/usr/bin/env
# -*- coding: utf-8 -*-
# Copyright (C) Victor M. Mendiola Lau - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Written by Victor M. Mendiola Lau <ryuzakyl@gmail.com>, February 2017
import os
import scipy.io as sio
import... | #!/usr/bin/env
# -*- coding: utf-8 -*-
# Copyright (C) Victor M. Mendiola Lau - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Written by Victor M. Mendiola Lau <ryuzakyl@gmail.com>, February 2017
import os
import scipy.io as sio
import... | en | null | 440 |
0048288.py | ''' device.py
'''
from transitions import Machine
from core.clock import ClockReference
from core.message_router import MessageRouter
class Device:
''' Device:
A base class that all accelerator components inherit from.
A device requires a clock-reference and a message-router (to communicate)
Args:
... | ''' device.py
'''
from transitions import Machine
from core.clock import ClockReference
from core.message_router import MessageRouter
class Device:
''' Device:
A base class that all accelerator components inherit from.
A device requires a clock-reference and a message-router (to communicate)
Args:
... | en | null | 351 |
0046825.py | # -*- coding: utf-8 -*-
import os
import qiniu
from qiniu import Auth
from gevent import monkey
from gevent.pool import Pool
from config import config
monkey.patch_socket()
def down(token, key, localfile, mime_type, delete=False):
ret, info = qiniu.put_file(
token, key, localfile,
... | # -*- coding: utf-8 -*-
import os
import qiniu
from qiniu import Auth
from gevent import monkey
from gevent.pool import Pool
from config import config
monkey.patch_socket()
def down(token, key, localfile, mime_type, delete=False):
ret, info = qiniu.put_file(
token, key, localfile,
... | en | null | 722 |
0026033.py | import unittest
import numpy as np
from megnet.utils.general import expand_1st, to_list, fast_label_binarize
class TestGeneralUtils(unittest.TestCase):
def test_expand_dim(self):
x = np.array([1, 2, 3])
self.assertListEqual(list(expand_1st(x).shape), [1, 3])
def test_to_list(self):
x... | import unittest
import numpy as np
from megnet.utils.general import expand_1st, to_list, fast_label_binarize
class TestGeneralUtils(unittest.TestCase):
def test_expand_dim(self):
x = np.array([1, 2, 3])
self.assertListEqual(list(expand_1st(x).shape), [1, 3])
def test_to_list(self):
x... | en | null | 321 |
0036990.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved
#
################################################################################
"""
File: source/encoders/embedder.py
"""
import l... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved
#
################################################################################
"""
File: source/encoders/embedder.py
"""
import l... | en | null | 305 |
0031473.py | # Ensure we get the local copy of tornado instead of what's on the standard path
import os
import sys
import time
sys.path.insert(0, os.path.abspath(".."))
import tornado
master_doc = "index"
project = "Tornado"
copyright = "2009-%s, The Tornado Authors" % time.strftime("%Y")
version = release = tornado.version
lan... | # Ensure we get the local copy of tornado instead of what's on the standard path
import os
import sys
import time
sys.path.insert(0, os.path.abspath(".."))
import tornado
master_doc = "index"
project = "Tornado"
copyright = "2009-%s, The Tornado Authors" % time.strftime("%Y")
version = release = tornado.version
lan... | en | null | 1,005 |
0008285.py | import os
import sys
import importlib
from unittest import mock
import importlib_metadata
import pytest
import mlflow
from mlflow.utils.requirements_utils import (
_is_comment,
_is_empty,
_is_requirements_file,
_strip_inline_comment,
_join_continued_lines,
_parse_requirements,
_prune_packa... | import os
import sys
import importlib
from unittest import mock
import importlib_metadata
import pytest
import mlflow
from mlflow.utils.requirements_utils import (
_is_comment,
_is_empty,
_is_requirements_file,
_strip_inline_comment,
_join_continued_lines,
_parse_requirements,
_prune_packa... | en | null | 3,001 |
0016824.py | import csv
import numpy as np
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--tissue', type=str, default='Brain - Cortex', metavar='tissue',
help='type of tissue filtered for')
parser.add_argument('--save-to', type=str,
default='../../data/gtex_processe... | import csv
import numpy as np
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--tissue', type=str, default='Brain - Cortex', metavar='tissue',
help='type of tissue filtered for')
parser.add_argument('--save-to', type=str,
default='../../data/gtex_processe... | en | null | 1,010 |
0017474.py | """
This module contains all forms used in the teacher Views
"""
from django import forms
from django.forms import HiddenInput, MultipleHiddenInput
from django.urls import reverse_lazy
from django_addanother.widgets import AddAnotherWidgetWrapper
from django_select2.forms import ModelSelect2MultipleWidget
from stea... | """
This module contains all forms used in the teacher Views
"""
from django import forms
from django.forms import HiddenInput, MultipleHiddenInput
from django.urls import reverse_lazy
from django_addanother.widgets import AddAnotherWidgetWrapper
from django_select2.forms import ModelSelect2MultipleWidget
from stea... | en | null | 445 |
0013953.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from corral import run
from ..models import PawprintXTile
class PreparePawprintToSync(run.Step):
model = PawprintXTile
conditions = [
PawprintXTile.status == "raw",
PawprintXTile.tile.has(status="loaded"),
PawprintXTile.pawprint.has(stat... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from corral import run
from ..models import PawprintXTile
class PreparePawprintToSync(run.Step):
model = PawprintXTile
conditions = [
PawprintXTile.status == "raw",
PawprintXTile.tile.has(status="loaded"),
PawprintXTile.pawprint.has(stat... | en | null | 144 |
0032118.py | """reindex_outcomes
Revision ID: 61a1763b9c8d
Revises: 340d5cc7e806
Create Date: 2019-08-09 12:47:22.165013
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "61a1763b9c8d"
down_revision = "340d5cc7e806"
branch_labels = ()
depends_on = None
def upgrade():
#... | """reindex_outcomes
Revision ID: 61a1763b9c8d
Revises: 340d5cc7e806
Create Date: 2019-08-09 12:47:22.165013
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "61a1763b9c8d"
down_revision = "340d5cc7e806"
branch_labels = ()
depends_on = None
def upgrade():
#... | en | null | 352 |
0049773.py | import pytest
import sys
import os
import time
os.environ['SENTINEL_ENV'] = 'test'
os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__), '../../test_sentinel.conf'))
sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '../../../lib')))
import misc
import config
fr... | import pytest
import sys
import os
import time
os.environ['SENTINEL_ENV'] = 'test'
os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__), '../../test_sentinel.conf'))
sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '../../../lib')))
import misc
import config
fr... | en | null | 6,421 |
0003297.py | from logging import debug, info, warning, error, exception
import re
from datetime import datetime, timedelta
from .. import AbstractServiceHandler
from data.models import Episode, UnprocessedStream
class ServiceHandler(AbstractServiceHandler):
_show_url = "http://crunchyroll.com/{id}"
_show_re = re.compile("crunch... | from logging import debug, info, warning, error, exception
import re
from datetime import datetime, timedelta
from .. import AbstractServiceHandler
from data.models import Episode, UnprocessedStream
class ServiceHandler(AbstractServiceHandler):
_show_url = "http://crunchyroll.com/{id}"
_show_re = re.compile("crunch... | en | null | 2,290 |
0030954.py | """
rock.py
Zhiang Chen, Feb 2020
data class for mask rcnn
"""
import os
import numpy as np
import torch
from PIL import Image
import pickle
import matplotlib.pyplot as plt
"""
./datasets/
Rock/
data/
0_8.npy
0_9.npy
1_4.npy
...
"""
class Dataset(object):
... | """
rock.py
Zhiang Chen, Feb 2020
data class for mask rcnn
"""
import os
import numpy as np
import torch
from PIL import Image
import pickle
import matplotlib.pyplot as plt
"""
./datasets/
Rock/
data/
0_8.npy
0_9.npy
1_4.npy
...
"""
class Dataset(object):
... | en | null | 1,676 |
0023594.py | # Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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 a... | # Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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 a... | en | null | 1,862 |
0022304.py | __author__ = 'Jan Pecinovsky'
from opengrid_dev.config import Config
config = Config()
import os
import sys
import json
import jsonpickle
import datetime as dt
import pandas as pd
from requests.exceptions import HTTPError
import warnings
from tqdm import tqdm
# compatibility with py3
if sys.version_info.major >= 3:... | __author__ = 'Jan Pecinovsky'
from opengrid_dev.config import Config
config = Config()
import os
import sys
import json
import jsonpickle
import datetime as dt
import pandas as pd
from requests.exceptions import HTTPError
import warnings
from tqdm import tqdm
# compatibility with py3
if sys.version_info.major >= 3:... | en | null | 4,697 |
0044820.py | #!/bin/python
# helper script to regenerate helm chart file: partial of charts/cert-management/templates/deployment.yaml
import re
options = """
cert-class
cert-target-class
controllers
cpuprofile
default-issuer
default-issuer-domain-ranges
disable-namespace-restriction
dns
dns-namespace
dns-owner-id
dns.id
help
in... | #!/bin/python
# helper script to regenerate helm chart file: partial of charts/cert-management/templates/deployment.yaml
import re
options = """
cert-class
cert-target-class
controllers
cpuprofile
default-issuer
default-issuer-domain-ranges
disable-namespace-restriction
dns
dns-namespace
dns-owner-id
dns.id
help
in... | en | null | 712 |
0044649.py | import warnings
import numpy as np
from joblib import Parallel, delayed
from sklearn.base import MetaEstimatorMixin, clone
from sklearn.multiclass import OneVsRestClassifier as _SKOvR
from sklearn.multiclass import _ConstantPredictor
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import LabelBinarize... | import warnings
import numpy as np
from joblib import Parallel, delayed
from sklearn.base import MetaEstimatorMixin, clone
from sklearn.multiclass import OneVsRestClassifier as _SKOvR
from sklearn.multiclass import _ConstantPredictor
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import LabelBinarize... | en | null | 740 |
0027794.py | from office365.runtime.client_value import ClientValue
class SPSiteCreationRequest(ClientValue):
def __init__(self, title, url, owner=None):
super(SPSiteCreationRequest, self).__init__()
self.Title = title
self.Url = url
self.WebTemplate = "SITEPAGEPUBLISHING#0"
self.Owner... | from office365.runtime.client_value import ClientValue
class SPSiteCreationRequest(ClientValue):
def __init__(self, title, url, owner=None):
super(SPSiteCreationRequest, self).__init__()
self.Title = title
self.Url = url
self.WebTemplate = "SITEPAGEPUBLISHING#0"
self.Owner... | en | null | 305 |
0002011.py | import numpy as np
import random
from dataLoader.batch import batcher
from transformers import BertTokenizerFast, ElectraTokenizerFast
from configs.WNUT_configs import *
from utils.ml_utils import *
from utils.data_utils import *
from utils.metric_utils import *
import argparse
from tqdm import tqdm
from pathlib import... | import numpy as np
import random
from dataLoader.batch import batcher
from transformers import BertTokenizerFast, ElectraTokenizerFast
from configs.WNUT_configs import *
from utils.ml_utils import *
from utils.data_utils import *
from utils.metric_utils import *
import argparse
from tqdm import tqdm
from pathlib import... | en | null | 5,720 |
0018824.py | # Copyright (c) 2020 The Khronos Group 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 agreed ... | # Copyright (c) 2020 The Khronos Group 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 agreed ... | en | null | 2,492 |
0025755.py | from datetime import datetime, timedelta
import iso8601
from celery.exceptions import Retry
from flask import current_app, json
from notifications_utils.statsd_decorators import statsd
from sqlalchemy.orm.exc import NoResultFound
from app import notify_celery, statsd_client
from app.clients.email.aws_ses import get_a... | from datetime import datetime, timedelta
import iso8601
from celery.exceptions import Retry
from flask import current_app, json
from notifications_utils.statsd_decorators import statsd
from sqlalchemy.orm.exc import NoResultFound
from app import notify_celery, statsd_client
from app.clients.email.aws_ses import get_a... | en | null | 893 |
0025408.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | en | null | 255 |
0036475.py | # ===============================================================================
# Copyright 2015 Jake Ross
#
# 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... | # ===============================================================================
# Copyright 2015 Jake Ross
#
# 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... | en | null | 4,111 |
0016340.py | from win_unc.errors import InvalidUncPathError
from win_unc.cleaners import clean_unc_path
from win_unc.unc_credentials import get_creds_from_string
from win_unc.validators import is_valid_unc_path
class UncDirectory(object):
"""
Represents a UNC directory on Windows. A UNC directory is a path and optionally ... | from win_unc.errors import InvalidUncPathError
from win_unc.cleaners import clean_unc_path
from win_unc.unc_credentials import get_creds_from_string
from win_unc.validators import is_valid_unc_path
class UncDirectory(object):
"""
Represents a UNC directory on Windows. A UNC directory is a path and optionally ... | en | null | 1,393 |
0045480.py | # -*- coding: utf-8 -*-
"""Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, 2017, 2018, 2019, 2020 Caleb Bell
<Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (t... | # -*- coding: utf-8 -*-
"""Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, 2017, 2018, 2019, 2020 Caleb Bell
<Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (t... | en | null | 2,886 |
0044283.py | from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
import requests
from datetime import datetime, timedelta, timezone
import os
from os.path import join, dirname
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), "../../", '.env')
load_dotenv(dotenv_path)
RASPI_URL ... | from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
import requests
from datetime import datetime, timedelta, timezone
import os
from os.path import join, dirname
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), "../../", '.env')
load_dotenv(dotenv_path)
RASPI_URL ... | en | null | 310 |
0041631.py | from django import template
from ..models import Post,Category
register = template.Library()
@register.simple_tag
def get_recent_posts(num=5):
return Post.objects.all().order_by('-created_time')[:num]
@register.simple_tag
def archives():
return Post.objects.dates('created_time', 'month', order='DESC')
@register.s... | from django import template
from ..models import Post,Category
register = template.Library()
@register.simple_tag
def get_recent_posts(num=5):
return Post.objects.all().order_by('-created_time')[:num]
@register.simple_tag
def archives():
return Post.objects.dates('created_time', 'month', order='DESC')
@register.s... | en | null | 116 |
0022660.py | import numpy as np
from neupy import layers
from base import BaseTestCase
class ReshapeLayerTestCase(BaseTestCase):
def test_reshape_layer_1d_shape(self):
x = np.random.random((5, 4, 3, 2, 1))
input_layer = layers.Input((4, 3, 2, 1))
reshape_layer = layers.Reshape()
input_layer ... | import numpy as np
from neupy import layers
from base import BaseTestCase
class ReshapeLayerTestCase(BaseTestCase):
def test_reshape_layer_1d_shape(self):
x = np.random.random((5, 4, 3, 2, 1))
input_layer = layers.Input((4, 3, 2, 1))
reshape_layer = layers.Reshape()
input_layer ... | en | null | 261 |
0008246.py | # -*- coding: utf-8 -*-
"""
Datary python sdk Datasets test file
"""
import mock
from datary.test.test_datary import DataryTestCase
from datary.test.mock_requests import MockRequestResponse
class DataryDatasetsTestCase(DataryTestCase):
"""
DataryDatasets Test case
"""
@mock.patch('datary.requests.re... | # -*- coding: utf-8 -*-
"""
Datary python sdk Datasets test file
"""
import mock
from datary.test.test_datary import DataryTestCase
from datary.test.mock_requests import MockRequestResponse
class DataryDatasetsTestCase(DataryTestCase):
"""
DataryDatasets Test case
"""
@mock.patch('datary.requests.re... | en | null | 2,320 |
0008710.py | '''
SIGNUS V1 post API
'''
from flask import g
from app.api.signus_v1 import signus_v1 as api
from app.api.decorators import timer, login_required, login_optional
from app.controllers.post import (post_like,
post_unlike,
post_view)
@api.route("/post/... | '''
SIGNUS V1 post API
'''
from flask import g
from app.api.signus_v1 import signus_v1 as api
from app.api.decorators import timer, login_required, login_optional
from app.controllers.post import (post_like,
post_unlike,
post_view)
@api.route("/post/... | en | null | 406 |
0031000.py | import logging
from pathlib import Path
from typing import List, Optional
from great_expectations.datasource.data_connector.inferred_asset_file_path_data_connector import (
InferredAssetFilePathDataConnector,
)
from great_expectations.datasource.data_connector.util import (
get_filesystem_one_level_directory_g... | import logging
from pathlib import Path
from typing import List, Optional
from great_expectations.datasource.data_connector.inferred_asset_file_path_data_connector import (
InferredAssetFilePathDataConnector,
)
from great_expectations.datasource.data_connector.util import (
get_filesystem_one_level_directory_g... | en | null | 1,021 |
0049143.py | # -*- coding: utf-8 -*-
"""
Tests the 'read_fwf' function in parsers.py. This
test suite is independent of the others because the
engine is set to 'python-fwf' internally.
"""
from datetime import datetime
import numpy as np
import pytest
import pandas.compat as compat
from pandas.compat import BytesIO, StringIO
i... | # -*- coding: utf-8 -*-
"""
Tests the 'read_fwf' function in parsers.py. This
test suite is independent of the others because the
engine is set to 'python-fwf' internally.
"""
from datetime import datetime
import numpy as np
import pytest
import pandas.compat as compat
from pandas.compat import BytesIO, StringIO
i... | en | null | 6,671 |
0049729.py | from .. dynamic_array.array import Array
class Stack:
def __init__(self, cap=float('inf')):
self.rep = Array()
self.cap = cap
self.top = 0
def __repr__(self):
return repr(self.rep)
def push(self, x):
if self.top >= self.cap:
raise TypeError('Overflow: ... | from .. dynamic_array.array import Array
class Stack:
def __init__(self, cap=float('inf')):
self.rep = Array()
self.cap = cap
self.top = 0
def __repr__(self):
return repr(self.rep)
def push(self, x):
if self.top >= self.cap:
raise TypeError('Overflow: ... | en | null | 194 |
0028689.py | """Template tags for anchors app"""
try:
from urlparse import urlparse
except ImportError: # Python 3
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from django import template
from django.contrib.sites.models import Site
from django.utils.safestring import mark_safe
from django.utils.html i... | """Template tags for anchors app"""
try:
from urlparse import urlparse
except ImportError: # Python 3
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from django import template
from django.contrib.sites.models import Site
from django.utils.safestring import mark_safe
from django.utils.html i... | en | null | 618 |
0024525.py | import tensorflow as tf
############################################################
# Miscellenous Graph Functions
############################################################
def trim_zeros_graph(boxes, name='trim_zeros'):
"""Often boxes are represented with matrices of shape [N, 4] and
are padded with zero... | import tensorflow as tf
############################################################
# Miscellenous Graph Functions
############################################################
def trim_zeros_graph(boxes, name='trim_zeros'):
"""Often boxes are represented with matrices of shape [N, 4] and
are padded with zero... | en | null | 2,036 |
0013802.py | """A modified image folder class
We modify the official PyTorch image folder (https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py)
so that this class can load images from both current directory and its subdirectories.
"""
import torch.utils.data as data
from PIL import Image
import os
import... | """A modified image folder class
We modify the official PyTorch image folder (https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py)
so that this class can load images from both current directory and its subdirectories.
"""
import torch.utils.data as data
from PIL import Image
import os
import... | en | null | 753 |
0006571.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | en | null | 402 |
0028359.py | import json
import uuid
from collections import OrderedDict
from ... import path
from ...iterutils import first
__all__ = ['SlnBuilder', 'SlnElement', 'SlnVariable', 'Solution', 'UuidMap']
class SlnElement:
def __init__(self, name, arg=None, value=None):
if (arg is None) != (value is None):
... | import json
import uuid
from collections import OrderedDict
from ... import path
from ...iterutils import first
__all__ = ['SlnBuilder', 'SlnElement', 'SlnVariable', 'Solution', 'UuidMap']
class SlnElement:
def __init__(self, name, arg=None, value=None):
if (arg is None) != (value is None):
... | en | null | 1,715 |
0018541.py | #!/usr/bin/env python
"""
Created on Fri Jun 19 10:46:32 2015
@author: ruizca
"""
import argparse
import logging
import subprocess
from itertools import count
from pathlib import Path
from astropy.coordinates.sky_coordinate import SkyCoord
from astropy.table import Table
from astropy.units import UnitTypeError
from ... | #!/usr/bin/env python
"""
Created on Fri Jun 19 10:46:32 2015
@author: ruizca
"""
import argparse
import logging
import subprocess
from itertools import count
from pathlib import Path
from astropy.coordinates.sky_coordinate import SkyCoord
from astropy.table import Table
from astropy.units import UnitTypeError
from ... | en | null | 1,818 |
0023850.py | """Contains a class which extracts the needed arguments of an arbitrary
methode/function and wraps them for future usage. E.g correctly choosing
the needed arguments and passing them on to the original function.
"""
import inspect
import copy
import torch
from ..problem.spaces.points import Points
class UserFunct... | """Contains a class which extracts the needed arguments of an arbitrary
methode/function and wraps them for future usage. E.g correctly choosing
the needed arguments and passing them on to the original function.
"""
import inspect
import copy
import torch
from ..problem.spaces.points import Points
class UserFunct... | en | null | 2,798 |
0041616.py | """Amazon NeptuneClient Module."""
import logging
from typing import Any, Dict, List, Optional
import boto3
import requests
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from gremlin_python.driver import client
from SPARQLWrapper import SPARQLWrapper
from awswrangler import exception... | """Amazon NeptuneClient Module."""
import logging
from typing import Any, Dict, List, Optional
import boto3
import requests
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from gremlin_python.driver import client
from SPARQLWrapper import SPARQLWrapper
from awswrangler import exception... | en | null | 2,549 |
0026693.py | # Copyright (C) 2020 University of Oxford
#
# 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 t... | # Copyright (C) 2020 University of Oxford
#
# 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 t... | en | null | 380 |
0002257.py | import re
import sys
import inspect
_py2 = sys.version_info[0] == 2
_py3 = sys.version_info[0] == 3
# noinspection PyPep8Naming
class route(object):
def __init__(self, rule, **options):
"""
Class Initializer - This will only execute if using BottleCBV's original route() style.
"""
... | import re
import sys
import inspect
_py2 = sys.version_info[0] == 2
_py3 = sys.version_info[0] == 3
# noinspection PyPep8Naming
class route(object):
def __init__(self, rule, **options):
"""
Class Initializer - This will only execute if using BottleCBV's original route() style.
"""
... | en | null | 2,636 |
0039829.py | import numpy as np
import tensorflow as tf
from tensorflow.python.keras import models, layers
from tensorflow.python.keras.datasets import mnist
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
import random
import json
(train_images, train_labels), (test_images, test_labels) = mnis... | import numpy as np
import tensorflow as tf
from tensorflow.python.keras import models, layers
from tensorflow.python.keras.datasets import mnist
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
import random
import json
(train_images, train_labels), (test_images, test_labels) = mnis... | en | null | 1,302 |
0019785.py | from flask import render_template, send_from_directory, request, jsonify
from app import app
import hashlib, uuid
import game
from app import __config__ as config
def compare_password(password, correct_hash):
"""
Compares password with hash
"""
hashed_password = hashlib.sha512(password).hexdigest()
... | from flask import render_template, send_from_directory, request, jsonify
from app import app
import hashlib, uuid
import game
from app import __config__ as config
def compare_password(password, correct_hash):
"""
Compares password with hash
"""
hashed_password = hashlib.sha512(password).hexdigest()
... | en | null | 425 |
0049638.py | import json
from copy import deepcopy
from typing import Optional
import openai
from openai import api_requestor, util
from openai.openai_response import OpenAIResponse
from openai.util import ApiType
class OpenAIObject(dict):
api_base_override = None
def __init__(
self,
id=None,
api... | import json
from copy import deepcopy
from typing import Optional
import openai
from openai import api_requestor, util
from openai.openai_response import OpenAIResponse
from openai.util import ApiType
class OpenAIObject(dict):
api_base_override = None
def __init__(
self,
id=None,
api... | en | null | 2,469 |
0016043.py | import numpy as np
import matplotlib.pyplot as plt
import scipy.sparse as sparse
import sys
sys.path.append("..")
from Laplacian import *
def getCirculantAdj(N, lags):
#Setup circular parts
I = range(N)*(len(lags)+2)
J = range(1, N+1) + range(-1, N-1)
J[N-1] = 0
J[N] = N-1
for lag in lags:
... | import numpy as np
import matplotlib.pyplot as plt
import scipy.sparse as sparse
import sys
sys.path.append("..")
from Laplacian import *
def getCirculantAdj(N, lags):
#Setup circular parts
I = range(N)*(len(lags)+2)
J = range(1, N+1) + range(-1, N-1)
J[N-1] = 0
J[N] = N-1
for lag in lags:
... | en | null | 990 |
0031951.py | # coding=utf-8
# Copyright 2022 The Reach ML Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | # coding=utf-8
# Copyright 2022 The Reach ML Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | en | null | 969 |
0003092.py | from django.db import models
from django_encrypted_json.fields import EncryptedValueJsonField
# Create your models here.
class TestModel(models.Model):
json = EncryptedValueJsonField(default={})
optional_json = EncryptedValueJsonField(blank=True, null=True)
partial_encrypt = EncryptedValueJsonField(
... | from django.db import models
from django_encrypted_json.fields import EncryptedValueJsonField
# Create your models here.
class TestModel(models.Model):
json = EncryptedValueJsonField(default={})
optional_json = EncryptedValueJsonField(blank=True, null=True)
partial_encrypt = EncryptedValueJsonField(
... | en | null | 136 |
0026653.py | from typing import Dict, Optional
from ciphey.iface import Checker, Config, ParamSpec, registry
@registry.register
class HumanChecker(Checker[str]):
@staticmethod
def getParams() -> Optional[Dict[str, ParamSpec]]:
pass
def check(self, text: str) -> Optional[str]:
with self._config().paus... | from typing import Dict, Optional
from ciphey.iface import Checker, Config, ParamSpec, registry
@registry.register
class HumanChecker(Checker[str]):
@staticmethod
def getParams() -> Optional[Dict[str, ParamSpec]]:
pass
def check(self, text: str) -> Optional[str]:
with self._config().paus... | en | null | 204 |
0007034.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Imports --------------------------------------------------------------------------... | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Imports --------------------------------------------------------------------------... | en | null | 978 |
0027169.py | #!/usr/bin/env python
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test NetCDF driver support.
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
###############################################################################
# Co... | #!/usr/bin/env python
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test NetCDF driver support.
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
###############################################################################
# Co... | en | null | 9,034 |
0039753.py | # coding: utf-8
"""
Seldon Deploy API
API to interact and manage the lifecycle of your machine learning models deployed through Seldon Deploy. # noqa: E501
OpenAPI spec version: v1alpha1
Contact: hello@seldon.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future... | # coding: utf-8
"""
Seldon Deploy API
API to interact and manage the lifecycle of your machine learning models deployed through Seldon Deploy. # noqa: E501
OpenAPI spec version: v1alpha1
Contact: hello@seldon.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future... | en | null | 328 |
0031510.py | import _plotly_utils.basevalidators
class CustomdataValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(
self, plotly_name="customdata", parent_name="choroplethmapbox", **kwargs
):
super(CustomdataValidator, self).__init__(
plotly_name=plotly_name,
... | import _plotly_utils.basevalidators
class CustomdataValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(
self, plotly_name="customdata", parent_name="choroplethmapbox", **kwargs
):
super(CustomdataValidator, self).__init__(
plotly_name=plotly_name,
... | en | null | 122 |
0007792.py | # voom_mode_org.py
# Last Modified: 2013-10-31
# VOoM -- Vim two-pane outliner, plugin for Python-enabled Vim 7.x
# Website: http://www.vim.org/scripts/script.php?script_id=2657
# Author: Vlad Irnov (vlad DOT irnov AT gmail DOT com)
# License: CC0, see http://creativecommons.org/publicdomain/zero/1.0/
"""
VOoM markup ... | # voom_mode_org.py
# Last Modified: 2013-10-31
# VOoM -- Vim two-pane outliner, plugin for Python-enabled Vim 7.x
# Website: http://www.vim.org/scripts/script.php?script_id=2657
# Author: Vlad Irnov (vlad DOT irnov AT gmail DOT com)
# License: CC0, see http://creativecommons.org/publicdomain/zero/1.0/
"""
VOoM markup ... | en | null | 647 |
0030055.py | """Tests for `InteractorFinder` class."""
import pandas as pd
from drugintfinder.finder import InteractorFinder
from .constants import MAPT, PROTEIN, PHOSPHORYLATION, CAUSAL
finder = InteractorFinder(symbol=MAPT, pmods=[PHOSPHORYLATION], edge=CAUSAL)
class TestInteractorFinder:
"""Tests for the InteractorFinde... | """Tests for `InteractorFinder` class."""
import pandas as pd
from drugintfinder.finder import InteractorFinder
from .constants import MAPT, PROTEIN, PHOSPHORYLATION, CAUSAL
finder = InteractorFinder(symbol=MAPT, pmods=[PHOSPHORYLATION], edge=CAUSAL)
class TestInteractorFinder:
"""Tests for the InteractorFinde... | en | null | 626 |
0020445.py | # Generated with CombinedLoadingApproach
#
from enum import Enum
from enum import auto
class CombinedLoadingApproach(Enum):
""""""
LRFD = auto()
WSD = auto()
def label(self):
if self == CombinedLoadingApproach.LRFD:
return "LRFD"
if self == CombinedLoadingApproach.WSD:
... | # Generated with CombinedLoadingApproach
#
from enum import Enum
from enum import auto
class CombinedLoadingApproach(Enum):
""""""
LRFD = auto()
WSD = auto()
def label(self):
if self == CombinedLoadingApproach.LRFD:
return "LRFD"
if self == CombinedLoadingApproach.WSD:
... | en | null | 96 |
0005880.py | from django.shortcuts import get_object_or_404
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, generics, views, exceptions
from rest_framework.response import Response
from core import models
from core.models.base import GameStatus
from service import serializers
from ... | from django.shortcuts import get_object_or_404
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, generics, views, exceptions
from rest_framework.response import Response
from core import models
from core.models.base import GameStatus
from service import serializers
from ... | en | null | 1,720 |
0042525.py | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Building()
result.template = "object/building/poi/shared_naboo_ruins_medium_3.iff"
result.attribute_template_id =... | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Building()
result.template = "object/building/poi/shared_naboo_ruins_medium_3.iff"
result.attribute_template_id =... | en | null | 147 |
0024224.py | from django.views.generic import FormView
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse_lazy
from contact.models import Contact, Newsletter
from contact.forms import ContactForm, NewsletterForm
class TwoFormView(FormView):
template_name = 'two_form.html'
form_cla... | from django.views.generic import FormView
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse_lazy
from contact.models import Contact, Newsletter
from contact.forms import ContactForm, NewsletterForm
class TwoFormView(FormView):
template_name = 'two_form.html'
form_cla... | en | null | 456 |
0016930.py | import torch as t
import torch.nn as nn
import torch.nn.functional as F
class MTRN(nn.Module):
def __init__(self, frame_count: int):
super().__init__()
self.frame_count = frame_count
self.fc1 = nn.Linear(256 * frame_count, 1024)
self.fc2 = nn.Linear(1024, 512)
... | import torch as t
import torch.nn as nn
import torch.nn.functional as F
class MTRN(nn.Module):
def __init__(self, frame_count: int):
super().__init__()
self.frame_count = frame_count
self.fc1 = nn.Linear(256 * frame_count, 1024)
self.fc2 = nn.Linear(1024, 512)
... | en | null | 1,415 |
0026983.py | from ROAR.planning_module.mission_planner.mission_planner import (
MissionPlanner,
)
from pathlib import Path
import logging
from typing import List, Optional
from ROAR.utilities_module.data_structures_models import Transform, Location, Rotation
from collections import deque
from ROAR.agent_module.agent import Agen... | from ROAR.planning_module.mission_planner.mission_planner import (
MissionPlanner,
)
from pathlib import Path
import logging
from typing import List, Optional
from ROAR.utilities_module.data_structures_models import Transform, Location, Rotation
from collections import deque
from ROAR.agent_module.agent import Agen... | en | null | 1,231 |
0009443.py | from django.contrib.auth.decorators import permission_required
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from .models import Book, Author, BookInstance, Genre
from django.views import generic
from django.views.generic.edit i... | from django.contrib.auth.decorators import permission_required
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from .models import Book, Author, BookInstance, Genre
from django.views import generic
from django.views.generic.edit i... | en | null | 1,423 |
0006694.py | # module solution.py
#
# Copyright (c) 2018 Rafael Reis
#
"""
solution module - Implements Solution, a class that describes a solution for the problem.
"""
__version__ = "1.0"
import copy
import sys
from random import shuffle
import numpy as np
def random(pctsp, start_size):
s = Solution(pctsp)
length = le... | # module solution.py
#
# Copyright (c) 2018 Rafael Reis
#
"""
solution module - Implements Solution, a class that describes a solution for the problem.
"""
__version__ = "1.0"
import copy
import sys
from random import shuffle
import numpy as np
def random(pctsp, start_size):
s = Solution(pctsp)
length = le... | en | null | 1,639 |
0009745.py | from abc import ABCMeta
from uuid import UUID
import jsonschema
from dateutil.parser import parse as dateparse
from uptimer.events import SCHEMATA_PATH
from uptimer.events.cache import schema_cache
from uptimer.helpers import to_bool, to_none
class EventDefinitionError(ValueError):
pass
class EventMeta(ABCMet... | from abc import ABCMeta
from uuid import UUID
import jsonschema
from dateutil.parser import parse as dateparse
from uptimer.events import SCHEMATA_PATH
from uptimer.events.cache import schema_cache
from uptimer.helpers import to_bool, to_none
class EventDefinitionError(ValueError):
pass
class EventMeta(ABCMet... | en | null | 1,040 |
0019095.py |
"""
Utilities for vectorization.
**The contents of this module are intended only for internal Deephaven use and may change at any time.**
"""
import ast
import traceback
from collections import OrderedDict
import collections
from io import UnsupportedOperation
import numba as nb
import numba.types
import numba.typi... |
"""
Utilities for vectorization.
**The contents of this module are intended only for internal Deephaven use and may change at any time.**
"""
import ast
import traceback
from collections import OrderedDict
import collections
from io import UnsupportedOperation
import numba as nb
import numba.types
import numba.typi... | en | null | 2,707 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.