code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from datetime import datetime
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from easy_thumbnails.fields import ThumbnailerImageField
from .constants import WAITING, REJECTED, SELECTED
from clothings.models impo... | designs/models.py | from datetime import datetime
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from easy_thumbnails.fields import ThumbnailerImageField
from .constants import WAITING, REJECTED, SELECTED
from clothings.models impo... | 0.589716 | 0.125226 |
import argparse
import logging
# Have to do this here because imports below pull in boto which likes to set up logging configuration its own way.
from pandas import DataFrame
logging.basicConfig(
format='%(asctime)s %(name)-20s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S'
... | sandbox_phase_2/covid-xprize-robotasks-main/judging/generate_predictions_local.py | import argparse
import logging
# Have to do this here because imports below pull in boto which likes to set up logging configuration its own way.
from pandas import DataFrame
logging.basicConfig(
format='%(asctime)s %(name)-20s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S'
... | 0.695855 | 0.361644 |
import asyncio
import copy
import glob
import os
import pathlib
import uuid
from datetime import time
import yaml
from aiohttp import web
from app.objects.c_adversary import Adversary
from app.objects.c_operation import Operation
from app.objects.c_schedule import Schedule
from app.objects.secondclass.c_fact import F... | app/service/rest_svc.py | import asyncio
import copy
import glob
import os
import pathlib
import uuid
from datetime import time
import yaml
from aiohttp import web
from app.objects.c_adversary import Adversary
from app.objects.c_operation import Operation
from app.objects.c_schedule import Schedule
from app.objects.secondclass.c_fact import F... | 0.236604 | 0.076822 |
from .base import ApiBase
import requests
class Checklists(ApiBase):
__module__ = 'trello'
def __init__(self, apikey, token=None):
self._apikey = apikey
self._token = token
def get(self, idChecklist, cards=None, card_fields=None, checkItems=None, checkItem_fields=None, fields=No... | trello/checklists.py | from .base import ApiBase
import requests
class Checklists(ApiBase):
__module__ = 'trello'
def __init__(self, apikey, token=None):
self._apikey = apikey
self._token = token
def get(self, idChecklist, cards=None, card_fields=None, checkItems=None, checkItem_fields=None, fields=No... | 0.423339 | 0.146697 |
"""Tests sonnet.python.modules.nets.mlp."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import sonnet as snt
from sonnet.testing import parameterized
import tensorflow as tf
class MLPTest(parameterized.Parameter... | sonnet/python/modules/nets/mlp_test.py |
"""Tests sonnet.python.modules.nets.mlp."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import sonnet as snt
from sonnet.testing import parameterized
import tensorflow as tf
class MLPTest(parameterized.Parameter... | 0.874064 | 0.412885 |
import pkgutil
import warnings
from pathlib import Path
from pmfp.utils.fs_utils import get_abs_path, path_to_str
from ..utils import (
sphinx_new,
no_jekyll,
sphinx_config,
sphinx_build,
move_to_source,
makeindex
)
from pmfp.utils.template_utils import template_2_content
AppendConfig = ""
so... | pmfp/entrypoint/doc_/new/new_py.py | import pkgutil
import warnings
from pathlib import Path
from pmfp.utils.fs_utils import get_abs_path, path_to_str
from ..utils import (
sphinx_new,
no_jekyll,
sphinx_config,
sphinx_build,
move_to_source,
makeindex
)
from pmfp.utils.template_utils import template_2_content
AppendConfig = ""
so... | 0.238107 | 0.078749 |
import numpy as np
from mindspore import context
from mindspore import Tensor, nn
from mindspore.common.parameter import Parameter
from mindspore.ops import composite as C
from mindspore.ops import operations as P
from mindspore.common import dtype as mstype
grad_all = C.GradOperation(get_all=True)
context.set_context... | tests/st/control/inner/test_332_for_after_for_in_for.py | import numpy as np
from mindspore import context
from mindspore import Tensor, nn
from mindspore.common.parameter import Parameter
from mindspore.ops import composite as C
from mindspore.ops import operations as P
from mindspore.common import dtype as mstype
grad_all = C.GradOperation(get_all=True)
context.set_context... | 0.772359 | 0.35095 |
"Test squeezer, coverage 95%"
from textwrap import dedent
from tkinter import Text, Tk
import unittest
from unittest.mock import Mock, NonCallableMagicMock, patch, sentinel, ANY
from test.support import requires
from idlelib.config import idleConf
from idlelib.percolator import Percolator
from idlelib.squeezer import... | Lib/idlelib/idle_test/test_squeezer.py | "Test squeezer, coverage 95%"
from textwrap import dedent
from tkinter import Text, Tk
import unittest
from unittest.mock import Mock, NonCallableMagicMock, patch, sentinel, ANY
from test.support import requires
from idlelib.config import idleConf
from idlelib.percolator import Percolator
from idlelib.squeezer import... | 0.829803 | 0.345409 |
import numpy as np
import glob
import shutil
import os
import cv2
from PIL import Image, ImageOps
from matplotlib import pyplot as plt
clothes_dir = '/home/ssai1/dhgwag/VITON/VITON-HD/datasets/train/cloth'
clothes_mask_dir = '/home/ssai1/dhgwag/VITON/VITON-HD/datasets/train/cloth-mask'
image_dir = '/home... | Scripts/clothes_blackenizer.py | import numpy as np
import glob
import shutil
import os
import cv2
from PIL import Image, ImageOps
from matplotlib import pyplot as plt
clothes_dir = '/home/ssai1/dhgwag/VITON/VITON-HD/datasets/train/cloth'
clothes_mask_dir = '/home/ssai1/dhgwag/VITON/VITON-HD/datasets/train/cloth-mask'
image_dir = '/home... | 0.099334 | 0.32826 |
import os
import re
import logging
import urllib
from storage import Storage
from http import HTTP
regex_at = re.compile('(?<!\\\\)\$[\w_]+')
regex_anything = re.compile('(?<!\\\\)\$anything')
regex_iter = re.compile(r'.*code=(?P<code>\d+)&ticket=(?P<ticket>.+).*')
params=Storage()
params.routes_in=[]
params.routes_... | gluon/rewrite.py | import os
import re
import logging
import urllib
from storage import Storage
from http import HTTP
regex_at = re.compile('(?<!\\\\)\$[\w_]+')
regex_anything = re.compile('(?<!\\\\)\$anything')
regex_iter = re.compile(r'.*code=(?P<code>\d+)&ticket=(?P<ticket>.+).*')
params=Storage()
params.routes_in=[]
params.routes_... | 0.187839 | 0.055592 |
import sys
from gflags import _helpers
# TODO(vrusinov): use DISCLAIM_key_flags when it's moved out of __init__.
_helpers.disclaim_module_ids.add(id(sys.modules[__name__]))
class Error(Exception):
"""The base class for all flags errors."""
# TODO(b/31596146): Remove FlagsError.
FlagsError = Error
class CantO... | third_party/py/gflags/gflags/exceptions.py | import sys
from gflags import _helpers
# TODO(vrusinov): use DISCLAIM_key_flags when it's moved out of __init__.
_helpers.disclaim_module_ids.add(id(sys.modules[__name__]))
class Error(Exception):
"""The base class for all flags errors."""
# TODO(b/31596146): Remove FlagsError.
FlagsError = Error
class CantO... | 0.310904 | 0.272339 |
from hypothesis import given
from hypothesis.strategies import lists, text
from matching import Player
@given(name=text())
def test_init(name):
""" Make an instance of Player and check their attributes are correct. """
player = Player(name)
assert player.name == name
assert player.prefs is None
... | tests/players/test_player.py |
from hypothesis import given
from hypothesis.strategies import lists, text
from matching import Player
@given(name=text())
def test_init(name):
""" Make an instance of Player and check their attributes are correct. """
player = Player(name)
assert player.name == name
assert player.prefs is None
... | 0.807764 | 0.614799 |
import datetime
import errno
import os
import shutil
import unittest
from xml.etree import ElementTree as et
from procsim.core import exceptions, job_order
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
JOB_ORDER_0083 = 'JobOrder_0083.xml'
TEST_JOB_ORDER = 'job_order.xml'
EXPECTED_INPUTS = [
(['$PATH/BIO_R... | procsim/core/test/test_job_order.py | import datetime
import errno
import os
import shutil
import unittest
from xml.etree import ElementTree as et
from procsim.core import exceptions, job_order
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
JOB_ORDER_0083 = 'JobOrder_0083.xml'
TEST_JOB_ORDER = 'job_order.xml'
EXPECTED_INPUTS = [
(['$PATH/BIO_R... | 0.256646 | 0.353986 |
import traceback
from functools import wraps
from . import exception
from . import flavor, peel, is_event, chat_flavors, inline_flavors
def _wrap_none(fn):
def w(*args, **kwargs):
try:
return fn(*args, **kwargs)
except (KeyError, exception.BadFlavor):
return None
retur... | amanobot/delegate.py | import traceback
from functools import wraps
from . import exception
from . import flavor, peel, is_event, chat_flavors, inline_flavors
def _wrap_none(fn):
def w(*args, **kwargs):
try:
return fn(*args, **kwargs)
except (KeyError, exception.BadFlavor):
return None
retur... | 0.649245 | 0.12749 |
import codecs
import os
import re
import sys
from setuptools import find_packages, setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [("pytest-args=", "a", "Arguments to pass into py.test")]
def initialize_options(self):
TestCommand.initialize_op... | setup.py | import codecs
import os
import re
import sys
from setuptools import find_packages, setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [("pytest-args=", "a", "Arguments to pass into py.test")]
def initialize_options(self):
TestCommand.initialize_op... | 0.307982 | 0.322859 |
import os
import numpy as np
from data.imca import generate_synthetic_data
from metrics.mcc import mean_corr_coef
from models.icebeem_wrapper import ICEBEEM_wrapper
from models.ivae.ivae_wrapper import IVAE_wrapper
from models.tcl.tcl_wrapper_gpu import TCL_wrapper
def run_ivae_exp(args, config):
"""run iVAE si... | runners/simulation_runner.py | import os
import numpy as np
from data.imca import generate_synthetic_data
from metrics.mcc import mean_corr_coef
from models.icebeem_wrapper import ICEBEEM_wrapper
from models.ivae.ivae_wrapper import IVAE_wrapper
from models.tcl.tcl_wrapper_gpu import TCL_wrapper
def run_ivae_exp(args, config):
"""run iVAE si... | 0.522446 | 0.307423 |
from tf_keras_1.optimizers.imports import *
from system.imports import *
@accepts(dict, post_trace=False)
#@TraceFunction(trace_args=False, trace_rv=False)
def load_optimizer(system_dict):
'''
Load Optimizers in training states
Args:
system_dict (dict): System dictionary storing experiment state a... | monk/tf_keras_1/optimizers/return_optimizer.py | from tf_keras_1.optimizers.imports import *
from system.imports import *
@accepts(dict, post_trace=False)
#@TraceFunction(trace_args=False, trace_rv=False)
def load_optimizer(system_dict):
'''
Load Optimizers in training states
Args:
system_dict (dict): System dictionary storing experiment state a... | 0.659076 | 0.092074 |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class StructuredAttention_bi(nn.Module):
def __init__(self, dropout=0.1, scale=100):
super(StructuredAttention_bi, self).__init__()
self.dropout = dropout
self.scale = scale
def forward(self, C, Q, c_mas... | iPerceiveVideoQA/qanet/context_query_attention.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class StructuredAttention_bi(nn.Module):
def __init__(self, dropout=0.1, scale=100):
super(StructuredAttention_bi, self).__init__()
self.dropout = dropout
self.scale = scale
def forward(self, C, Q, c_mas... | 0.885136 | 0.421314 |
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
import logging # isort:skip
log = logging.getLogger(__name__)
#-----------------------------------------------------------------------------
# Impo... | bokeh/sphinxext/bokeh_model.py | #-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
import logging # isort:skip
log = logging.getLogger(__name__)
#-----------------------------------------------------------------------------
# Impo... | 0.362518 | 0.096323 |
import sys, unittest
from django.test import TestCase
from django.core.serializers.json import DjangoJSONEncoder
from django.utils import timezone
from explorer.exporters import CSVExporter, JSONExporter, ExcelExporter, PdfExporter
from explorer.tests.factories import SimpleQueryFactory
from explorer.models import Quer... | explorer/tests/test_exporters.py | import sys, unittest
from django.test import TestCase
from django.core.serializers.json import DjangoJSONEncoder
from django.utils import timezone
from explorer.exporters import CSVExporter, JSONExporter, ExcelExporter, PdfExporter
from explorer.tests.factories import SimpleQueryFactory
from explorer.models import Quer... | 0.462959 | 0.406332 |
lst = [1, 2, 3, 4, 5]
# 리스트의 가장 뒤에 10을 추가
lst.append(10)
print(lst)
# [1, 2, 3, 4, 5, 10]
# 3번 인덱스 자리에 22를 삽입
lst.insert(3, 22)
print(lst)
# [1, 2, 3, 22, 4, 5, 10]
# lst의 뒤에 지정한 리스트 추가
# lst += [4, 5, 6] 과 결과가 같아 보이나, +=는 새로운 리스트를 생성하므로 속도가 더 느림
lst.extend([4, 5, 6])
print(lst)
# [1, 2, 3, 22, 4, 5, 10, 4, 5, 6]
# ... | week_1/func2.py | lst = [1, 2, 3, 4, 5]
# 리스트의 가장 뒤에 10을 추가
lst.append(10)
print(lst)
# [1, 2, 3, 4, 5, 10]
# 3번 인덱스 자리에 22를 삽입
lst.insert(3, 22)
print(lst)
# [1, 2, 3, 22, 4, 5, 10]
# lst의 뒤에 지정한 리스트 추가
# lst += [4, 5, 6] 과 결과가 같아 보이나, +=는 새로운 리스트를 생성하므로 속도가 더 느림
lst.extend([4, 5, 6])
print(lst)
# [1, 2, 3, 22, 4, 5, 10, 4, 5, 6]
# ... | 0.073734 | 0.579162 |
import logging
import json
from pcmdi_metrics.driver.outputmetrics import OutputMetrics
from pcmdi_metrics.driver.observation import Observation
from pcmdi_metrics.driver.model import Model
import pcmdi_metrics.driver.dataset
import pcmdi_metrics.driver.pmp_parser
from pcmdi_metrics import LOG_LEVEL
import ast
class ... | pcmdi_metrics/pcmdi/mean_climate_metrics_driver.py | import logging
import json
from pcmdi_metrics.driver.outputmetrics import OutputMetrics
from pcmdi_metrics.driver.observation import Observation
from pcmdi_metrics.driver.model import Model
import pcmdi_metrics.driver.dataset
import pcmdi_metrics.driver.pmp_parser
from pcmdi_metrics import LOG_LEVEL
import ast
class ... | 0.437824 | 0.108708 |
from distutils.version import StrictVersion
import os
import re
import subprocess
from typing import List
from typing import Optional
from typing import Set
from typing import Union
import lttng
from .names import CONTEXT_TYPE_CONSTANTS_MAP
from .names import DEFAULT_CONTEXT
from .names import DEFAULT_EVENTS_KERNEL
f... | tracetools_trace/tracetools_trace/tools/lttng_impl.py | from distutils.version import StrictVersion
import os
import re
import subprocess
from typing import List
from typing import Optional
from typing import Set
from typing import Union
import lttng
from .names import CONTEXT_TYPE_CONSTANTS_MAP
from .names import DEFAULT_CONTEXT
from .names import DEFAULT_EVENTS_KERNEL
f... | 0.786787 | 0.173044 |
import os
import pytest
from llnl.util.link_tree import MergeConflictError
import spack.package
import spack.spec
from spack.directory_layout import DirectoryLayout
from spack.filesystem_view import YamlFilesystemView
from spack.repo import RepoPath
def create_ext_pkg(name, prefix, extendee_spec, monkeypatch):
... | lib/spack/spack/test/test_activations.py | import os
import pytest
from llnl.util.link_tree import MergeConflictError
import spack.package
import spack.spec
from spack.directory_layout import DirectoryLayout
from spack.filesystem_view import YamlFilesystemView
from spack.repo import RepoPath
def create_ext_pkg(name, prefix, extendee_spec, monkeypatch):
... | 0.392104 | 0.153994 |
import argparse
try:
from . import treedata_pb2 as proto
from . import utils
except (ValueError, ImportError):
import treedata_pb2 as proto
import utils
import represent_ast as ra
class Node:
def __init__(self, id, label, position):
self.id = id
self.label = labe... | ase20_supplementary/webui/model/preprocess_clang.py | import argparse
try:
from . import treedata_pb2 as proto
from . import utils
except (ValueError, ImportError):
import treedata_pb2 as proto
import utils
import represent_ast as ra
class Node:
def __init__(self, id, label, position):
self.id = id
self.label = labe... | 0.278453 | 0.213787 |
from django.conf.urls import url
from django.contrib import admin
from django.contrib.admin.actions import delete_selected
from django.contrib.auth.models import User
from django.test import SimpleTestCase, TestCase, override_settings
from django.test.client import RequestFactory
from django.urls import reverse
from .... | tests/admin_views/test_adminsite.py | from django.conf.urls import url
from django.contrib import admin
from django.contrib.admin.actions import delete_selected
from django.contrib.auth.models import User
from django.test import SimpleTestCase, TestCase, override_settings
from django.test.client import RequestFactory
from django.urls import reverse
from .... | 0.549641 | 0.271499 |
import asyncio
import concurrent.futures
import functools
import logging
import signal
import threading
import warnings
from typing import (Optional, Collection, Union, Tuple, Set, Text, Any, Coroutine,
cast, TYPE_CHECKING)
from kopf.engines import peering
from kopf.engines import posting
from kopf... | kopf/reactor/running.py | import asyncio
import concurrent.futures
import functools
import logging
import signal
import threading
import warnings
from typing import (Optional, Collection, Union, Tuple, Set, Text, Any, Coroutine,
cast, TYPE_CHECKING)
from kopf.engines import peering
from kopf.engines import posting
from kopf... | 0.764276 | 0.154535 |
import json
import requests
from src.clustering.models import ClusteringMethods
from src.encoding.models import ValueEncodings, TaskGenerationTypes
from src.hyperparameter_optimization.models import HyperOptAlgorithms, HyperOptLosses, HyperparameterOptimizationMethods
from src.labelling.models import LabelTypes, Thre... | src/utils/experiments_utils.py | import json
import requests
from src.clustering.models import ClusteringMethods
from src.encoding.models import ValueEncodings, TaskGenerationTypes
from src.hyperparameter_optimization.models import HyperOptAlgorithms, HyperOptLosses, HyperparameterOptimizationMethods
from src.labelling.models import LabelTypes, Thre... | 0.563498 | 0.3415 |
import sys
import logging
import numpy as np
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Evaluator:
def __init__(self, num_samples: int = 0, num_features: int = 0):
self.loss = 0.0
self.best_loss = sys.maxsize
self.best_image2text_recall_at_k = -1.0
... | src/utils/evaluators.py | import sys
import logging
import numpy as np
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Evaluator:
def __init__(self, num_samples: int = 0, num_features: int = 0):
self.loss = 0.0
self.best_loss = sys.maxsize
self.best_image2text_recall_at_k = -1.0
... | 0.590071 | 0.327131 |
import numpy as np
from gradient_algorithm import gradient_algorithm_var_alpha, gradient_algorithm_fixed_alpha, gradient_algorithm_linesearch
from conjugate_gradient_algorithm import conjugate_gradient_algorithm, conjugate_gradient_algorithm_linesearch
from newton_algorithm import newton_algorithm, newton_algorithm_lin... | system_of_linear_equations/demo_system_of_linear_equations.py | import numpy as np
from gradient_algorithm import gradient_algorithm_var_alpha, gradient_algorithm_fixed_alpha, gradient_algorithm_linesearch
from conjugate_gradient_algorithm import conjugate_gradient_algorithm, conjugate_gradient_algorithm_linesearch
from newton_algorithm import newton_algorithm, newton_algorithm_lin... | 0.652574 | 0.588121 |
import warnings
from functools import partial
import onnx
from onnx import numpy_helper
import tensorflow as tf
from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE
import numpy as np
from tensorflow.python.ops.image_ops_impl import ResizeMethodV1
class Operations:
def make_op(self, op_type, inputs, attrs):
#... | onnx2keras.py | import warnings
from functools import partial
import onnx
from onnx import numpy_helper
import tensorflow as tf
from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE
import numpy as np
from tensorflow.python.ops.image_ops_impl import ResizeMethodV1
class Operations:
def make_op(self, op_type, inputs, attrs):
#... | 0.453988 | 0.562237 |
from collections import defaultdict
from enum import Enum
from typing import Dict, Optional
from dagster import Field, Selector
from dagster import _check as check
from dagster.serdes.serdes import whitelist_for_serdes
def get_retries_config():
return Field(
Selector({"enabled": {}, "disabled": {}}),
... | python_modules/dagster/dagster/core/execution/retries.py | from collections import defaultdict
from enum import Enum
from typing import Dict, Optional
from dagster import Field, Selector
from dagster import _check as check
from dagster.serdes.serdes import whitelist_for_serdes
def get_retries_config():
return Field(
Selector({"enabled": {}, "disabled": {}}),
... | 0.846863 | 0.157331 |
import glob
import os
import datetime
import json
import numpy as np
import pandas as pd
from pandas import DataFrame
import time
from telegram_definition_L1 import *
from golabal_def import Dir_Path
# telegram directory (default)
tel_directory = Dir_Path
# initialisation
selTelegram_N02 = np.array... | setup_data.py | import glob
import os
import datetime
import json
import numpy as np
import pandas as pd
from pandas import DataFrame
import time
from telegram_definition_L1 import *
from golabal_def import Dir_Path
# telegram directory (default)
tel_directory = Dir_Path
# initialisation
selTelegram_N02 = np.array... | 0.182899 | 0.228737 |
import time, sys
from time import gmtime
import httplib, urllib
ip_address='10.12.19.67'
#ip_address='127.0.0.1'
#ip_address='10.20.218.197'
cost='0'
weather='overcast'
#local_hour=time.localtime().tm_hour
sun_percentage=[0,0,0,0,0,0,0.2305,0.6537,0.8328,0.9215,0.9689,0.9927,1,0.9927,0.9689,0.9215,0.8328,0.6537,0.2305... | NinjaBandSPADE/SPADE-agents/blinds_agent.py | import time, sys
from time import gmtime
import httplib, urllib
ip_address='10.12.19.67'
#ip_address='127.0.0.1'
#ip_address='10.20.218.197'
cost='0'
weather='overcast'
#local_hour=time.localtime().tm_hour
sun_percentage=[0,0,0,0,0,0,0.2305,0.6537,0.8328,0.9215,0.9689,0.9927,1,0.9927,0.9689,0.9215,0.8328,0.6537,0.2305... | 0.029633 | 0.084191 |
import logging
import ray
import ray.streaming._streaming as _streaming
import ray.streaming.generated.remote_call_pb2 as remote_call_pb
import ray.streaming.runtime.processor as processor
from ray.streaming.config import Config
from ray.streaming.runtime.graph import ExecutionGraph
from ray.streaming.runtime.task imp... | streaming/python/runtime/worker.py | import logging
import ray
import ray.streaming._streaming as _streaming
import ray.streaming.generated.remote_call_pb2 as remote_call_pb
import ray.streaming.runtime.processor as processor
from ray.streaming.config import Config
from ray.streaming.runtime.graph import ExecutionGraph
from ray.streaming.runtime.task imp... | 0.687735 | 0.054224 |
# Standard library imports
from typing import Dict, List, Tuple
# Third-party imports
import mxnet as mx
# First-party imports
from gluonts.core.component import validated
from gluonts.distribution.bijection import Bijection, InverseBijection
from gluonts.distribution.bijection_output import BijectionOutput
from glu... | src/gluonts/distribution/box_cox_tranform.py |
# Standard library imports
from typing import Dict, List, Tuple
# Third-party imports
import mxnet as mx
# First-party imports
from gluonts.core.component import validated
from gluonts.distribution.bijection import Bijection, InverseBijection
from gluonts.distribution.bijection_output import BijectionOutput
from glu... | 0.969222 | 0.753047 |
import argparse
import json
from datetime import datetime, timedelta
import requests
from bs4 import BeautifulSoup
from models import Ad, Filter
DEFAULT_FILTER_PATH = 'filter.json'
MONTHS = {
'jan': 1,
'fev': 2,
'mar': 3,
'abr': 4,
'mai': 5,
'jun': 6,
'jul': 7,
'ago': 8,
'set': 9,... | scrape.py | import argparse
import json
from datetime import datetime, timedelta
import requests
from bs4 import BeautifulSoup
from models import Ad, Filter
DEFAULT_FILTER_PATH = 'filter.json'
MONTHS = {
'jan': 1,
'fev': 2,
'mar': 3,
'abr': 4,
'mai': 5,
'jun': 6,
'jul': 7,
'ago': 8,
'set': 9,... | 0.519765 | 0.153644 |
"""Helper tools for use in tests."""
from __future__ import division
import base64
import copy
import itertools
import os
from collections import defaultdict
from decimal import Decimal
import boto3
import pytest
from boto3.dynamodb.types import Binary
from botocore.exceptions import NoRegionError
from mock import pa... | test/functional/functional_test_utils.py | """Helper tools for use in tests."""
from __future__ import division
import base64
import copy
import itertools
import os
from collections import defaultdict
from decimal import Decimal
import boto3
import pytest
from boto3.dynamodb.types import Binary
from botocore.exceptions import NoRegionError
from mock import pa... | 0.653569 | 0.339745 |
import argparse
from http import client as httplib
import socket
from oslo_serialization import jsonutils
from kuryr_kubernetes import constants
class UnixDomainHttpConnection(httplib.HTTPConnection):
def __init__(self, path, timeout):
httplib.HTTPConnection.__init__(
self, "localhost", ti... | contrib/pools-management/subports.py |
import argparse
from http import client as httplib
import socket
from oslo_serialization import jsonutils
from kuryr_kubernetes import constants
class UnixDomainHttpConnection(httplib.HTTPConnection):
def __init__(self, path, timeout):
httplib.HTTPConnection.__init__(
self, "localhost", ti... | 0.4436 | 0.061199 |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os
from collections import OrderedDict
import sys
linestyles = OrderedDict(
[('solid', (0, ())),
('loosely dotted', (0, (1, 10))),
('dotted', ... | DEEPLEARNING/DL_VOXELNET/parse_log.py | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os
from collections import OrderedDict
import sys
linestyles = OrderedDict(
[('solid', (0, ())),
('loosely dotted', (0, (1, 10))),
('dotted', ... | 0.245718 | 0.405508 |
import enum
import jarvisenv
class Status(enum.Enum):
"""Available cart statuses"""
Idle = 0
Moving = 1
Loading = 2
Unloading = 3
class Load:
"""Object for a single load."""
def __init__(self, src, dst, weight, content):
assert weight > 0
self.src = src
self.dst ... | cart.py | import enum
import jarvisenv
class Status(enum.Enum):
"""Available cart statuses"""
Idle = 0
Moving = 1
Loading = 2
Unloading = 3
class Load:
"""Object for a single load."""
def __init__(self, src, dst, weight, content):
assert weight > 0
self.src = src
self.dst ... | 0.707101 | 0.378057 |
from .deployment_utils import UniversumRunner
from .utils import python, simple_test_config
def test_minimal_install(clean_docker_main: UniversumRunner):
# Run without parameters
log = clean_docker_main.environment.assert_unsuccessful_execution(f"{python()} -m universum")
assert "No module named universum... | tests/test_deployment.py | from .deployment_utils import UniversumRunner
from .utils import python, simple_test_config
def test_minimal_install(clean_docker_main: UniversumRunner):
# Run without parameters
log = clean_docker_main.environment.assert_unsuccessful_execution(f"{python()} -m universum")
assert "No module named universum... | 0.51562 | 0.330282 |
import gevent.monkey; gevent.monkey.patch_all()
import socket
import time
import gevent
import gevent.server
import gevent.socket
import gevent.queue
from cluster import ClusterManager
from dispatcher import DispatchClient
from task import Task
import util
import constants
class ScheduleError(Exception): pass
clas... | miyamoto/scheduler.py | import gevent.monkey; gevent.monkey.patch_all()
import socket
import time
import gevent
import gevent.server
import gevent.socket
import gevent.queue
from cluster import ClusterManager
from dispatcher import DispatchClient
from task import Task
import util
import constants
class ScheduleError(Exception): pass
clas... | 0.222447 | 0.071689 |
from tenable.errors import *
from ..checker import check, single
from datetime import date
import pytest
@pytest.mark.vcr()
def test_families(api):
families = api.plugins.families()
assert isinstance(families, list)
for f in families:
check(f, 'count', int)
check(f, 'id', int)
check... | tests/io/test_plugins.py | from tenable.errors import *
from ..checker import check, single
from datetime import date
import pytest
@pytest.mark.vcr()
def test_families(api):
families = api.plugins.families()
assert isinstance(families, list)
for f in families:
check(f, 'count', int)
check(f, 'id', int)
check... | 0.501465 | 0.378603 |
import numpy as np
import matplotlib.pyplot as plt
from numpy.polynomial.legendre import leggauss
from quadr import lglnodes,equispaced
def lagrange_basis(nodes,x,k):
y=np.zeros(x.size)
for ix, xi in enumerate(x):
tmp=[(xi-nodes[j])/(nodes[k]-nodes[j]) for j in range(len(nodes)) if j!=k]
y[ix]=... | pythonCodes/DeC.py | import numpy as np
import matplotlib.pyplot as plt
from numpy.polynomial.legendre import leggauss
from quadr import lglnodes,equispaced
def lagrange_basis(nodes,x,k):
y=np.zeros(x.size)
for ix, xi in enumerate(x):
tmp=[(xi-nodes[j])/(nodes[k]-nodes[j]) for j in range(len(nodes)) if j!=k]
y[ix]=... | 0.119459 | 0.509093 |
# Copyright 2019 <NAME>
# License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import random
import torch as th
import torch.nn.functional as tf
from typing import Tuple, Union
def tf_mask(batch: int,
shape: Tuple[int],
p: float = 1.0,
max_bands: int = 30,
... | aps/transform/augment.py |
# Copyright 2019 <NAME>
# License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import random
import torch as th
import torch.nn.functional as tf
from typing import Tuple, Union
def tf_mask(batch: int,
shape: Tuple[int],
p: float = 1.0,
max_bands: int = 30,
... | 0.916339 | 0.426919 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
import numpy as np
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
def PoissonGen(inp, rescale_fac=2.0):
rand_inp = torch.rand_like(inp)
return torch.mul(torch.le(rand_inp * rescale_fac, torch.abs(inp))... | initial/network/initial_0.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
import numpy as np
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
def PoissonGen(inp, rescale_fac=2.0):
rand_inp = torch.rand_like(inp)
return torch.mul(torch.le(rand_inp * rescale_fac, torch.abs(inp))... | 0.858911 | 0.617974 |
import httplib
import stubout
from cinder import context
from cinder import db
from cinder import exception
from cinder.openstack.common import jsonutils
from cinder.openstack.common.scheduler import filters
from cinder import test
from cinder.tests.scheduler import fakes
from cinder.tests import utils as test_utils
f... | cinder/tests/scheduler/test_host_filters.py | import httplib
import stubout
from cinder import context
from cinder import db
from cinder import exception
from cinder.openstack.common import jsonutils
from cinder.openstack.common.scheduler import filters
from cinder import test
from cinder.tests.scheduler import fakes
from cinder.tests import utils as test_utils
f... | 0.634543 | 0.30234 |
import logging
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from six.moves import input
from django_extensions.management.mysql import parse_mysql_cnf
from django_extensions.management.utils import signalcommand
class Command(BaseCommand):
help = "Resets the... | django_extensions/management/commands/reset_db.py | import logging
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from six.moves import input
from django_extensions.management.mysql import parse_mysql_cnf
from django_extensions.management.utils import signalcommand
class Command(BaseCommand):
help = "Resets the... | 0.314577 | 0.047184 |
class Error(Exception):
pass
class AlreadyExists(Error):
pass
class BadArgument(Error):
pass
class BadExitStatus(Error):
pass
class ConfigError(Error):
pass
class ContentLengthMismatch(Error):
pass
class ContentChecksumMismatch(Error):
pass
class ContentSeekError(Error):
pa... | fluiddb/common/error.py | class Error(Exception):
pass
class AlreadyExists(Error):
pass
class BadArgument(Error):
pass
class BadExitStatus(Error):
pass
class ConfigError(Error):
pass
class ContentLengthMismatch(Error):
pass
class ContentChecksumMismatch(Error):
pass
class ContentSeekError(Error):
pa... | 0.738763 | 0.173743 |
import json
import os
from concurrent.futures import ThreadPoolExecutor
import pytest
from ruamel import yaml
from precept import (
Precept, Command, Argument, Config, ConfigProperty, Nestable, ConfigFormat,
config_factory)
override_configs = {
'config_int': 25,
'config_str': 'bar',
'config_list'... | tests/test_configs.py | import json
import os
from concurrent.futures import ThreadPoolExecutor
import pytest
from ruamel import yaml
from precept import (
Precept, Command, Argument, Config, ConfigProperty, Nestable, ConfigFormat,
config_factory)
override_configs = {
'config_int': 25,
'config_str': 'bar',
'config_list'... | 0.388038 | 0.166354 |
from galaxy_analysis.plot.plot_styles import *
from galaxy_analysis.analysis.compute_time_average import compute_time_average
from galaxy_analysis.utilities import utilities
import sys
import numpy as np
import matplotlib.pyplot as plt
#filepath = '/mnt/ceph/users/emerick/enzo_runs/pleiades/starIC/run11_30km/final_snd... | method_paper_plots/time_average_velocity.py | from galaxy_analysis.plot.plot_styles import *
from galaxy_analysis.analysis.compute_time_average import compute_time_average
from galaxy_analysis.utilities import utilities
import sys
import numpy as np
import matplotlib.pyplot as plt
#filepath = '/mnt/ceph/users/emerick/enzo_runs/pleiades/starIC/run11_30km/final_snd... | 0.325628 | 0.297757 |
from conans import ConanFile, tools, AutoToolsBuildEnvironment
import os
class LibX264Conan(ConanFile):
name = "libx264"
version = "20190605"
url = "https://github.com/bincrafters/conan-libx264"
homepage = "https://www.videolan.org/developers/x264.html"
author = "Bincrafters <<EMAIL>>"
descri... | conanfile.py |
from conans import ConanFile, tools, AutoToolsBuildEnvironment
import os
class LibX264Conan(ConanFile):
name = "libx264"
version = "20190605"
url = "https://github.com/bincrafters/conan-libx264"
homepage = "https://www.videolan.org/developers/x264.html"
author = "Bincrafters <<EMAIL>>"
descri... | 0.382141 | 0.136868 |
from collections import deque
from operator import itemgetter
import networkx as nx
from ..utils import arbitrary_element
__author__ = """\n""".join(['<NAME> <<EMAIL>>'])
__all__ = ['cuthill_mckee_ordering',
'reverse_cuthill_mckee_ordering']
def cuthill_mckee_ordering(G, heuristic=None):
"""Generate ... | networkx/utils/rcm.py | from collections import deque
from operator import itemgetter
import networkx as nx
from ..utils import arbitrary_element
__author__ = """\n""".join(['<NAME> <<EMAIL>>'])
__all__ = ['cuthill_mckee_ordering',
'reverse_cuthill_mckee_ordering']
def cuthill_mckee_ordering(G, heuristic=None):
"""Generate ... | 0.900157 | 0.624837 |
"""Caches used by Spack to store data"""
import os
import llnl.util.lang
from llnl.util.filesystem import mkdirp
from llnl.util.symlink import symlink
import spack.config
import spack.error
import spack.fetch_strategy
import spack.paths
import spack.util.file_cache
import spack.util.path
def misc_cache_location():... | lib/spack/spack/caches.py |
"""Caches used by Spack to store data"""
import os
import llnl.util.lang
from llnl.util.filesystem import mkdirp
from llnl.util.symlink import symlink
import spack.config
import spack.error
import spack.fetch_strategy
import spack.paths
import spack.util.file_cache
import spack.util.path
def misc_cache_location():... | 0.553264 | 0.224831 |
from __future__ import division
from __future__ import with_statement
aa_colors = {'start' : 'c',
'basic' : 'b',
'acidic' : 'r',
'polar' : 'g',
'nonpolar' : 'y',
'stop' : 'k'}
nucleotides = ['a', 'c', 'g', 'u']
start_codon = 'aug'
stop_c... | toolbox_transcription.py | from __future__ import division
from __future__ import with_statement
aa_colors = {'start' : 'c',
'basic' : 'b',
'acidic' : 'r',
'polar' : 'g',
'nonpolar' : 'y',
'stop' : 'k'}
nucleotides = ['a', 'c', 'g', 'u']
start_codon = 'aug'
stop_c... | 0.539105 | 0.06727 |
from multiprocessing import Process, Queue, TimeoutError, Value
from multiprocessing.queues import Empty, Full
from abc import abstractmethod, ABCMeta
import logging
import copy
__default_exit_flag__ = Value('b', True)
__fmt__ = "%(levelname)s: %(asctime)s - %(name)s - %(process)s - %(message)s"
class StreamElement... | pewpew/base.py | from multiprocessing import Process, Queue, TimeoutError, Value
from multiprocessing.queues import Empty, Full
from abc import abstractmethod, ABCMeta
import logging
import copy
__default_exit_flag__ = Value('b', True)
__fmt__ = "%(levelname)s: %(asctime)s - %(name)s - %(process)s - %(message)s"
class StreamElement... | 0.637144 | 0.127571 |
import future
import builtins
import past
import six
import copy
from timeit import default_timer as timer
from datetime import datetime
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets
from torch.utils.data import Dataset
i... | adv/diffai/__main__.py | import future
import builtins
import past
import six
import copy
from timeit import default_timer as timer
from datetime import datetime
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets
from torch.utils.data import Dataset
i... | 0.759047 | 0.195498 |
import asyncio
import logging
from contextlib import suppress
from typing import Optional
import discord
from discord import Message
from discord.abc import Messageable
from discord.embeds import EmptyEmbed
from discord.ext import commands
from milton.core.config import CONFIG
log = logging.getLogger(__name__)
DELE... | milton/utils/paginator.py | import asyncio
import logging
from contextlib import suppress
from typing import Optional
import discord
from discord import Message
from discord.abc import Messageable
from discord.embeds import EmptyEmbed
from discord.ext import commands
from milton.core.config import CONFIG
log = logging.getLogger(__name__)
DELE... | 0.822332 | 0.148788 |
import os
from wisdem import run_wisdem
import wisdem.postprocessing.compare_designs as compare_designs
# File management
thisdir = os.path.dirname(os.path.realpath(__file__))
ontology_dir = os.path.join(os.path.dirname(thisdir), "WT_Ontology")
fname_wt_input = os.path.join(ontology_dir, "IEA-15-240-RWT.yaml")
fname... | WISDEM/optimize_monopile_tower.py | import os
from wisdem import run_wisdem
import wisdem.postprocessing.compare_designs as compare_designs
# File management
thisdir = os.path.dirname(os.path.realpath(__file__))
ontology_dir = os.path.join(os.path.dirname(thisdir), "WT_Ontology")
fname_wt_input = os.path.join(ontology_dir, "IEA-15-240-RWT.yaml")
fname... | 0.347648 | 0.212436 |
import os
import string
import uuid
import cv2
import imutils.text
def update_flag(key_press, current_flag, flags):
"""Handle key press from cv2.waitKey() for capturing frames
:param key_press: output from `cv2.waitKey()`
:param current_flag: value of 'flag' holding previous key press
:param flags: d... | imclassify/gather_images.py | import os
import string
import uuid
import cv2
import imutils.text
def update_flag(key_press, current_flag, flags):
"""Handle key press from cv2.waitKey() for capturing frames
:param key_press: output from `cv2.waitKey()`
:param current_flag: value of 'flag' holding previous key press
:param flags: d... | 0.573678 | 0.457985 |
from django.shortcuts import render, redirect
from django.http import HttpResponse, Http404
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from .models import Image, Profile, Comments, Likes
from friendship.models import Follow
from .forms import ImageForm,... | instagramClone/views.py | from django.shortcuts import render, redirect
from django.http import HttpResponse, Http404
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from .models import Image, Profile, Comments, Likes
from friendship.models import Follow
from .forms import ImageForm,... | 0.371707 | 0.068102 |
import os
import json
import time
import urllib
import logging
import bs4
import click
import requests
import schooldiggerscraper.utils # noqa
logging.basicConfig(level=logging.INFO)
class SchoolDiggerScraper(object):
"""Class of scraper, can download and save."""
def __init__(self, state, level, out, sl... | SchoolDiggerScraper/scrape.py | import os
import json
import time
import urllib
import logging
import bs4
import click
import requests
import schooldiggerscraper.utils # noqa
logging.basicConfig(level=logging.INFO)
class SchoolDiggerScraper(object):
"""Class of scraper, can download and save."""
def __init__(self, state, level, out, sl... | 0.431584 | 0.083255 |
from django.core.urlresolvers import reverse
from cms.test_utils.testcases import CMSTestCase
from richie.apps.core.factories import UserFactory
from richie.apps.courses.factories import (
CourseFactory,
OrganizationFactory,
SubjectFactory,
)
class CourseAdminTestCase(CMSTestCase):
"""
Integrati... | tests/apps/courses/test_admin_course.py | from django.core.urlresolvers import reverse
from cms.test_utils.testcases import CMSTestCase
from richie.apps.core.factories import UserFactory
from richie.apps.courses.factories import (
CourseFactory,
OrganizationFactory,
SubjectFactory,
)
class CourseAdminTestCase(CMSTestCase):
"""
Integrati... | 0.692434 | 0.390912 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import os
from six.moves import xrange
import torch
import torch.nn.functional as F
from torch.autograd import Variable as Var
from torch.utils.data import DataLoader, Dataset
ckpt_path =... | syft/dp/pate.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import os
from six.moves import xrange
import torch
import torch.nn.functional as F
from torch.autograd import Variable as Var
from torch.utils.data import DataLoader, Dataset
ckpt_path =... | 0.912969 | 0.543409 |
import logging
import os.path
import sys
# Automagically add util/py_lib to PYTHONPATH environment variable.
path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',
'..', '..', 'util', 'py_lib'))
sys.path.insert(0, path)
import seqan.app_tests as app_tests
def main(so... | apps/insegt/tests/run_tests.py | import logging
import os.path
import sys
# Automagically add util/py_lib to PYTHONPATH environment variable.
path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',
'..', '..', 'util', 'py_lib'))
sys.path.insert(0, path)
import seqan.app_tests as app_tests
def main(so... | 0.309754 | 0.069954 |
import csv
import sys
from datetime import datetime, timedelta
import itertools
import operator
import os
use_colors = sys.stdout.isatty()
if use_colors:
try:
import colorama
if os.name == 'nt':
colorama.init(strip=True, convert=True)
else:
colorama.init()
exce... | workcalc.py |
import csv
import sys
from datetime import datetime, timedelta
import itertools
import operator
import os
use_colors = sys.stdout.isatty()
if use_colors:
try:
import colorama
if os.name == 'nt':
colorama.init(strip=True, convert=True)
else:
colorama.init()
exce... | 0.228587 | 0.173131 |
import os
import sys
import logging
import threading
currPath = os.path.dirname(os.path.realpath(__file__))
rootPath = os.path.dirname(currPath)
sys.path.append(rootPath)
from rtCommon.exampleInterface import ExampleInterface
from rtCommon.wsRemoteService import WsRemoteService, parseConnectionArgs
from rtCommon.utils ... | rtCommon/exampleService.py | import os
import sys
import logging
import threading
currPath = os.path.dirname(os.path.realpath(__file__))
rootPath = os.path.dirname(currPath)
sys.path.append(rootPath)
from rtCommon.exampleInterface import ExampleInterface
from rtCommon.wsRemoteService import WsRemoteService, parseConnectionArgs
from rtCommon.utils ... | 0.442155 | 0.078148 |
"""Base task runner"""
import getpass
import os
import subprocess
import threading
from tempfile import NamedTemporaryFile
from typing import Optional, Union
from airflow.configuration import conf
from airflow.exceptions import AirflowConfigException
from airflow.models.taskinstance import load_error_file
from airflow... | airflow/task/task_runner/base_task_runner.py | """Base task runner"""
import getpass
import os
import subprocess
import threading
from tempfile import NamedTemporaryFile
from typing import Optional, Union
from airflow.configuration import conf
from airflow.exceptions import AirflowConfigException
from airflow.models.taskinstance import load_error_file
from airflow... | 0.715026 | 0.1291 |
def readFile(filename):
f = open(filename, "r")
content = f.read()
f.close()
return content
def writeFile(filename, content):
f = open(filename, "w")
f.write(content)
f.close()
return
def removeComments(text): # Removes Comments (/**/ and //) in and before the portlist and whitespace a... | tbgenerator.py | def readFile(filename):
f = open(filename, "r")
content = f.read()
f.close()
return content
def writeFile(filename, content):
f = open(filename, "w")
f.write(content)
f.close()
return
def removeComments(text): # Removes Comments (/**/ and //) in and before the portlist and whitespace a... | 0.193452 | 0.143758 |
from __future__ import print_function, division, absolute_import
import itertools
import numpy as np
import regreg.atoms.group_lasso as GL
import regreg.api as rr
import nose.tools as nt
from .test_seminorms import Solver, all_close, SolverFactory
from .test_cones import ConeSolverFactory
class GroupSolverFactor... | regreg/atoms/tests/test_group_lasso.py | from __future__ import print_function, division, absolute_import
import itertools
import numpy as np
import regreg.atoms.group_lasso as GL
import regreg.api as rr
import nose.tools as nt
from .test_seminorms import Solver, all_close, SolverFactory
from .test_cones import ConeSolverFactory
class GroupSolverFactor... | 0.704567 | 0.231842 |
import serial
import time
import random
import sys
s = None
num_leds = 93
play_time = 0
def flush_input():
s.flushInput()
def wait_for_ack():
while s.inWaiting() <= 0:
pass ... | python/flower20.py |
import serial
import time
import random
import sys
s = None
num_leds = 93
play_time = 0
def flush_input():
s.flushInput()
def wait_for_ack():
while s.inWaiting() <= 0:
pass ... | 0.211335 | 0.144722 |
import os, time;
from mWindowsAPI import *;
from mWindowsSDK import SECURITY_MANDATORY_MEDIUM_RID;
from mConsole import oConsole;
def fTestProcess(sComSpec, sThisProcessISA, sExpectedChildProcessISA):
oConsole.fOutput("=== Testing process related functions ", sPadding = "=");
oConsole.fOutput("* This process ISA: ... | Tests/fTestProcess.py | import os, time;
from mWindowsAPI import *;
from mWindowsSDK import SECURITY_MANDATORY_MEDIUM_RID;
from mConsole import oConsole;
def fTestProcess(sComSpec, sThisProcessISA, sExpectedChildProcessISA):
oConsole.fOutput("=== Testing process related functions ", sPadding = "=");
oConsole.fOutput("* This process ISA: ... | 0.359027 | 0.270155 |
import click
from aiida.cmdline.commands.cmd_data import verdi_data
from aiida.cmdline.params import arguments
from aiida.cmdline.utils import echo
from aiida.common.utils import get_mode_string
@verdi_data.group('remote')
def remote():
"""
Managing Remote_Data data types
"""
pass
@remote.command('l... | aiida/cmdline/commands/cmd_data/cmd_remote.py | import click
from aiida.cmdline.commands.cmd_data import verdi_data
from aiida.cmdline.params import arguments
from aiida.cmdline.utils import echo
from aiida.common.utils import get_mode_string
@verdi_data.group('remote')
def remote():
"""
Managing Remote_Data data types
"""
pass
@remote.command('l... | 0.176849 | 0.07383 |
import argparse
import codecs
import logging
import math
def ComputeMutualInfo(char_freq_file, bi_freq_file, output_file, filter_file):
"""Computes mutual information of multi-character terms
Use the corpus character and character bigram frequency information to compute
the mutual information for each bigram, ... | chinesenotes/mutualinfo.py | import argparse
import codecs
import logging
import math
def ComputeMutualInfo(char_freq_file, bi_freq_file, output_file, filter_file):
"""Computes mutual information of multi-character terms
Use the corpus character and character bigram frequency information to compute
the mutual information for each bigram, ... | 0.555676 | 0.452475 |
import random
import cv2
import numpy as np
from augraphy.augmentations.lib import add_noise
from augraphy.base.augmentation import Augmentation
class DustyInk(Augmentation):
"""Applies random noise to the ink itself, emulating a dusty or
inconsistent ink tone when followed by a blur.
:param intensity_... | augraphy/augmentations/dustyink.py | import random
import cv2
import numpy as np
from augraphy.augmentations.lib import add_noise
from augraphy.base.augmentation import Augmentation
class DustyInk(Augmentation):
"""Applies random noise to the ink itself, emulating a dusty or
inconsistent ink tone when followed by a blur.
:param intensity_... | 0.86988 | 0.401629 |
import subprocess
from uuid import getnode as get_mac
import datetime
import logging
from logging.handlers import RotatingFileHandler
import requests
import json
import netifaces
import os
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(messag... | code/applyPolicies.py | import subprocess
from uuid import getnode as get_mac
import datetime
import logging
from logging.handlers import RotatingFileHandler
import requests
import json
import netifaces
import os
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(messag... | 0.177847 | 0.041365 |
from urlparse import urljoin
from sqlalchemy import orm, inspect
from sqlalchemy.ext import hybrid
from ggrc import db
from ggrc.fulltext import attributes as ft_attributes
from ggrc.fulltext import mixin as ft_mixin
from ggrc.models import mixins
from ggrc.models import reflection
from ggrc.models import relationshi... | src/ggrc_workflows/models/cycle.py | from urlparse import urljoin
from sqlalchemy import orm, inspect
from sqlalchemy.ext import hybrid
from ggrc import db
from ggrc.fulltext import attributes as ft_attributes
from ggrc.fulltext import mixin as ft_mixin
from ggrc.models import mixins
from ggrc.models import reflection
from ggrc.models import relationshi... | 0.780495 | 0.08438 |
import os
import argparse
from model_init import init_dataloader
from mindspore import dataset as ds
parser = argparse.ArgumentParser()
parser.add_argument('--dataset_path', default=None, help='Location of data.')
parser.add_argument('--data_output_path', default=None, help='Location of converted data.')
parser.add_a... | research/cv/ProtoNet/preprocess.py | import os
import argparse
from model_init import init_dataloader
from mindspore import dataset as ds
parser = argparse.ArgumentParser()
parser.add_argument('--dataset_path', default=None, help='Location of data.')
parser.add_argument('--data_output_path', default=None, help='Location of converted data.')
parser.add_a... | 0.413004 | 0.118232 |
"""Tests for tensorflow.python.framework.importer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from google.protobuf import text_format
from tensorflow.core.framework import graph_pb2
from tensorflow.core.framework import op_def_p... | tensorflow/python/framework/importer_test.py | """Tests for tensorflow.python.framework.importer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from google.protobuf import text_format
from tensorflow.core.framework import graph_pb2
from tensorflow.core.framework import op_def_p... | 0.795062 | 0.188026 |
"""Integration tests for the Osquery flow, its API client and API endpoints."""
import json
from absl import app
from grr_api_client import utils
from grr_response_proto.api import osquery_pb2 as api_osquery_pb2
from grr_response_server.flows.general import osquery as osquery_flow
from grr_response_server.gui import ... | grr/server/grr_response_server/gui/api_integration_tests/osquery_test.py | """Integration tests for the Osquery flow, its API client and API endpoints."""
import json
from absl import app
from grr_api_client import utils
from grr_response_proto.api import osquery_pb2 as api_osquery_pb2
from grr_response_server.flows.general import osquery as osquery_flow
from grr_response_server.gui import ... | 0.746693 | 0.351784 |
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
import numpy as np
import os
import json
import gdown
... | PULSE.py | import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
import numpy as np
import os
import json
import gdown
... | 0.718989 | 0.429549 |
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipIf
from tests.suppo... | tests/unit/modules/test_useradd.py | # Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipIf
from tests.suppo... | 0.615897 | 0.173708 |
import os
import argparse
import cv2
import shutil
import itertools
import tqdm
import numpy as np
import json
import six
import tensorflow as tf
try:
import horovod.tensorflow as hvd
except ImportError:
pass
assert six.PY3, "FasterRCNN requires Python 3!"
from tensorpack import *
from tensorpack.tfutils.sum... | examples/FasterRCNN/train.py |
import os
import argparse
import cv2
import shutil
import itertools
import tqdm
import numpy as np
import json
import six
import tensorflow as tf
try:
import horovod.tensorflow as hvd
except ImportError:
pass
assert six.PY3, "FasterRCNN requires Python 3!"
from tensorpack import *
from tensorpack.tfutils.sum... | 0.720565 | 0.21596 |
import inspect
from abc import ABC
from typing import Dict
from fedrec.data_models.trainer_state_model import TrainerState
from fedrec.python_executors.base_actor import BaseActor
from fedrec.user_modules.envis_base_module import EnvisBase
from fedrec.utilities import registry
from fedrec.utilities.logger import BaseL... | fedrec/python_executors/trainer.py | import inspect
from abc import ABC
from typing import Dict
from fedrec.data_models.trainer_state_model import TrainerState
from fedrec.python_executors.base_actor import BaseActor
from fedrec.user_modules.envis_base_module import EnvisBase
from fedrec.utilities import registry
from fedrec.utilities.logger import BaseL... | 0.738763 | 0.200989 |
import os
import os.path
from typing import Any, Callable, List, Optional, Union, Tuple
from PIL import Image
from .utils import download_and_extract_archive, verify_str_arg
from .vision import VisionDataset
class Caltech101(VisionDataset):
"""`Caltech 101 <http://www.vision.caltech.edu/Image_Datasets/Caltech10... | torchvision/datasets/caltech.py | import os
import os.path
from typing import Any, Callable, List, Optional, Union, Tuple
from PIL import Image
from .utils import download_and_extract_archive, verify_str_arg
from .vision import VisionDataset
class Caltech101(VisionDataset):
"""`Caltech 101 <http://www.vision.caltech.edu/Image_Datasets/Caltech10... | 0.865181 | 0.396915 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import filer.fields.file
import filer.fields.image
import publications.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.FI... | publications/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import filer.fields.file
import filer.fields.image
import publications.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.FI... | 0.52975 | 0.134151 |
import pyspark
import json
import pandas as pd
import numpy as np
from pyspark.sql.functions import udf
from pyspark.sql.types import ArrayType, StringType
from pyspark.ml.feature import Tokenizer, CountVectorizer, StopWordsRemover, NGram, IDF
from nltk.corpus import stopwords
from string import maketrans
"""
=======... | src/sentimentAnalysis/dataProcessing.py | import pyspark
import json
import pandas as pd
import numpy as np
from pyspark.sql.functions import udf
from pyspark.sql.types import ArrayType, StringType
from pyspark.ml.feature import Tokenizer, CountVectorizer, StopWordsRemover, NGram, IDF
from nltk.corpus import stopwords
from string import maketrans
"""
=======... | 0.603465 | 0.466481 |
from ..broker import Broker
class SensorDatumBroker(Broker):
controller = "sensor_data"
def index(self, **kwargs):
"""Lists the available sensor data. Any of the inputs listed may be be used to narrow the list; other inputs will be ignored. Of the various ways to query lists, using this method is mos... | infoblox_netmri/api/broker/v3_8_0/sensor_datum_broker.py | from ..broker import Broker
class SensorDatumBroker(Broker):
controller = "sensor_data"
def index(self, **kwargs):
"""Lists the available sensor data. Any of the inputs listed may be be used to narrow the list; other inputs will be ignored. Of the various ways to query lists, using this method is mos... | 0.868688 | 0.633495 |
import os
import sys
import glob
import logging
import argparse
import synapse.exc as s_exc
import synapse.glob as s_glob
import synapse.common as s_common
import synapse.telepath as s_telepath
import synapse.lib.output as s_output
import synapse.lib.hashset as s_hashset
logger = logging.getLogger(__name__)
def ma... | synapse/tools/pushfile.py | import os
import sys
import glob
import logging
import argparse
import synapse.exc as s_exc
import synapse.glob as s_glob
import synapse.common as s_common
import synapse.telepath as s_telepath
import synapse.lib.output as s_output
import synapse.lib.hashset as s_hashset
logger = logging.getLogger(__name__)
def ma... | 0.209551 | 0.095181 |
import copy
import logging
from typing import Any, Dict, Optional, Union, List, Tuple
import pickle
from .variant_generator import parse_spec_vars
from ..tune.sample import Categorical, Domain, Float, Integer, LogUniform, \
Quantized, Uniform
from ..tune.trial import flatten_dict, unflatten_dict
logger = ... | flaml/searcher/suggestion.py | import copy
import logging
from typing import Any, Dict, Optional, Union, List, Tuple
import pickle
from .variant_generator import parse_spec_vars
from ..tune.sample import Categorical, Domain, Float, Integer, LogUniform, \
Quantized, Uniform
from ..tune.trial import flatten_dict, unflatten_dict
logger = ... | 0.921123 | 0.292358 |
def ComShrDecom(U, V, E):
delta = max_unicore(U+V, E)
for a in range(1, delta+1):
peelByB(U, V, E, a)
for b in range(1, delta+1):
peelByA(U, V, E, b)
def histogram(tracker):
parallel filter(tracker, 0) # filter out empty elements
parallel sort(tracker)
hist = parallel freqCount(tracker)
return hist
def ... | benchmarks/BiCore/pseudocode.py | def ComShrDecom(U, V, E):
delta = max_unicore(U+V, E)
for a in range(1, delta+1):
peelByB(U, V, E, a)
for b in range(1, delta+1):
peelByA(U, V, E, b)
def histogram(tracker):
parallel filter(tracker, 0) # filter out empty elements
parallel sort(tracker)
hist = parallel freqCount(tracker)
return hist
def ... | 0.433262 | 0.407392 |
import grpc
from yandex.cloud.operation import operation_pb2 as yandex_dot_cloud_dot_operation_dot_operation__pb2
from yandex.cloud.vpc.v1 import route_table_pb2 as yandex_dot_cloud_dot_vpc_dot_v1_dot_route__table__pb2
from yandex.cloud.vpc.v1 import route_table_service_pb2 as yandex_dot_cloud_dot_vpc_dot_v1_dot_route... | yandex/cloud/vpc/v1/route_table_service_pb2_grpc.py | import grpc
from yandex.cloud.operation import operation_pb2 as yandex_dot_cloud_dot_operation_dot_operation__pb2
from yandex.cloud.vpc.v1 import route_table_pb2 as yandex_dot_cloud_dot_vpc_dot_v1_dot_route__table__pb2
from yandex.cloud.vpc.v1 import route_table_service_pb2 as yandex_dot_cloud_dot_vpc_dot_v1_dot_route... | 0.619126 | 0.106435 |
import numpy as np
from pyannote.audio.keras_utils import load_model
from pyannote.audio.signal import Binarize, Peak
from pyannote.audio.features import Precomputed
import my_cluster
from pyannote.core import Annotation
from pyannote.audio.embedding.utils import l2_normalize
from pyannote.database import get_annotated... | diarization_with_neural_approach/optimization/speaker_diarization.py | import numpy as np
from pyannote.audio.keras_utils import load_model
from pyannote.audio.signal import Binarize, Peak
from pyannote.audio.features import Precomputed
import my_cluster
from pyannote.core import Annotation
from pyannote.audio.embedding.utils import l2_normalize
from pyannote.database import get_annotated... | 0.566139 | 0.1933 |
from functools import partial
import re
class Bot(object):
def __init__(self, id):
self.id = id
self.chips = []
def get(self, value):
if not value in self.chips:
self.chips.append(value)
self.chips.sort()
def remove_low(self):
return self.chips.po... | 10.py | from functools import partial
import re
class Bot(object):
def __init__(self, id):
self.id = id
self.chips = []
def get(self, value):
if not value in self.chips:
self.chips.append(value)
self.chips.sort()
def remove_low(self):
return self.chips.po... | 0.531209 | 0.541773 |
from pprint import pformat
from six import iteritems
import re
class InstanceMetaData(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | whoville/cloudbreak/models/instance_meta_data.py | from pprint import pformat
from six import iteritems
import re
class InstanceMetaData(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | 0.562177 | 0.131257 |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: os_keystone_service
short_description: Manage OpenStack Identity services
extends_documentation_fragment: openstack
author: "<NAME> (@SamYaple)"
v... | ansible/modules/cloud/openstack/os_keystone_service.py |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: os_keystone_service
short_description: Manage OpenStack Identity services
extends_documentation_fragment: openstack
author: "<NAME> (@SamYaple)"
v... | 0.586404 | 0.209449 |
from __future__ import print_function
import numpy as np
import pandas as pd
import argparse
import json
import os
import sys
import shortuuid
import platform
import ast
from time import strftime, time
import visdom
import torch
import torch.optim.lr_scheduler as lr_sched
from torch.autograd import Variable
import torc... | main.py | from __future__ import print_function
import numpy as np
import pandas as pd
import argparse
import json
import os
import sys
import shortuuid
import platform
import ast
from time import strftime, time
import visdom
import torch
import torch.optim.lr_scheduler as lr_sched
from torch.autograd import Variable
import torc... | 0.678327 | 0.213767 |
import string, sys, glob, os
import collections
HERE = os.path.dirname(__file__)
if HERE == '':
HERE = '.'
print '############################ %s' % HERE
NT_esn = collections.namedtuple( 'errorShortName', ['name', 'long_name', 'description' ] )
class errorShortNames(object):
def __init__(self, file='config/testS... | ceda_cc/summary.py | import string, sys, glob, os
import collections
HERE = os.path.dirname(__file__)
if HERE == '':
HERE = '.'
print '############################ %s' % HERE
NT_esn = collections.namedtuple( 'errorShortName', ['name', 'long_name', 'description' ] )
class errorShortNames(object):
def __init__(self, file='config/testS... | 0.052936 | 0.190385 |
"""utility script to parse given filenames or string
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import cssutils
import logging
import optparse
import sys
def main(args=None):
"""
Parses given filename(s) or string or URL (using optional encoding) and
prints the parsed style sheet to stdo... | venv/lib/python3.6/site-packages/cssutils/scripts/cssparse.py | """utility script to parse given filenames or string
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import cssutils
import logging
import optparse
import sys
def main(args=None):
"""
Parses given filename(s) or string or URL (using optional encoding) and
prints the parsed style sheet to stdo... | 0.337968 | 0.158956 |