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 |
|---|---|---|---|---|
import pytest
from django.urls import reverse
from pytest_django.asserts import assertContains
from ...folders.tests.factories import FolderFactory
from ..models import Note
from .factories import NoteFactory, UserFactory
@pytest.fixture
def user():
return UserFactory()
@pytest.fixture
def note():
return N... | sib_notes/notes/tests/test_views.py | import pytest
from django.urls import reverse
from pytest_django.asserts import assertContains
from ...folders.tests.factories import FolderFactory
from ..models import Note
from .factories import NoteFactory, UserFactory
@pytest.fixture
def user():
return UserFactory()
@pytest.fixture
def note():
return N... | 0.574156 | 0.643385 |
import pyttsx3
import datetime
import wikipedia
import webbrowser as wb
import os
import speech_recognition as sr
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def speak(audio):
engine.say(audio)
print("Speaking....")
engine.runAndW... | Aspire The AI.py | import pyttsx3
import datetime
import wikipedia
import webbrowser as wb
import os
import speech_recognition as sr
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def speak(audio):
engine.say(audio)
print("Speaking....")
engine.runAndW... | 0.094224 | 0.062674 |
import argparse
import os
import re
import unicodedata
import Levenshtein
import pandas
import pandas as pd
import regex
from bz2file import BZ2File
from tqdm import tqdm
from wiktionary_de_parser import Parser
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--wiktionary', type=str, defau... | testsets/wiktionary_extraction.py | import argparse
import os
import re
import unicodedata
import Levenshtein
import pandas
import pandas as pd
import regex
from bz2file import BZ2File
from tqdm import tqdm
from wiktionary_de_parser import Parser
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--wiktionary', type=str, defau... | 0.212886 | 0.219129 |
no_yes = {'NO': '90004', 'YES': '90003'}
no_yes_1 = {'No': '1066', 'Yes': '1065'}
no_yes_pregnant = {'No': '90081', 'Yes': '90082'}
relationship = {
'AUNT/UNCLE': '90281', 'BROTHER/SISTER': '90285', 'CHILD': '90280',
'COUSIN': '90286', 'FRIEND': '5618', 'GRANDCHILD': '90284', 'GRANDPARENT': '90283',
'NIECE/... | core/common.py | no_yes = {'NO': '90004', 'YES': '90003'}
no_yes_1 = {'No': '1066', 'Yes': '1065'}
no_yes_pregnant = {'No': '90081', 'Yes': '90082'}
relationship = {
'AUNT/UNCLE': '90281', 'BROTHER/SISTER': '90285', 'CHILD': '90280',
'COUSIN': '90286', 'FRIEND': '5618', 'GRANDCHILD': '90284', 'GRANDPARENT': '90283',
'NIECE/... | 0.335024 | 0.115486 |
from .interval_limit import IntervalLimit
def local_compare_to(a, b):
return -1 if a < b else 1 if a > b else 0
class Interval:
@staticmethod
def closed(lower, upper):
return Interval(lower, True, upper, True)
@staticmethod
def open(lower, upper):
return Interval(lower, False, up... | timeandmoneypy/intervals/interval.py | from .interval_limit import IntervalLimit
def local_compare_to(a, b):
return -1 if a < b else 1 if a > b else 0
class Interval:
@staticmethod
def closed(lower, upper):
return Interval(lower, True, upper, True)
@staticmethod
def open(lower, upper):
return Interval(lower, False, up... | 0.84075 | 0.534491 |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: nsxt_policy_ip_block
short_description: Create or Delete a... | plugins/modules/nsxt_policy_ip_block.py |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: nsxt_policy_ip_block
short_description: Create or Delete a... | 0.736211 | 0.123234 |
import pickle
import numpy as np
import theano
import theano.tensor as tt
from theano.tests import unittest_tools as utt
from exoplanet.theano_ops.starry import (
GetCl,
GetClRev,
LimbDark,
RadiusFromOccArea,
)
from exoplanet.theano_ops.driver import SimpleLimbDark
class TestGetCl(utt.InferShapeTes... | tests/theano_ops/starry_test.py |
import pickle
import numpy as np
import theano
import theano.tensor as tt
from theano.tests import unittest_tools as utt
from exoplanet.theano_ops.starry import (
GetCl,
GetClRev,
LimbDark,
RadiusFromOccArea,
)
from exoplanet.theano_ops.driver import SimpleLimbDark
class TestGetCl(utt.InferShapeTes... | 0.4917 | 0.509886 |
import logging
import os
class SkiaGoldProperties(object):
def __init__(self, args):
"""Abstract class to validate and store properties related to Skia Gold.
Args:
args: The parsed arguments from an argparse.ArgumentParser.
"""
self._git_revision = None
self._issue = None
self._patchs... | build/skia_gold_common/skia_gold_properties.py | import logging
import os
class SkiaGoldProperties(object):
def __init__(self, args):
"""Abstract class to validate and store properties related to Skia Gold.
Args:
args: The parsed arguments from an argparse.ArgumentParser.
"""
self._git_revision = None
self._issue = None
self._patchs... | 0.670824 | 0.118131 |
import pandas as pd
df = pd.read_csv(r'C:\Users\Ishant\Desktop\BE Project\Combined_99Acres_V4.csv') # reading the csv file to be cleaned
df2 = df.copy() # create a copy of csv file
row = 1 # initialise row counter for reading each tuple of csv
new_column = df['Location'] + str(1)
# we then add the series to the d... | Data_Cleaning.py | import pandas as pd
df = pd.read_csv(r'C:\Users\Ishant\Desktop\BE Project\Combined_99Acres_V4.csv') # reading the csv file to be cleaned
df2 = df.copy() # create a copy of csv file
row = 1 # initialise row counter for reading each tuple of csv
new_column = df['Location'] + str(1)
# we then add the series to the d... | 0.113383 | 0.402803 |
import sys
from typing import Any
from PySide2.QtCore import QRectF, QRect
from PySide2.QtWidgets import QMessageBox, QLabel
from PySide2.QtGui import Qt, QColor, QPainter, QPen, QPaintEvent, QFontMetrics, QBrush
__author__ = "<NAME>"
QDIALOG_TYPES = (QMessageBox)
WINDOW_BUTTONS_RIGHT: str = 'window_buttons_right'
... | src/qtmodernredux/windowstyle/windowtitlelabel.py | import sys
from typing import Any
from PySide2.QtCore import QRectF, QRect
from PySide2.QtWidgets import QMessageBox, QLabel
from PySide2.QtGui import Qt, QColor, QPainter, QPen, QPaintEvent, QFontMetrics, QBrush
__author__ = "<NAME>"
QDIALOG_TYPES = (QMessageBox)
WINDOW_BUTTONS_RIGHT: str = 'window_buttons_right'
... | 0.584508 | 0.164148 |
import inspect
import re
from collections import Counter
from typing import Any, Callable, Dict, List, Optional, Tuple
from urllib.parse import urljoin
from squall import convertors, params
PARAM_REGEX = re.compile("{([a-zA-Z_][a-zA-Z0-9_]*)(:[a-zA-Z_][a-zA-Z0-9_]*)?}")
class Path:
__slots__ = ["path", "handler... | squall/routing/path.py | import inspect
import re
from collections import Counter
from typing import Any, Callable, Dict, List, Optional, Tuple
from urllib.parse import urljoin
from squall import convertors, params
PARAM_REGEX = re.compile("{([a-zA-Z_][a-zA-Z0-9_]*)(:[a-zA-Z_][a-zA-Z0-9_]*)?}")
class Path:
__slots__ = ["path", "handler... | 0.86164 | 0.187579 |
import os
import numpy as np
import argparse
import random
import tensorflow as tf
from data_generators.data_generator import DataGenerator
from models.maml import MAML
parser = argparse.ArgumentParser()
parser.add_argument('data_path', metavar='DATA',
help='path to data')
parser.add_argument('ckpt_name', metavar... | main.py | import os
import numpy as np
import argparse
import random
import tensorflow as tf
from data_generators.data_generator import DataGenerator
from models.maml import MAML
parser = argparse.ArgumentParser()
parser.add_argument('data_path', metavar='DATA',
help='path to data')
parser.add_argument('ckpt_name', metavar... | 0.516595 | 0.132711 |
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from . import nodes_pb2 as nodes__pb2
class NodesStub(object):
"""Nodes make up the strongDM network, and allow your users to connect securely to your resources. There are two types of nodes:
- **Gateways** are the entry ... | strongdm/nodes_pb2_grpc.py | """Client and server classes corresponding to protobuf-defined services."""
import grpc
from . import nodes_pb2 as nodes__pb2
class NodesStub(object):
"""Nodes make up the strongDM network, and allow your users to connect securely to your resources. There are two types of nodes:
- **Gateways** are the entry ... | 0.776538 | 0.288619 |
import socket
import argparse
import threading
import signal
import json
import requests
import sys
import time
import traceback
from queue import Queue
from contextlib import contextmanager
CLIENT2SERVER = 1
SERVER2CLIENT = 2
running = True
def log(m):
print(m, file=sys.stderr)
def mitm(buff, direction, shar... | attacks/confi_check/mitm.py | import socket
import argparse
import threading
import signal
import json
import requests
import sys
import time
import traceback
from queue import Queue
from contextlib import contextmanager
CLIENT2SERVER = 1
SERVER2CLIENT = 2
running = True
def log(m):
print(m, file=sys.stderr)
def mitm(buff, direction, shar... | 0.211498 | 0.091707 |
from __future__ import absolute_import, unicode_literals
import requests
import json
import os
import sys
import urllib
reload(sys)
sys.setdefaultencoding('utf8')
from flask import Flask, request, abort, render_template
from wechatpy import parse_message, create_reply
from wechatpy.utils import check_signature
from wec... | examples/echo/app.py | from __future__ import absolute_import, unicode_literals
import requests
import json
import os
import sys
import urllib
reload(sys)
sys.setdefaultencoding('utf8')
from flask import Flask, request, abort, render_template
from wechatpy import parse_message, create_reply
from wechatpy.utils import check_signature
from wec... | 0.20091 | 0.0584 |
import logging
import os
import time
from core.results_processor import util
from core.tbmv3 import trace_processor
from tracing.metrics import metric_runner
# Aggregated TBMv2 trace is saved under this name.
HTML_TRACE_NAME = 'trace.html'
# Concatenated proto trace is saved under this name.
CONCATENATED_PROTO_NA... | tools/perf/core/results_processor/compute_metrics.py |
import logging
import os
import time
from core.results_processor import util
from core.tbmv3 import trace_processor
from tracing.metrics import metric_runner
# Aggregated TBMv2 trace is saved under this name.
HTML_TRACE_NAME = 'trace.html'
# Concatenated proto trace is saved under this name.
CONCATENATED_PROTO_NA... | 0.438785 | 0.118947 |
import pytest
import smbclient._pool as pool
from smbprotocol.exceptions import (
InvalidParameter,
)
from .conftest import (
DOMAIN_NAME,
DOMAIN_REFERRAL,
)
@pytest.fixture()
def reset_config():
config = pool.ClientConfig()
client_guid = config.client_guid
username = config.username
pa... | tests/test_smbclient_pool.py |
import pytest
import smbclient._pool as pool
from smbprotocol.exceptions import (
InvalidParameter,
)
from .conftest import (
DOMAIN_NAME,
DOMAIN_REFERRAL,
)
@pytest.fixture()
def reset_config():
config = pool.ClientConfig()
client_guid = config.client_guid
username = config.username
pa... | 0.533397 | 0.127625 |
import unittest
from collections import OrderedDict
import numpy as np
import oneflow.experimental as flow
from test_util import GenArgList
dummy_val = np.random.randn(2, 3)
in_val = np.full((2, 3), -2)
cpu0_device = flow.device("cpu")
gpu0_device = flow.device("cuda")
class DummyModule(flow.nn.Module):
def __... | oneflow/python/test/modules/test_module_to.py | import unittest
from collections import OrderedDict
import numpy as np
import oneflow.experimental as flow
from test_util import GenArgList
dummy_val = np.random.randn(2, 3)
in_val = np.full((2, 3), -2)
cpu0_device = flow.device("cpu")
gpu0_device = flow.device("cuda")
class DummyModule(flow.nn.Module):
def __... | 0.661595 | 0.716746 |
# pylint:disable=redefined-outer-name
import numpy as np
import pytest
from pyei import GoodmansER
@pytest.fixture
def group_and_vote_fractions():
"""Sample group and vote fractions, where every member of the demographic
group votes for the given candidate and every non-member of the
demographic group doe... | test/test_goodmans_er.py | # pylint:disable=redefined-outer-name
import numpy as np
import pytest
from pyei import GoodmansER
@pytest.fixture
def group_and_vote_fractions():
"""Sample group and vote fractions, where every member of the demographic
group votes for the given candidate and every non-member of the
demographic group doe... | 0.726717 | 0.696023 |
import os
import json
import boto3
from boto3.dynamodb.conditions import Key, Attr
from policy import MFAuth
application = os.environ['application']
environment = os.environ['environment']
apps_table_name = '{}-{}-apps'.format(application, environment)
schema_table_name = '{}-{}-schema'.format(application... | source/lambda_app_item.py |
import os
import json
import boto3
from boto3.dynamodb.conditions import Key, Attr
from policy import MFAuth
application = os.environ['application']
environment = os.environ['environment']
apps_table_name = '{}-{}-apps'.format(application, environment)
schema_table_name = '{}-{}-schema'.format(application... | 0.258607 | 0.054525 |
__all__ = ['convert_examples_to_features', 'preprocess_data', 'ALL_TASKS_DIC', 'EXTRA_METRICS',
'RACEHash', 'ReCoRDHash', 'process_MultiRC_answers', 'process_ReCoRD_answers', 'process_RACE_answers']
# Classes being called directly by finetune_bort.py
import os
import re
import json
import logging
import f... | utils/finetune_utils.py |
__all__ = ['convert_examples_to_features', 'preprocess_data', 'ALL_TASKS_DIC', 'EXTRA_METRICS',
'RACEHash', 'ReCoRDHash', 'process_MultiRC_answers', 'process_ReCoRD_answers', 'process_RACE_answers']
# Classes being called directly by finetune_bort.py
import os
import re
import json
import logging
import f... | 0.679179 | 0.317083 |
import gzip
import pickle
import os
from gensim.models.doc2vec import TaggedDocument
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.abspath(os.path.join(os.path.join(CURRENT_DIR, '..'), 'data'))
MODEL_DIR = os.path.join(DATA_DIR, 'models')
VOCAB_DIR = os.path.join(DATA_DIR, 'vocabs')
PICKL... | scripts/manager.py | import gzip
import pickle
import os
from gensim.models.doc2vec import TaggedDocument
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.abspath(os.path.join(os.path.join(CURRENT_DIR, '..'), 'data'))
MODEL_DIR = os.path.join(DATA_DIR, 'models')
VOCAB_DIR = os.path.join(DATA_DIR, 'vocabs')
PICKL... | 0.06777 | 0.07024 |
"""Define graph entity."""
import abc
from collections import OrderedDict
from typing import List
from mindinsight.mindconverter.common.log import logger as log
from mindinsight.mindconverter.graph_based_converter.constant import InputType
from mindinsight.mindconverter.common.exceptions import NodeInputTypeNotSuppor... | mindinsight/mindconverter/graph_based_converter/third_party_graph/base.py | """Define graph entity."""
import abc
from collections import OrderedDict
from typing import List
from mindinsight.mindconverter.common.log import logger as log
from mindinsight.mindconverter.graph_based_converter.constant import InputType
from mindinsight.mindconverter.common.exceptions import NodeInputTypeNotSuppor... | 0.940572 | 0.271333 |
__all__ = ['ParticleInterval']
"""
Contains the ParticleInterval class
"""
from panda3d.core import *
from panda3d.direct import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from .Interval import Interval
class ParticleInterval(Interval):
"""
Use this interval when you want to have gre... | Panda3D-1.10.0/direct/interval/ParticleInterval.py |
__all__ = ['ParticleInterval']
"""
Contains the ParticleInterval class
"""
from panda3d.core import *
from panda3d.direct import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from .Interval import Interval
class ParticleInterval(Interval):
"""
Use this interval when you want to have gre... | 0.679817 | 0.331985 |
# In[ ]:
import pandas as pd
data=pd.read_csv("../../../input/merishnasuwal_breast-cancer-prediction-dataset/Breast_cancer_data.csv", delimiter=",")
# In[ ]:
data.head()
# In[ ]:
data.shape
# In[ ]:
data["diagnosis"].value_counts()
# In[ ]:
data.info()
# In[ ]:
Y=data["diagnosis"]
X=data.drop("di... | relancer-exp/original_notebooks/merishnasuwal_breast-cancer-prediction-dataset/breast-cancer-prediction-decision-tree.py |
# In[ ]:
import pandas as pd
data=pd.read_csv("../../../input/merishnasuwal_breast-cancer-prediction-dataset/Breast_cancer_data.csv", delimiter=",")
# In[ ]:
data.head()
# In[ ]:
data.shape
# In[ ]:
data["diagnosis"].value_counts()
# In[ ]:
data.info()
# In[ ]:
Y=data["diagnosis"]
X=data.drop("di... | 0.484868 | 0.531574 |
import serial
import time
import os
import xmlformatter
import signal
def handler(signum, frame):
print("Forever is over!")
raise Exception("end of time")
def xml_formatter(xml_filename):
#Formatting the xml output
formatter = xmlformatter.Formatter(indent="1", indent_char="\t", encoding_output="UTF-8", preserve=... | test/SerialRead.py | import serial
import time
import os
import xmlformatter
import signal
def handler(signum, frame):
print("Forever is over!")
raise Exception("end of time")
def xml_formatter(xml_filename):
#Formatting the xml output
formatter = xmlformatter.Formatter(indent="1", indent_char="\t", encoding_output="UTF-8", preserve=... | 0.038394 | 0.198666 |
from functools import partial
from typing import Optional, Tuple
from gdsfactory.cell import cell
from gdsfactory.component import Component
from gdsfactory.components.compass import compass
from gdsfactory.tech import LAYER
from gdsfactory.types import ComponentOrFactory, Layer
@cell
def pad(
size: Tuple[float,... | gdsfactory/components/pad.py | from functools import partial
from typing import Optional, Tuple
from gdsfactory.cell import cell
from gdsfactory.component import Component
from gdsfactory.components.compass import compass
from gdsfactory.tech import LAYER
from gdsfactory.types import ComponentOrFactory, Layer
@cell
def pad(
size: Tuple[float,... | 0.92391 | 0.39036 |
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.encoding import force_bytes, force_str
from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth import get_user_model as django_get_user_model
from rest_framework.authtoken.models import Token
f... | drf_registration/utils/users.py | from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.encoding import force_bytes, force_str
from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth import get_user_model as django_get_user_model
from rest_framework.authtoken.models import Token
f... | 0.778986 | 0.129678 |
import numpy as np
import sys
import tensorflow as tf
import time
import os
import pickle as pkl
os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
syspath = os.path.dirname(os.path.realpath(__file__)) + '/../..'
sys.path.insert(0, syspath)
from vbsw_module.functions.df import dataset_weighting
from vbsw_module.algorit... | vbsw_module/algorithms/vbsw.py | import numpy as np
import sys
import tensorflow as tf
import time
import os
import pickle as pkl
os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
syspath = os.path.dirname(os.path.realpath(__file__)) + '/../..'
sys.path.insert(0, syspath)
from vbsw_module.functions.df import dataset_weighting
from vbsw_module.algorit... | 0.412767 | 0.17614 |
from flask import Blueprint, request, jsonify
from os import path
from sense2vec import Sense2Vec
from lib.AutocompleteIndex import AutocompleteIndex
from lib.VectorSearchIndex import VectorSearchIndex
api = Blueprint("api", __name__)
s2v = Sense2Vec().from_disk(path.join(path.dirname(__file__), "../data"))
search_in... | server/api/routes.py | from flask import Blueprint, request, jsonify
from os import path
from sense2vec import Sense2Vec
from lib.AutocompleteIndex import AutocompleteIndex
from lib.VectorSearchIndex import VectorSearchIndex
api = Blueprint("api", __name__)
s2v = Sense2Vec().from_disk(path.join(path.dirname(__file__), "../data"))
search_in... | 0.641085 | 0.218253 |
import math
import cv2
import numpy as np
def is_inside_polygon(polygon, point):
# ref:https://stackoverflow.com/a/2922778/1266873
# int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
# {
# int i, j, c = 0;
# for (i = 0, j = nvert-1; i < nvert; j = i++) {
# if ... | ndu_gate_camera/utility/geometry_helper.py | import math
import cv2
import numpy as np
def is_inside_polygon(polygon, point):
# ref:https://stackoverflow.com/a/2922778/1266873
# int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
# {
# int i, j, c = 0;
# for (i = 0, j = nvert-1; i < nvert; j = i++) {
# if ... | 0.467818 | 0.501404 |
import os
import time
import numpy as np
import pandas as pd
import librosa
import configparser
import soundfile as sf
from keras.models import model_from_json
from keras import backend as K
from sklearn.cluster import AgglomerativeClustering, KMeans, DBSCAN
import sklearn
import tensorflow as tf
from scipy.cluster.hi... | app/src/aipcloud/sound/clustering/clustering.py |
import os
import time
import numpy as np
import pandas as pd
import librosa
import configparser
import soundfile as sf
from keras.models import model_from_json
from keras import backend as K
from sklearn.cluster import AgglomerativeClustering, KMeans, DBSCAN
import sklearn
import tensorflow as tf
from scipy.cluster.hi... | 0.529507 | 0.221414 |
from typing import List, Tuple, Dict
class ScoreContributionSpecification:
"""
Specifies how to calculate the score of a goal-directed benchmark.
The global score will be a weighted average of top-x scores.
This class specifies which top-x to consider and what the corresponding weights are.
"""
... | examples/generation/docking_generation/guacamol_tdc/guacamol/guacamol/goal_directed_score_contributions.py | from typing import List, Tuple, Dict
class ScoreContributionSpecification:
"""
Specifies how to calculate the score of a goal-directed benchmark.
The global score will be a weighted average of top-x scores.
This class specifies which top-x to consider and what the corresponding weights are.
"""
... | 0.960556 | 0.740221 |
from database.database import MongoManager
from pydantic.networks import EmailStr
from auth.manager.auth import authenticate_manager, create_manager, send_sign_up_code_verification
from models.manager import ManagerCreate, ManagerLogin
from auth.constants import REFRESH_TOKEN_EXPIRES_TIME, SECRET_KEY, TOKEN_EXPIRES_TIM... | auth/manager/router.py | from database.database import MongoManager
from pydantic.networks import EmailStr
from auth.manager.auth import authenticate_manager, create_manager, send_sign_up_code_verification
from models.manager import ManagerCreate, ManagerLogin
from auth.constants import REFRESH_TOKEN_EXPIRES_TIME, SECRET_KEY, TOKEN_EXPIRES_TIM... | 0.334916 | 0.075109 |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# M... | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/vega/core/backend_register.py |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# M... | 0.758063 | 0.111628 |
import json
from urllib import parse
from paddleflow.common.exception.paddleflow_sdk_exception import PaddleFlowSDKException
from paddleflow.utils import api_client
from paddleflow.common import api
from paddleflow.queue.queue_info import QueueInfo
from paddleflow.queue.queue_info import GrantInfo
class QueueServiceA... | client/paddleflow/queue/queue_api.py |
import json
from urllib import parse
from paddleflow.common.exception.paddleflow_sdk_exception import PaddleFlowSDKException
from paddleflow.utils import api_client
from paddleflow.common import api
from paddleflow.queue.queue_info import QueueInfo
from paddleflow.queue.queue_info import GrantInfo
class QueueServiceA... | 0.5144 | 0.107813 |
from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edi... | spark_auto_mapper_fhir/value_sets/role_class_partitive.py | from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edi... | 0.7874 | 0.263831 |
import os
from plotly.graph_objs import Bar, Figure, Layout
from ..memberlookup import message_to_author, id_to_name
from ..statistic import statistic
from ..plotly_helpers import marker, try_saving_plotly_figure
class Total(object):
def __init__(self, author):
self.author = author
self.hearts_r... | groupmestats/statistics/heartsreceivedplot.py | import os
from plotly.graph_objs import Bar, Figure, Layout
from ..memberlookup import message_to_author, id_to_name
from ..statistic import statistic
from ..plotly_helpers import marker, try_saving_plotly_figure
class Total(object):
def __init__(self, author):
self.author = author
self.hearts_r... | 0.356447 | 0.133641 |
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_databas... | gen/joyride_pb2.py | """Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_databas... | 0.282196 | 0.091707 |
import sys
import xbmc
import xbmcgui
import xbmcaddon
import time
import kodi
import log_utils
import utils
from salts_lib import salts_utils
from salts_lib import image_proxy
from salts_lib import utils2
from salts_lib.utils2 import i18n
from salts_lib.constants import MODES
from salts_lib.db_utils import DB_Connecti... | plugin.video.saltsrd.lite/service.py | import sys
import xbmc
import xbmcgui
import xbmcaddon
import time
import kodi
import log_utils
import utils
from salts_lib import salts_utils
from salts_lib import image_proxy
from salts_lib import utils2
from salts_lib.utils2 import i18n
from salts_lib.constants import MODES
from salts_lib.db_utils import DB_Connecti... | 0.225843 | 0.065635 |
from pathlib import Path
from typing import Dict, Iterator, List, Optional, Tuple, Union
import numpy as np
import tensorflow as tf
import tensorflow.python.util.deprecation as deprecation
import tensorflow_probability as tfp
from tqdm import tqdm
from ..datalib.metrics import MetricAnalyser
deprecation._PRINT_DEPRE... | unlockgnn/gp/gp_trainer.py | from pathlib import Path
from typing import Dict, Iterator, List, Optional, Tuple, Union
import numpy as np
import tensorflow as tf
import tensorflow.python.util.deprecation as deprecation
import tensorflow_probability as tfp
from tqdm import tqdm
from ..datalib.metrics import MetricAnalyser
deprecation._PRINT_DEPRE... | 0.971766 | 0.616503 |
import pytest
from click.testing import CliRunner
import os
import json
from .utils import git_repo
from keras.layers import Dense, Flatten, Reshape, Input, LSTM, Embedding, Input, Concatenate
from keras.models import Sequential, Model
from keras import backend as K
import wandb
from wandb import wandb_run
from wandb.k... | tests/test_keras.py | import pytest
from click.testing import CliRunner
import os
import json
from .utils import git_repo
from keras.layers import Dense, Flatten, Reshape, Input, LSTM, Embedding, Input, Concatenate
from keras.models import Sequential, Model
from keras import backend as K
import wandb
from wandb import wandb_run
from wandb.k... | 0.691289 | 0.380068 |
from typing import Union
import numpy as np
from numpy import ndarray
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from .base import TK2Conv2D, TK2Linear
from ..tn_module import LambdaLayer
class TK2Block(nn.Module):
def __init__(self, c_in: int, c_out: int, r: in... | tednet/tnn/tucker2/tk2_resnet.py | from typing import Union
import numpy as np
from numpy import ndarray
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from .base import TK2Conv2D, TK2Linear
from ..tn_module import LambdaLayer
class TK2Block(nn.Module):
def __init__(self, c_in: int, c_out: int, r: in... | 0.94933 | 0.566558 |
from rally.common import objects
from rally import consts
from rally.deployment import engine
@engine.configure(name="ExistingCloud")
class ExistingCloud(engine.Engine):
"""Just use an existing OpenStack deployment without deploying anything.
To use ExistingCloud, you should put credential information to th... | rally/deployment/engines/existing.py |
from rally.common import objects
from rally import consts
from rally.deployment import engine
@engine.configure(name="ExistingCloud")
class ExistingCloud(engine.Engine):
"""Just use an existing OpenStack deployment without deploying anything.
To use ExistingCloud, you should put credential information to th... | 0.527803 | 0.37777 |
import click
from fandogh_cli.fandogh_client.secrets_client import list_secret, create_secret, put_secret, delete_secret
from .utils import format_text, TextStyle
from .presenter import present
from .base_commands import FandoghCommand
@click.group("secret")
def secret():
"""Secret management commands"""
@click... | fandogh_cli/secret_commands.py | import click
from fandogh_cli.fandogh_client.secrets_client import list_secret, create_secret, put_secret, delete_secret
from .utils import format_text, TextStyle
from .presenter import present
from .base_commands import FandoghCommand
@click.group("secret")
def secret():
"""Secret management commands"""
@click... | 0.347094 | 0.087642 |
from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.auto... | demo.py | from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.auto... | 0.624637 | 0.397529 |
from torch.utils.data import DataLoader
from utils.parser_utils import get_args
args, device = get_args()
from utils.dataset_tools import check_download_dataset
from data import ConvertToThreeChannels, FewShotLearningDatasetParallel
from torchvision import transforms
from experiment_builder import ExperimentBuilder
... | train_continual_learning_few_shot_system.py | from torch.utils.data import DataLoader
from utils.parser_utils import get_args
args, device = get_args()
from utils.dataset_tools import check_download_dataset
from data import ConvertToThreeChannels, FewShotLearningDatasetParallel
from torchvision import transforms
from experiment_builder import ExperimentBuilder
... | 0.752831 | 0.409516 |
__author__ = '__Rebecca__'
__version__ = '0.0.2'
import os
import json
import time
import requests
import multiprocessing
from bcy_single_climber import bcy_single_climber
'''
链接:https://bcy.net/home/timeline/loaduserposts?since=0&grid_type=timeline&uid=3482886&limit=20
单次最大请求20条
since=0为从头获取
获取第21条时,since=【第20条的i... | bcy_user_climber.py |
__author__ = '__Rebecca__'
__version__ = '0.0.2'
import os
import json
import time
import requests
import multiprocessing
from bcy_single_climber import bcy_single_climber
'''
链接:https://bcy.net/home/timeline/loaduserposts?since=0&grid_type=timeline&uid=3482886&limit=20
单次最大请求20条
since=0为从头获取
获取第21条时,since=【第20条的i... | 0.1532 | 0.046812 |
import builtins
import mock
import numpy as np
from sudoku.sudoku import Sudoku
def is_valid_array(arr):
return np.array_equal(sorted(arr), np.arange(1, 10, 1))
def check_valid_puzzle(board):
# Check that all digits 1-9 are represented in the row and are not duplicated.
for i in range(9):
if ... | tests/test_sudoku.py |
import builtins
import mock
import numpy as np
from sudoku.sudoku import Sudoku
def is_valid_array(arr):
return np.array_equal(sorted(arr), np.arange(1, 10, 1))
def check_valid_puzzle(board):
# Check that all digits 1-9 are represented in the row and are not duplicated.
for i in range(9):
if ... | 0.723602 | 0.598459 |
from mako.template import Template
import os
import importlib.resources as resources
def genRobotCode(projectType, config):
if projectType == "Simple":
with resources.path(__name__, "templates") as path:
with open(os.path.join(path, "Simple", "Robot.java.mako"), "r") as template:
... | frc_characterization/drive_characterization/__init__.py | from mako.template import Template
import os
import importlib.resources as resources
def genRobotCode(projectType, config):
if projectType == "Simple":
with resources.path(__name__, "templates") as path:
with open(os.path.join(path, "Simple", "Robot.java.mako"), "r") as template:
... | 0.509032 | 0.12692 |
from __future__ import unicode_literals
import random
import pyecharts.echarts as option
base_fs = [] # _config_components() 方法中被调用
other_fs = [] # add() 方法中被调用
SYMBOLS = ("rect", "roundRect", "triangle", "diamond", "pin", "arrow")
def collect_other_func(func):
other_fs.append(func)
return func
def ... | pyecharts/echarts/option.py | from __future__ import unicode_literals
import random
import pyecharts.echarts as option
base_fs = [] # _config_components() 方法中被调用
other_fs = [] # add() 方法中被调用
SYMBOLS = ("rect", "roundRect", "triangle", "diamond", "pin", "arrow")
def collect_other_func(func):
other_fs.append(func)
return func
def ... | 0.448909 | 0.263422 |
class HistoryManager():
def __init__(self, maxSize=100):
""" Initialize HistoryManager which saved maximal maxSize states.
The maxSize+1 insertion removes the first
"""
self.history = []
# Position is a value contains the index of the state in a continues way.
# T... | gui/network_manager/history_manager.py | class HistoryManager():
def __init__(self, maxSize=100):
""" Initialize HistoryManager which saved maximal maxSize states.
The maxSize+1 insertion removes the first
"""
self.history = []
# Position is a value contains the index of the state in a continues way.
# T... | 0.61451 | 0.224895 |
import numpy as np
import psyneulink.core.llvm as pnlvm
import psyneulink.core.components.functions.transferfunctions as Functions
import psyneulink.core.globals.keywords as kw
import pytest
from math import e, pi, sqrt
SIZE=5
test_var = np.random.rand(SIZE)
test_matrix = np.random.rand(SIZE, SIZE)
test_matrix_s = np... | tests/functions/test_transfer.py | import numpy as np
import psyneulink.core.llvm as pnlvm
import psyneulink.core.components.functions.transferfunctions as Functions
import psyneulink.core.globals.keywords as kw
import pytest
from math import e, pi, sqrt
SIZE=5
test_var = np.random.rand(SIZE)
test_matrix = np.random.rand(SIZE, SIZE)
test_matrix_s = np... | 0.554712 | 0.394143 |
__all__ = [
"Schedule",
"Season",
"Team",
"team_from_str"
]
class Season(object):
"""Data model of types of seasons"""
POST = 'POST'
PRE = 'PRE'
PRO = 'PRO'
REGULAR = 'REG'
class Schedule(object):
"""Data model of a season's week's schedule"""
def __init__(self, season, we... | ffpicker/data/models.py | __all__ = [
"Schedule",
"Season",
"Team",
"team_from_str"
]
class Season(object):
"""Data model of types of seasons"""
POST = 'POST'
PRE = 'PRE'
PRO = 'PRO'
REGULAR = 'REG'
class Schedule(object):
"""Data model of a season's week's schedule"""
def __init__(self, season, we... | 0.750278 | 0.155399 |
import os.path as op
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_almost_equal)
from nose.tools import assert_true, assert_raises
import warnings
from mne.datasets import testing
from mne import read_forward_solution
from mne.simulatio... | mne/simulation/tests/test_evoked.py |
import os.path as op
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_almost_equal)
from nose.tools import assert_true, assert_raises
import warnings
from mne.datasets import testing
from mne import read_forward_solution
from mne.simulatio... | 0.567218 | 0.574275 |
import pytest
from decouple import config
@pytest.fixture
def ipnetworkxmlschema():
from lxml import etree
schema = config('EPPSCHEMAPATH', '../../../schemas') + '/ipnetwork-1.0.xsd'
xmlschema_doc = etree.parse(schema)
return etree.XMLSchema(xmlschema_doc)
@pytest.fixture
def checkipnetworkcommandx... | tests/unit/ipnetwork/conftest.py | import pytest
from decouple import config
@pytest.fixture
def ipnetworkxmlschema():
from lxml import etree
schema = config('EPPSCHEMAPATH', '../../../schemas') + '/ipnetwork-1.0.xsd'
xmlschema_doc = etree.parse(schema)
return etree.XMLSchema(xmlschema_doc)
@pytest.fixture
def checkipnetworkcommandx... | 0.420243 | 0.188567 |
import csv
import glob
import unittest
import numpy as np
import libpandasafety_py
MAX_RATE_UP = 3
MAX_RATE_DOWN = 3
MAX_STEER = 261
MAX_RT_DELTA = 112
RT_INTERVAL = 250000
MAX_TORQUE_ERROR = 80
def twos_comp(val, bits):
if val >= 0:
return val
else:
return (2**bits) + val
def sign(a):
if a > 0:
... | panda/tests/safety/test_chrysler.py | import csv
import glob
import unittest
import numpy as np
import libpandasafety_py
MAX_RATE_UP = 3
MAX_RATE_DOWN = 3
MAX_STEER = 261
MAX_RT_DELTA = 112
RT_INTERVAL = 250000
MAX_TORQUE_ERROR = 80
def twos_comp(val, bits):
if val >= 0:
return val
else:
return (2**bits) + val
def sign(a):
if a > 0:
... | 0.483161 | 0.320077 |
from itertools import chain
from collections import namedtuple
from .lazyre import LazyReCompile
LinePart = namedtuple("LinePart", ["start", "stop", "word"])
current_word_re = LazyReCompile(r"(?<![)\]\w_.])" r"([\w_][\w0-9._]*[(]?)")
def current_word(cursor_offset, line):
"""the object.attribute.attribute just... | bpython/line.py | from itertools import chain
from collections import namedtuple
from .lazyre import LazyReCompile
LinePart = namedtuple("LinePart", ["start", "stop", "word"])
current_word_re = LazyReCompile(r"(?<![)\]\w_.])" r"([\w_][\w0-9._]*[(]?)")
def current_word(cursor_offset, line):
"""the object.attribute.attribute just... | 0.415373 | 0.38885 |
import numpy as np
x = np.load('Data/x.npy')
y = np.load('Data/y.npy')
from maxsmooth.DCF import smooth
N = 5
result = smooth(x, y, N, base_dir='examples/', fit_type='qp')
"""
We have changed the order of the fit to 5 to illustrate that for
order :math:`{N \leq 5}` and fits with derivatives :math:`{m \geq 2}` const... | example_codes/param_plotter_example.py | import numpy as np
x = np.load('Data/x.npy')
y = np.load('Data/y.npy')
from maxsmooth.DCF import smooth
N = 5
result = smooth(x, y, N, base_dir='examples/', fit_type='qp')
"""
We have changed the order of the fit to 5 to illustrate that for
order :math:`{N \leq 5}` and fits with derivatives :math:`{m \geq 2}` const... | 0.905565 | 0.827201 |
import pytestqt.qtbot
from qtpy import QtCore
import pytest
import qtrio._qt
def test_signal_emits(qtbot: pytestqt.qtbot.QtBot) -> None:
"""qtrio._core.Signal emits."""
class NotQObject:
signal = qtrio.Signal()
instance = NotQObject()
with qtbot.wait_signal(instance.signal, 100):
i... | qtrio/_tests/test_qt.py | import pytestqt.qtbot
from qtpy import QtCore
import pytest
import qtrio._qt
def test_signal_emits(qtbot: pytestqt.qtbot.QtBot) -> None:
"""qtrio._core.Signal emits."""
class NotQObject:
signal = qtrio.Signal()
instance = NotQObject()
with qtbot.wait_signal(instance.signal, 100):
i... | 0.630912 | 0.657786 |
# [START docs_quickstart]
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import sys
import converters.latex
import converters.markdown
# If modifyi... | download-doc.py |
# [START docs_quickstart]
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import sys
import converters.latex
import converters.markdown
# If modifyi... | 0.338186 | 0.172799 |
import numpy as np
from enum import Enum
class BasePalette(Enum):
"""Palette Enum class with additional helper functions"""
def __len__(self):
"""Number of colors in palette"""
return len(self.value)
def __iter__(self):
self.n = 0
return self
def __next__(self... | pyxelate/pal.py | import numpy as np
from enum import Enum
class BasePalette(Enum):
"""Palette Enum class with additional helper functions"""
def __len__(self):
"""Number of colors in palette"""
return len(self.value)
def __iter__(self):
self.n = 0
return self
def __next__(self... | 0.657209 | 0.359308 |
# Copyright 2006, <NAME> <<EMAIL>>
import logging
from twisted.internet import task, defer
from twisted.internet import reactor
import coherence.extern.louie as louie
from coherence.upnp.core.device import RootDevice
_log = logging.getLogger( "coherence.DeviceList" )
# this is a list of root devices!
class Devi... | WebBrickLibs/coherence/Save/DeviceList.py |
# Copyright 2006, <NAME> <<EMAIL>>
import logging
from twisted.internet import task, defer
from twisted.internet import reactor
import coherence.extern.louie as louie
from coherence.upnp.core.device import RootDevice
_log = logging.getLogger( "coherence.DeviceList" )
# this is a list of root devices!
class Devi... | 0.457137 | 0.056081 |
from jinja2 import Environment, FileSystemLoader
from simplemap.html_render import SilentUndefined
import json
import os
import sys
import traceback
TEMPLATES_DIR = FileSystemLoader('simplemap/templates')
ZOOM_DEFAULT = 11
LINES_DEFAULT = []
class Map(object):
def __init__(self, title, center=None, zoom=11, markers=... | simplemap/map.py | from jinja2 import Environment, FileSystemLoader
from simplemap.html_render import SilentUndefined
import json
import os
import sys
import traceback
TEMPLATES_DIR = FileSystemLoader('simplemap/templates')
ZOOM_DEFAULT = 11
LINES_DEFAULT = []
class Map(object):
def __init__(self, title, center=None, zoom=11, markers=... | 0.234231 | 0.084455 |
import argparse
import logging
from common import _utils
def main(argv=None):
parser = argparse.ArgumentParser(description='SageMaker Training Job')
parser.add_argument('--region', type=str.strip, required=True, help='The region where the cluster launches.')
parser.add_argument('--endpoint_config_name', type=s... | components/aws/sagemaker/deploy/src/deploy.py |
import argparse
import logging
from common import _utils
def main(argv=None):
parser = argparse.ArgumentParser(description='SageMaker Training Job')
parser.add_argument('--region', type=str.strip, required=True, help='The region where the cluster launches.')
parser.add_argument('--endpoint_config_name', type=s... | 0.591605 | 0.203312 |
import pprint
import re # noqa: F401
import six
from aylien_news_api.configuration import Configuration
class RelatedStories(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
o... | aylien_news_api/models/related_stories.py | import pprint
import re # noqa: F401
import six
from aylien_news_api.configuration import Configuration
class RelatedStories(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
o... | 0.768907 | 0.105073 |
import json
import uuid
from pgadmin.browser.server_groups.servers.databases.tests import \
utils as database_utils
from pgadmin.utils.route import BaseTestGenerator
from regression import parent_node_dict
from regression.python_test_utils import test_utils as utils
from . import utils as language_utils
from uni... | pgAdmin/pgadmin4/web/pgadmin/browser/server_groups/servers/databases/languages/tests/test_language_add.py |
import json
import uuid
from pgadmin.browser.server_groups.servers.databases.tests import \
utils as database_utils
from pgadmin.utils.route import BaseTestGenerator
from regression import parent_node_dict
from regression.python_test_utils import test_utils as utils
from . import utils as language_utils
from uni... | 0.500977 | 0.178454 |
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Mapping, Optional, Sequence, Type, cast
from uuid import uuid4
from intelliflow.core.application.context.traversal import ContextVisitor
from intelliflow.core.platform.development import HostPlatform
from intelliflow.core.serialization import Ser... | src/intelliflow/core/application/context/node/base.py |
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Mapping, Optional, Sequence, Type, cast
from uuid import uuid4
from intelliflow.core.application.context.traversal import ContextVisitor
from intelliflow.core.platform.development import HostPlatform
from intelliflow.core.serialization import Ser... | 0.899842 | 0.336658 |
import os
import sys
import re
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
# different source folders
version_info = sys.version_info[:2]
source_folder = {
(2, 5): 'py25',
(2, 6): 'py25',
(2, 7): 'py27',
(3, 4): 'py34',
(3, 5): 'py34',
(3, 6)... | setup.py |
import os
import sys
import re
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
# different source folders
version_info = sys.version_info[:2]
source_folder = {
(2, 5): 'py25',
(2, 6): 'py25',
(2, 7): 'py27',
(3, 4): 'py34',
(3, 5): 'py34',
(3, 6)... | 0.328422 | 0.247817 |
import argparse
import os
import logging
import random
import numpy as np
import torch
from torchvision.datasets import MNIST
import torchvision.transforms as xforms
from torch.utils.data import DataLoader
import ttools
import ttools.interfaces
import pydiffvg
LOG = ttools.get_logger(__name__)
pydiffvg.render_pyto... | apps/sketch_gan.py | import argparse
import os
import logging
import random
import numpy as np
import torch
from torchvision.datasets import MNIST
import torchvision.transforms as xforms
from torch.utils.data import DataLoader
import ttools
import ttools.interfaces
import pydiffvg
LOG = ttools.get_logger(__name__)
pydiffvg.render_pyto... | 0.842701 | 0.442215 |
import opensearchpy
import curator
import os
import json
import string, random, tempfile
import time
from click import testing as clicktest
from mock import patch, Mock
import unittest
from . import CuratorTestCase
from . import testvars as testvars
import logging
logger = logging.getLogger(__name__)
host, port = os.... | test/integration/test_count_pattern.py | import opensearchpy
import curator
import os
import json
import string, random, tempfile
import time
from click import testing as clicktest
from mock import patch, Mock
import unittest
from . import CuratorTestCase
from . import testvars as testvars
import logging
logger = logging.getLogger(__name__)
host, port = os.... | 0.365004 | 0.089654 |
from unittest import TestCase
from mkdocs.structure.nav import Section
from ...meta import Meta
from ...navigation import AwesomeNavigation
class TestSetTitle(TestCase):
def setUp(self):
self.section = Section('Section', [])
def test(self):
AwesomeNavigation._set_title(self.section, Meta(t... | mkdocs_awesome_pages_plugin/tests/navigation/test_static.py | from unittest import TestCase
from mkdocs.structure.nav import Section
from ...meta import Meta
from ...navigation import AwesomeNavigation
class TestSetTitle(TestCase):
def setUp(self):
self.section = Section('Section', [])
def test(self):
AwesomeNavigation._set_title(self.section, Meta(t... | 0.563618 | 0.355523 |
import csv
import io
import typing
import audeer
import audfactory.core.api as audfactory
# Skip doctests until we have public lookup tables
__doctest_skip__ = ['*']
LOOKUP_EXT = 'csv'
class Lookup:
r"""Lookup table for managing artifact flavors on Artifactory.
It creates one row for every flavor,
... | audfactory/core/lookup.py | import csv
import io
import typing
import audeer
import audfactory.core.api as audfactory
# Skip doctests until we have public lookup tables
__doctest_skip__ = ['*']
LOOKUP_EXT = 'csv'
class Lookup:
r"""Lookup table for managing artifact flavors on Artifactory.
It creates one row for every flavor,
... | 0.836955 | 0.382516 |
import collections
import functools
import itertools
import json
import operator
import pathlib
import subprocess
import sys
import pytest
PATH = pathlib.Path(".pytest-deps")
DEPS = set()
TEST_FILES = set()
def pytest_addoption(parser):
group = parser.getgroup("run-changed")
group.addoption(
"--chan... | pytest_run_changed/__init__.py | import collections
import functools
import itertools
import json
import operator
import pathlib
import subprocess
import sys
import pytest
PATH = pathlib.Path(".pytest-deps")
DEPS = set()
TEST_FILES = set()
def pytest_addoption(parser):
group = parser.getgroup("run-changed")
group.addoption(
"--chan... | 0.27914 | 0.158109 |
import argparse
from gym.spaces import Dict, Discrete, Tuple, MultiDiscrete
import logging
import os
import ray
from ray import tune
from ray.tune import register_env
from ray.rllib.algorithms.qmix import QMixConfig
from ray.rllib.env.multi_agent_env import ENV_STATE
from ray.rllib.examples.env.two_step_game import Tw... | rllib/examples/two_step_game.py | import argparse
from gym.spaces import Dict, Discrete, Tuple, MultiDiscrete
import logging
import os
import ray
from ray import tune
from ray.tune import register_env
from ray.rllib.algorithms.qmix import QMixConfig
from ray.rllib.env.multi_agent_env import ENV_STATE
from ray.rllib.examples.env.two_step_game import Tw... | 0.712832 | 0.22465 |
import unittest
import sys
import itertools
import time
import os
from streamsx.topology.topology import *
from streamsx.topology.tester import Tester
from streamsx.topology import schema
import streamsx.topology.context
import streamsx.spl.op as op
class TestPending(unittest.TestCase):
_multiprocess_can_split_ ... | test/python/topology/test2_pending.py | import unittest
import sys
import itertools
import time
import os
from streamsx.topology.topology import *
from streamsx.topology.tester import Tester
from streamsx.topology import schema
import streamsx.topology.context
import streamsx.spl.op as op
class TestPending(unittest.TestCase):
_multiprocess_can_split_ ... | 0.380183 | 0.39257 |
from urllib.parse import urlparse
from google.cloud import storage
import numpy as np
import resampy
import tensorflow as tf
import urllib.request
import itertools
import io
import jsonlines
from pydub import AudioSegment
import yamnet.params as yamnet_params
import yamnet.yamnet as yamnet_model
import os
from argp... | galvasr2/yamnet/inference.py | from urllib.parse import urlparse
from google.cloud import storage
import numpy as np
import resampy
import tensorflow as tf
import urllib.request
import itertools
import io
import jsonlines
from pydub import AudioSegment
import yamnet.params as yamnet_params
import yamnet.yamnet as yamnet_model
import os
from argp... | 0.52902 | 0.145479 |
import time
from urllib.parse import urlparse
from Jumpscale import j
from .ZeroOSClient import ZeroOSClient
class ZeroOSFactory(j.application.JSBaseConfigsClass):
"""
"""
_CHILDCLASS = ZeroOSClient
__jslocation__ = "j.clients.zos"
def get_by_id(self, node_id):
directory = j.clients.thr... | Jumpscale/clients/zero_os/ZeroOSClientFactory.py | import time
from urllib.parse import urlparse
from Jumpscale import j
from .ZeroOSClient import ZeroOSClient
class ZeroOSFactory(j.application.JSBaseConfigsClass):
"""
"""
_CHILDCLASS = ZeroOSClient
__jslocation__ = "j.clients.zos"
def get_by_id(self, node_id):
directory = j.clients.thr... | 0.305905 | 0.112381 |
import matplotlib.pyplot as plt
import numpy as np
from getopt import gnu_getopt as getopt
import sys
# parse command-line arguments
try:
optlist,args = getopt(sys.argv[1:], ':', ['verbose'])
assert len(args) < 2
except (AssertionError):
sys.exit(__doc__)
if len(args) > 0:
fname = args[0]
else:
fn... | readtapemonitor.py | import matplotlib.pyplot as plt
import numpy as np
from getopt import gnu_getopt as getopt
import sys
# parse command-line arguments
try:
optlist,args = getopt(sys.argv[1:], ':', ['verbose'])
assert len(args) < 2
except (AssertionError):
sys.exit(__doc__)
if len(args) > 0:
fname = args[0]
else:
fn... | 0.1069 | 0.349783 |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import random
import numpy as np
from tensorflow.keras.layers import *
from tensorflow.keras.activations import *
from tensorflow.keras.models import *
from tensorflow.keras.optimizers import *
from tensorflow.keras.initializers import *
from tensorflow.keras.callb... | 4_DeepLearning-Advanced/1-Gewichte_initialisieren.py | import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import random
import numpy as np
from tensorflow.keras.layers import *
from tensorflow.keras.activations import *
from tensorflow.keras.models import *
from tensorflow.keras.optimizers import *
from tensorflow.keras.initializers import *
from tensorflow.keras.callb... | 0.765681 | 0.459137 |
veiculo_lv = {}
class Veiculo:
#Cadastro do veiculo
def __init__(self,tipo_veiculo:str='c',modelo_veiculo:str='s',cor_veiculo:str='pt',placa_veiculo:str='r',tipo_combustivel:str='gc',potencia_motor:str='',ano_veiculo:str='2015',reserva:bool=False,nao_cadastrar:bool=False):
'''
***nao_... | CODE/Veiculo.py | veiculo_lv = {}
class Veiculo:
#Cadastro do veiculo
def __init__(self,tipo_veiculo:str='c',modelo_veiculo:str='s',cor_veiculo:str='pt',placa_veiculo:str='r',tipo_combustivel:str='gc',potencia_motor:str='',ano_veiculo:str='2015',reserva:bool=False,nao_cadastrar:bool=False):
'''
***nao_... | 0.086579 | 0.169543 |
from pathlib import Path
from pickle import dump, load, HIGHEST_PROTOCOL
from os.path import exists
from googleapiclient.discovery import build, HttpError
from src.spacy_utils import PatternNotFoundException
from src.semantic_sequence import SemanticSequence
SEARCH_REQ_FOLDER = '.searchRequests' # Savefolder of searc... | src/requester.py | from pathlib import Path
from pickle import dump, load, HIGHEST_PROTOCOL
from os.path import exists
from googleapiclient.discovery import build, HttpError
from src.spacy_utils import PatternNotFoundException
from src.semantic_sequence import SemanticSequence
SEARCH_REQ_FOLDER = '.searchRequests' # Savefolder of searc... | 0.566738 | 0.296565 |
import pandas as pd
import re
from jinja2 import Environment, FileSystemLoader, select_autoescape
env = Environment(
loader=FileSystemLoader('templates'),
autoescape=select_autoescape(['html', 'xml'])
)
template = env.get_template("index.html")
the_index = pd.read_csv('annotation_index.csv').dropna()
class... | index.py | import pandas as pd
import re
from jinja2 import Environment, FileSystemLoader, select_autoescape
env = Environment(
loader=FileSystemLoader('templates'),
autoescape=select_autoescape(['html', 'xml'])
)
template = env.get_template("index.html")
the_index = pd.read_csv('annotation_index.csv').dropna()
class... | 0.157752 | 0.154567 |
from unittest import mock
import io
import pytest
from django.core.management import call_command
from great_components.janitor.management.commands import helpers, settings_shake
@pytest.fixture(autouse=True)
def mock_get_settings_source_code():
patched = mock.patch.object(
helpers,
'get_setting... | tests/janitor/management/commands/test_settings_shake.py | from unittest import mock
import io
import pytest
from django.core.management import call_command
from great_components.janitor.management.commands import helpers, settings_shake
@pytest.fixture(autouse=True)
def mock_get_settings_source_code():
patched = mock.patch.object(
helpers,
'get_setting... | 0.641647 | 0.359027 |
from django import VERSION
from django.db.models.signals import post_save, pre_save
def reset_instance(instance, *args, **kwargs):
"""
Called on the post_save signal. Calls the instance's _reset_state method
"""
instance._reset_state()
class DirtyFieldsMixin(object):
"""
Gives dirty field tr... | dirtyfields/dirtyfields.py | from django import VERSION
from django.db.models.signals import post_save, pre_save
def reset_instance(instance, *args, **kwargs):
"""
Called on the post_save signal. Calls the instance's _reset_state method
"""
instance._reset_state()
class DirtyFieldsMixin(object):
"""
Gives dirty field tr... | 0.757256 | 0.176246 |
from osmclient.common import utils
from osmclient.common import wait as WaitForStatus
from osmclient.common.exceptions import ClientException
from osmclient.common.exceptions import NotFound
import json
class SdnController(object):
def __init__(self, http=None, client=None):
self._http = http
self... | src/osmclient/sol005/sdncontroller.py | from osmclient.common import utils
from osmclient.common import wait as WaitForStatus
from osmclient.common.exceptions import ClientException
from osmclient.common.exceptions import NotFound
import json
class SdnController(object):
def __init__(self, http=None, client=None):
self._http = http
self... | 0.352759 | 0.040846 |
from nltk.stem import WordNetLemmatizer
import fractions
import operator
from fuzzywuzzy import fuzz, process
import requests
import re
from ..models import FoodDescription, Tag
from . import fpdb
lemmer = WordNetLemmatizer()
def tokenize(text):
"""
First splits on r',|\.|and', strips the result, and removes... | app/fplib/nlp.py | from nltk.stem import WordNetLemmatizer
import fractions
import operator
from fuzzywuzzy import fuzz, process
import requests
import re
from ..models import FoodDescription, Tag
from . import fpdb
lemmer = WordNetLemmatizer()
def tokenize(text):
"""
First splits on r',|\.|and', strips the result, and removes... | 0.511473 | 0.257427 |
import gzip
import itertools
import os
import re
import struct
import tempfile
import typing as ty
import urllib.request
from fastnumbers import int
from filefetcher.manager import BuildTask
import lmdb
import msgpack
import pysam
RSID_CAPTURE = re.compile(r'RS=(\d+);?')
# The new dbSNP format uses refseq identifie... | zorp/loaders/make_rsid_lookup.py | import gzip
import itertools
import os
import re
import struct
import tempfile
import typing as ty
import urllib.request
from fastnumbers import int
from filefetcher.manager import BuildTask
import lmdb
import msgpack
import pysam
RSID_CAPTURE = re.compile(r'RS=(\d+);?')
# The new dbSNP format uses refseq identifie... | 0.474631 | 0.211539 |
import os
import gzip
import tarfile
import pickle
import numpy as np
import matplotlib.pyplot as plt
from dezero.utils import get_file, cache_dir
from dezero.transforms import Compose, Flatten, ToFloat, Normalize
# =============================================================================
# Base class
# ==========... | dezero/datasets.py | import os
import gzip
import tarfile
import pickle
import numpy as np
import matplotlib.pyplot as plt
from dezero.utils import get_file, cache_dir
from dezero.transforms import Compose, Flatten, ToFloat, Normalize
# =============================================================================
# Base class
# ==========... | 0.599016 | 0.431165 |
from typing import Dict
from base_collectors import JenkinsPluginSourceUpToDatenessCollector, SourceCollector
from collector_utilities.type import URL
from source_model import Entity, SourceMeasurement, SourceResponses
class OWASPDependencyCheckJenkinsPluginSecurityWarnings(SourceCollector):
"""OWASP Dependency... | components/collector/src/source_collectors/api_source_collectors/owasp_dependency_check_jenkins_plugin.py |
from typing import Dict
from base_collectors import JenkinsPluginSourceUpToDatenessCollector, SourceCollector
from collector_utilities.type import URL
from source_model import Entity, SourceMeasurement, SourceResponses
class OWASPDependencyCheckJenkinsPluginSecurityWarnings(SourceCollector):
"""OWASP Dependency... | 0.875628 | 0.110351 |
from cliff import lister
from osc_lib.command import command
from osc_lib import exceptions
from osc_lib import utils
from osc_lib.utils import tags as _tag
from oslo_utils import uuidutils
from octaviaclient.osc.v2 import constants as const
from octaviaclient.osc.v2 import utils as v2_utils
HTTP_METHODS = ['GET', 'P... | octaviaclient/osc/v2/health_monitor.py | from cliff import lister
from osc_lib.command import command
from osc_lib import exceptions
from osc_lib import utils
from osc_lib.utils import tags as _tag
from oslo_utils import uuidutils
from octaviaclient.osc.v2 import constants as const
from octaviaclient.osc.v2 import utils as v2_utils
HTTP_METHODS = ['GET', 'P... | 0.52829 | 0.116261 |
from __future__ import absolute_import
import errno
import io
import os
import re
import requests
PNG_TYPE = "image/png"
JPEG_TYPE = "image/jpeg"
FILE_TYPES = {
'jpg': JPEG_TYPE,
'jpeg': JPEG_TYPE,
'png': PNG_TYPE,
}
def _ensure_dir(dirname):
try:
os.mkdir(dirname)
except OSError as e:
... | zegami_zeg/run.py | from __future__ import absolute_import
import errno
import io
import os
import re
import requests
PNG_TYPE = "image/png"
JPEG_TYPE = "image/jpeg"
FILE_TYPES = {
'jpg': JPEG_TYPE,
'jpeg': JPEG_TYPE,
'png': PNG_TYPE,
}
def _ensure_dir(dirname):
try:
os.mkdir(dirname)
except OSError as e:
... | 0.402275 | 0.139104 |
import numpy as np
import matplotlib.pyplot as plt
import data_load
import gsw
import oceans as oc
import Internal_wave_properties_REV as iwp
import pandas as pd
# Testdata load
def internal_wave_properties(save_only=True):
ladcp, ctd, bathy = data_load.load_data()
rho_neutral = np.genfromtxt('neutral_rho.c... | lee_wave_analysis1.py | import numpy as np
import matplotlib.pyplot as plt
import data_load
import gsw
import oceans as oc
import Internal_wave_properties_REV as iwp
import pandas as pd
# Testdata load
def internal_wave_properties(save_only=True):
ladcp, ctd, bathy = data_load.load_data()
rho_neutral = np.genfromtxt('neutral_rho.c... | 0.425367 | 0.465995 |
import mock
from oslo_serialization import jsonutils
from oslo_utils import uuidutils
import six
from senlin.common import consts
from senlin.common import exception
from senlin.engine import node as nodem
from senlin.objects import node as node_obj
from senlin.profiles import base as pb
from senlin.tests.unit.common... | senlin/tests/unit/engine/test_node.py |
import mock
from oslo_serialization import jsonutils
from oslo_utils import uuidutils
import six
from senlin.common import consts
from senlin.common import exception
from senlin.engine import node as nodem
from senlin.objects import node as node_obj
from senlin.profiles import base as pb
from senlin.tests.unit.common... | 0.453504 | 0.344251 |
try:
import sys
import os
import click
from tabulate import tabulate
from utilities_common.util_base import UtilHelper
except ImportError as e:
raise ImportError("%s - required module not found" % str(e))
VERSION = '2.0'
ERROR_PERMISSIONS = 1
ERROR_CHASSIS_LOAD = 2
ERROR_NOT_IMPLEMENTED = 3
E... | pddf_fanutil/main.py |
try:
import sys
import os
import click
from tabulate import tabulate
from utilities_common.util_base import UtilHelper
except ImportError as e:
raise ImportError("%s - required module not found" % str(e))
VERSION = '2.0'
ERROR_PERMISSIONS = 1
ERROR_CHASSIS_LOAD = 2
ERROR_NOT_IMPLEMENTED = 3
E... | 0.327346 | 0.07333 |
import os
import re
import argparse
import pandas as pd
import importlib
import yaml
import copy
from zdb.modules.multirun import multidraw
from atsge.build_parallel import build_parallel
import logging
logging.getLogger(__name__).setLevel(logging.INFO)
logging.getLogger("atsge.SGEJobSubmitter").setLevel(logging.INFO... | zdb/scripts/draw_variation.py | import os
import re
import argparse
import pandas as pd
import importlib
import yaml
import copy
from zdb.modules.multirun import multidraw
from atsge.build_parallel import build_parallel
import logging
logging.getLogger(__name__).setLevel(logging.INFO)
logging.getLogger("atsge.SGEJobSubmitter").setLevel(logging.INFO... | 0.183228 | 0.149656 |
from django.conf import settings
from django.utils import translation
import pytest
from mock import Mock, patch
from olympia.amo.tests import TestCase
from olympia.amo.utils import from_string
from olympia.addons.models import Addon
from olympia.translations.templatetags import jinja_helpers
from olympia.translation... | src/olympia/translations/tests/test_helpers.py | from django.conf import settings
from django.utils import translation
import pytest
from mock import Mock, patch
from olympia.amo.tests import TestCase
from olympia.amo.utils import from_string
from olympia.addons.models import Addon
from olympia.translations.templatetags import jinja_helpers
from olympia.translation... | 0.63624 | 0.363506 |
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
from app import app
from apps import theme_explorer as te, text
import util
"""
=====================================================... | apps/bootstrap_templates.py | import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
from app import app
from apps import theme_explorer as te, text
import util
"""
=====================================================... | 0.656218 | 0.160661 |
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
import datasets
import learning
import copy
import argparse
# argparse
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', default='cora', help='Datasets: cora, email, ssets')
parser.a... | plot.py | import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
import datasets
import learning
import copy
import argparse
# argparse
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', default='cora', help='Datasets: cora, email, ssets')
parser.a... | 0.681303 | 0.502563 |
from sfm.decorator import run_if_is_main
from learn_mongodb.db_test import col
@run_if_is_main(__name__)
def prepare_data():
data = [{
"_id": 1,
"title": "abc123",
"isbn": "0001122223334",
"author": {"last": "zzz", "first": "aaa"},
"copies": 5,
}]
col.insert(data)
... | learn_mongodb/p3_aggregation/p2_project.py | from sfm.decorator import run_if_is_main
from learn_mongodb.db_test import col
@run_if_is_main(__name__)
def prepare_data():
data = [{
"_id": 1,
"title": "abc123",
"isbn": "0001122223334",
"author": {"last": "zzz", "first": "aaa"},
"copies": 5,
}]
col.insert(data)
... | 0.413359 | 0.420719 |