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 |
|---|---|---|---|---|
__author__ = 'spacegoing'
import numpy as np
import cv2
from matplotlib import pyplot as plt
class GMM:
'''
This class is a python version of part of (GMM) opencv grabcut.cpp
(opencv/modules/imgproc/src/grabcut.cpp)
Magic numbers in __init__ are:
modelSize = 1 + 3 + 9 # component weight + mean +... | PyMRFLSSVM/GrabCut/GMM_Unary.py | __author__ = 'spacegoing'
import numpy as np
import cv2
from matplotlib import pyplot as plt
class GMM:
'''
This class is a python version of part of (GMM) opencv grabcut.cpp
(opencv/modules/imgproc/src/grabcut.cpp)
Magic numbers in __init__ are:
modelSize = 1 + 3 + 9 # component weight + mean +... | 0.588416 | 0.412057 |
from typing import TYPE_CHECKING, Tuple, Sequence, Iterable, cast, List, Union
import array
import copy
from contextlib import contextmanager
from ezdxf.math import Vector, Matrix44
from ezdxf.math.transformtools import OCSTransform, NonUniformScalingError
from ezdxf.lldxf.attributes import DXFAttr, DXFAttributes, Def... | src/ezdxf/entities/lwpolyline.py | from typing import TYPE_CHECKING, Tuple, Sequence, Iterable, cast, List, Union
import array
import copy
from contextlib import contextmanager
from ezdxf.math import Vector, Matrix44
from ezdxf.math.transformtools import OCSTransform, NonUniformScalingError
from ezdxf.lldxf.attributes import DXFAttr, DXFAttributes, Def... | 0.908791 | 0.201695 |
from copy import deepcopy
from filecmp import cmp
from logging import getLogger
from multiprocessing import Pool
from os import unlink
from os.path import join as path_join
from pathlib import Path
from shutil import copyfile, move
from subprocess import CompletedProcess, run
from tempfile import NamedTemporaryFile
fro... | invoicez/builder.py | from copy import deepcopy
from filecmp import cmp
from logging import getLogger
from multiprocessing import Pool
from os import unlink
from os.path import join as path_join
from pathlib import Path
from shutil import copyfile, move
from subprocess import CompletedProcess, run
from tempfile import NamedTemporaryFile
fro... | 0.654564 | 0.093761 |
import time
import bpy
import mathutils
class RootMotionData(bpy.types.PropertyGroup):
hip = bpy.props.StringProperty(name="Hip Bone")
root = bpy.props.StringProperty(name="Root Bone")
copy = bpy.props.StringProperty(name="Debug Character")
step = bpy.props.IntProperty(name="Step Size", default=3, min... | root_motionist/root_motion.py | import time
import bpy
import mathutils
class RootMotionData(bpy.types.PropertyGroup):
hip = bpy.props.StringProperty(name="Hip Bone")
root = bpy.props.StringProperty(name="Root Bone")
copy = bpy.props.StringProperty(name="Debug Character")
step = bpy.props.IntProperty(name="Step Size", default=3, min... | 0.444083 | 0.199893 |
import json
import ujson
import csv
import re
with open('imdb_movies.json') as json_data:
data = json.load(json_data)
count = 0
imdb_ids = []
remove_length_movies = ["N/A", "1 min", "2 min", "3 min", "4 min", "5 min", "6 min", "7 min", "8 min", "9 min", "10 min", "11 min", "12 min", "13 min", "14 min", "15 m... | omdbapi-python-tool/reduce_movie_json.py | import json
import ujson
import csv
import re
with open('imdb_movies.json') as json_data:
data = json.load(json_data)
count = 0
imdb_ids = []
remove_length_movies = ["N/A", "1 min", "2 min", "3 min", "4 min", "5 min", "6 min", "7 min", "8 min", "9 min", "10 min", "11 min", "12 min", "13 min", "14 min", "15 m... | 0.225672 | 0.187318 |
from Tea.core import TeaCore
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util.client import Client as UtilClient
from alibabacloud_dingtalk.content_1_0 import models as dingtalkcontent__1__0_models
from alibaba... | dingtalk/python/alibabacloud_dingtalk/content_1_0/client.py | from Tea.core import TeaCore
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util.client import Client as UtilClient
from alibabacloud_dingtalk.content_1_0 import models as dingtalkcontent__1__0_models
from alibaba... | 0.529993 | 0.033653 |
import datetime
from typing import Any, Dict, List, Type, TypeVar, Union, cast
import attr
from dateutil.parser import isoparse
from ..models.meta_meta_attr import MetaMetaAttr
from ..models.meta_type_enum import MetaTypeEnum
from ..types import UNSET, Unset
T = TypeVar("T", bound="Meta")
@attr.s(auto_attribs=True... | osidb_bindings/bindings/python_client/models/meta.py | import datetime
from typing import Any, Dict, List, Type, TypeVar, Union, cast
import attr
from dateutil.parser import isoparse
from ..models.meta_meta_attr import MetaMetaAttr
from ..models.meta_type_enum import MetaTypeEnum
from ..types import UNSET, Unset
T = TypeVar("T", bound="Meta")
@attr.s(auto_attribs=True... | 0.657868 | 0.083404 |
import torch
import torch.nn.functional as F
from Layers.STFT import STFT
from Utility.utils import pad_list
class EnergyCalculator(torch.nn.Module):
def __init__(self, fs=16000, n_fft=1024, win_length=None, hop_length=256, window="hann", center=True,
normalized=False, onesided=True, use_token... | TrainingInterfaces/Text_to_Spectrogram/FastSpeech2/EnergyCalculator.py |
import torch
import torch.nn.functional as F
from Layers.STFT import STFT
from Utility.utils import pad_list
class EnergyCalculator(torch.nn.Module):
def __init__(self, fs=16000, n_fft=1024, win_length=None, hop_length=256, window="hann", center=True,
normalized=False, onesided=True, use_token... | 0.935058 | 0.416441 |
from __future__ import print_function
from os.path import basename, splitext, abspath, exists, dirname, join
from os import getpid
from util import logfmt, TemporaryDirectory, getext
from util.scripts import bse_py, antsApplyTransformsDWI_sh
from util.ants import antsRegistrationSyN_sh, antsApplyTransforms, antsRegist... | scripts/epi.py |
from __future__ import print_function
from os.path import basename, splitext, abspath, exists, dirname, join
from os import getpid
from util import logfmt, TemporaryDirectory, getext
from util.scripts import bse_py, antsApplyTransformsDWI_sh
from util.ants import antsRegistrationSyN_sh, antsApplyTransforms, antsRegist... | 0.427516 | 0.092729 |
from typing import Any, Type
import pytest
from pytest_mock import MockFixture
from pait import core, g
from pait.app.base import BaseAppHelper
from pait.model.core import PaitCoreModel
from pait.model.response import PaitBaseResponseModel
def demo() -> None:
pass
app_name: str = "fake_name"
class FakeAppHe... | tests/test_core.py | from typing import Any, Type
import pytest
from pytest_mock import MockFixture
from pait import core, g
from pait.app.base import BaseAppHelper
from pait.model.core import PaitCoreModel
from pait.model.response import PaitBaseResponseModel
def demo() -> None:
pass
app_name: str = "fake_name"
class FakeAppHe... | 0.660172 | 0.262279 |
from pathlib import Path
from typing import Any, Dict, Optional, Union, List, Iterable
from singer_sdk import typing as th # JSON Schema typing helpers
from tap_peloton.client import PelotonStream
# TODO: Delete this is if not using json files for schema definition
SCHEMAS_DIR = Path(__file__).parent / Path("./sch... | tap_peloton/streams.py |
from pathlib import Path
from typing import Any, Dict, Optional, Union, List, Iterable
from singer_sdk import typing as th # JSON Schema typing helpers
from tap_peloton.client import PelotonStream
# TODO: Delete this is if not using json files for schema definition
SCHEMAS_DIR = Path(__file__).parent / Path("./sch... | 0.606382 | 0.199191 |
_four_body_functional_forms = {
# "none": {},
# "zero": {},
# "class2": {},
# "cosine/shift/exp": {},
# "hybrid": {},
# "spherical": {},
# "table": {},
"charmmfsw": {
"form": "K*(1 + cos(n*phi-d))",
"parameters": ["K", "n", "d"],
"units": {
"K": "[ener... | eex/metadata/four_body_terms.py | _four_body_functional_forms = {
# "none": {},
# "zero": {},
# "class2": {},
# "cosine/shift/exp": {},
# "hybrid": {},
# "spherical": {},
# "table": {},
"charmmfsw": {
"form": "K*(1 + cos(n*phi-d))",
"parameters": ["K", "n", "d"],
"units": {
"K": "[ener... | 0.604165 | 0.517205 |
from loguru import logger as log
from config import TABLE_NAME as table
import psycopg2 # подключаем библиотеку для апи к бд (подробности https://www.postgresqltutorial.com/postgresql-python/)
from config import DB_NAME, USER_NAME, USER_PASSWORD, HOST # импортируем данные авторизации
# чтобы все работало нужно скачат... | bot/sql_api.py | from loguru import logger as log
from config import TABLE_NAME as table
import psycopg2 # подключаем библиотеку для апи к бд (подробности https://www.postgresqltutorial.com/postgresql-python/)
from config import DB_NAME, USER_NAME, USER_PASSWORD, HOST # импортируем данные авторизации
# чтобы все работало нужно скачат... | 0.20343 | 0.137532 |
import transformers
from datasets import load_dataset
from datasets import ClassLabel
import random
import pandas as pd
from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer, TrainingArguments
import math
def show_random_elements(dataset, num_examples=10):
"""Show random dataset elements
Args:... | FineTuneLanguageModel/fine_tune_language_CLM.py | import transformers
from datasets import load_dataset
from datasets import ClassLabel
import random
import pandas as pd
from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer, TrainingArguments
import math
def show_random_elements(dataset, num_examples=10):
"""Show random dataset elements
Args:... | 0.728845 | 0.576125 |
from __future__ import division
import copy
import numpy as np
from magni.cs.reconstruction.gamp import config as _conf
from magni.utils.config import Configger as _Configger
from magni.utils.validation import decorate_validation as _decorate_validation
from magni.utils.validation import validate_generic as _generic
... | magni/cs/reconstruction/gamp/_algorithm.py | from __future__ import division
import copy
import numpy as np
from magni.cs.reconstruction.gamp import config as _conf
from magni.utils.config import Configger as _Configger
from magni.utils.validation import decorate_validation as _decorate_validation
from magni.utils.validation import validate_generic as _generic
... | 0.907781 | 0.564579 |
from django.urls import resolve
from django.apps import apps
from django.conf import settings
# Method that extracts a list of all API apps for the project:
def get_user_api_app_permissions(permission_lst):
"""A method that parses a permission set to extract a subset
of API apps.
The method iterates over ... | velkozz_web_api/utils/app_management.py | from django.urls import resolve
from django.apps import apps
from django.conf import settings
# Method that extracts a list of all API apps for the project:
def get_user_api_app_permissions(permission_lst):
"""A method that parses a permission set to extract a subset
of API apps.
The method iterates over ... | 0.846387 | 0.362574 |
from __future__ import unicode_literals, division, absolute_import
import argparse
import datetime
import logging.config
import sys
import django
django.setup()
from django.contrib.auth.models import User
from pdata_app.models import RetrievalRequest, DataRequest
__version__ = '0.1.0b1'
DEFAULT_LOG_LEVEL = loggin... | scripts/update_dreqs/update_dreqs_0108.py | from __future__ import unicode_literals, division, absolute_import
import argparse
import datetime
import logging.config
import sys
import django
django.setup()
from django.contrib.auth.models import User
from pdata_app.models import RetrievalRequest, DataRequest
__version__ = '0.1.0b1'
DEFAULT_LOG_LEVEL = loggin... | 0.375363 | 0.093719 |
import configparser
import importlib.machinery
import importlib.util
import logging
import os
import sys
import sysconfig
from metadata_driver_interface.constants import CONFIG_OPTION
from metadata_driver_interface.exceptions import ConfigError
def parse_config(file_path):
"""Loads the configuration file given a... | metadata_driver_interface/utils.py | import configparser
import importlib.machinery
import importlib.util
import logging
import os
import sys
import sysconfig
from metadata_driver_interface.constants import CONFIG_OPTION
from metadata_driver_interface.exceptions import ConfigError
def parse_config(file_path):
"""Loads the configuration file given a... | 0.242295 | 0.057626 |
import subprocess
import asyncio
import logging
import coloredlogs
import getmac
from dbus_next.aio import MessageBus
from dbus_next import BusType
class WolReceiver(asyncio.DatagramProtocol):
"""Asyncio based Wake On LAN receiver listening on UDP port 9"""
def __init__(self, wol_callback):
super()._... | scratch/wol_listener_dbus.py | import subprocess
import asyncio
import logging
import coloredlogs
import getmac
from dbus_next.aio import MessageBus
from dbus_next import BusType
class WolReceiver(asyncio.DatagramProtocol):
"""Asyncio based Wake On LAN receiver listening on UDP port 9"""
def __init__(self, wol_callback):
super()._... | 0.432063 | 0.131731 |
"""Tests for the Skype main.db history database plugin."""
import unittest
# pylint: disable=unused-import
from plaso.formatters import skype as skype_formatter
from plaso.lib import timelib_test
from plaso.parsers import sqlite
from plaso.parsers.sqlite_plugins import skype
from plaso.parsers.sqlite_plugins import t... | plaso/parsers/sqlite_plugins/skype_test.py | """Tests for the Skype main.db history database plugin."""
import unittest
# pylint: disable=unused-import
from plaso.formatters import skype as skype_formatter
from plaso.lib import timelib_test
from plaso.parsers import sqlite
from plaso.parsers.sqlite_plugins import skype
from plaso.parsers.sqlite_plugins import t... | 0.503662 | 0.339828 |
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from foodgram_project.settings import COUNT_RECIPE
from recipes.forms import RecipeForm
from recipes.models import ... | recipes/views.py | from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from foodgram_project.settings import COUNT_RECIPE
from recipes.forms import RecipeForm
from recipes.models import ... | 0.551332 | 0.135146 |
import numpy as np
import scipy.linalg
from .unitary import Unitary
from .unitary_sequence_entry import UnitarySequenceEntry
class UnitaryDefinitions:
'''
Provides methods to create several commonly-used unitaries.
'''
@staticmethod
def rx(theta: float) -> Unitary:
'''
Rotation ar... | stoqcompiler/unitary/unitary_definitions.py | import numpy as np
import scipy.linalg
from .unitary import Unitary
from .unitary_sequence_entry import UnitarySequenceEntry
class UnitaryDefinitions:
'''
Provides methods to create several commonly-used unitaries.
'''
@staticmethod
def rx(theta: float) -> Unitary:
'''
Rotation ar... | 0.876911 | 0.592902 |
import os
from pprint import pprint
from unittest import TestCase
from pywind.ofgem.form import _make_url
from pywind.ofgem.form_data import FormData
class UrlTest(TestCase):
"""
Tests for the basic url function we use.
"""
def test_01(self):
""" URL Tests """
for case in [
... | tests/form_data_test.py | import os
from pprint import pprint
from unittest import TestCase
from pywind.ofgem.form import _make_url
from pywind.ofgem.form_data import FormData
class UrlTest(TestCase):
"""
Tests for the basic url function we use.
"""
def test_01(self):
""" URL Tests """
for case in [
... | 0.39129 | 0.491578 |
import logging
from absl import app, flags
import numpy as np
import tensorflow as tf
import dual_net
import preprocessing
import utils
# See www.moderndescartes.com/essays/shuffle_viz for discussion on sizing
flags.DEFINE_integer('shuffle_buffer_size', 2000,
'Size of buffer used to shuffle trai... | train.py | import logging
from absl import app, flags
import numpy as np
import tensorflow as tf
import dual_net
import preprocessing
import utils
# See www.moderndescartes.com/essays/shuffle_viz for discussion on sizing
flags.DEFINE_integer('shuffle_buffer_size', 2000,
'Size of buffer used to shuffle trai... | 0.789923 | 0.292412 |
import functools
import codecs
from .types import (
is_bytes,
is_text,
is_string,
)
def force_bytes(value):
if is_bytes(value):
return bytes(value)
elif is_text(value):
return codecs.encode(value, "iso-8859-1")
else:
raise TypeError("Unsupported type: {0}".format(type(... | env/lib/python3.6/site-packages/web3/utils/string.py | import functools
import codecs
from .types import (
is_bytes,
is_text,
is_string,
)
def force_bytes(value):
if is_bytes(value):
return bytes(value)
elif is_text(value):
return codecs.encode(value, "iso-8859-1")
else:
raise TypeError("Unsupported type: {0}".format(type(... | 0.393385 | 0.173673 |
import sys, os
import itertools, operator
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
def tuples_by_dispatch_width(tuples):
ret = []
tuples_sorted = sorted(tuples, key=operator.itemgetter(1))
for key,group in itertools.groupby(tuples_sorted,operator.itemgetter(1)):
... | ex1b/part2/tiled/speedup2.py |
import sys, os
import itertools, operator
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
def tuples_by_dispatch_width(tuples):
ret = []
tuples_sorted = sorted(tuples, key=operator.itemgetter(1))
for key,group in itertools.groupby(tuples_sorted,operator.itemgetter(1)):
... | 0.118156 | 0.237217 |
import time
import typing
from typing import Optional
import torch
import wandb
from rich import print as rich_print
from rich.console import Console
from rich.syntax import Syntax
from src.dataclass import Context
# Color coded tracebacks
# install(show_locals=False, extra_lines=0)
console = Console()
# TODO: All... | src/utils/formatting.py | import time
import typing
from typing import Optional
import torch
import wandb
from rich import print as rich_print
from rich.console import Console
from rich.syntax import Syntax
from src.dataclass import Context
# Color coded tracebacks
# install(show_locals=False, extra_lines=0)
console = Console()
# TODO: All... | 0.710929 | 0.21391 |
import pypinyin
import sys
from tqdm import tqdm
import json
chars = set()
with open('../data/char.txt', 'r', encoding='utf8', errors='ignore') as f:
for c in f.readlines()[0]:
chars.add(c)
# print(chars[:5])
print(len(chars))
def bi_freq():
bi_freq_dic = dict()
with open('../data/corpus.txt', '... | IntelligenceInput/src/build_dict/tri_build.py | import pypinyin
import sys
from tqdm import tqdm
import json
chars = set()
with open('../data/char.txt', 'r', encoding='utf8', errors='ignore') as f:
for c in f.readlines()[0]:
chars.add(c)
# print(chars[:5])
print(len(chars))
def bi_freq():
bi_freq_dic = dict()
with open('../data/corpus.txt', '... | 0.056848 | 0.245119 |
import numpy as np
from keras import backend as K
from util.pose_utils import keys_to_stack, stack_by_keys, pose_index
class BaseGenerator(object):
""" A generator that dynamically creates batches from a list of N examples. """
def __init__(self, N, batch_size, create_y):
"""
Para... | src/generators.py | import numpy as np
from keras import backend as K
from util.pose_utils import keys_to_stack, stack_by_keys, pose_index
class BaseGenerator(object):
""" A generator that dynamically creates batches from a list of N examples. """
def __init__(self, N, batch_size, create_y):
"""
Para... | 0.872714 | 0.457985 |
from vnc_api_test import *
from tcutils.config.vnc_introspect_utils import *
from tcutils.config.svc_mon_introspect_utils import SvcMonInspect
from tcutils.control.cn_introspect_utils import *
from tcutils.agent.vna_introspect_utils import *
from tcutils.collector.opserver_introspect_utils import *
from tcutils.collect... | common/connections.py | from vnc_api_test import *
from tcutils.config.vnc_introspect_utils import *
from tcutils.config.svc_mon_introspect_utils import SvcMonInspect
from tcutils.control.cn_introspect_utils import *
from tcutils.agent.vna_introspect_utils import *
from tcutils.collector.opserver_introspect_utils import *
from tcutils.collect... | 0.299105 | 0.079104 |
from flask import render_template, url_for, flash, redirect, request, Blueprint
from flask_login import login_user, current_user, logout_user, login_required
from ligh import db, bcrypt
from ligh.models import User, Post
from ligh.users.forms import RegistrationForm, LoginForm, UpdateAccountForm, RequestResetForm, Rese... | ligh/users/routes.py | from flask import render_template, url_for, flash, redirect, request, Blueprint
from flask_login import login_user, current_user, logout_user, login_required
from ligh import db, bcrypt
from ligh.models import User, Post
from ligh.users.forms import RegistrationForm, LoginForm, UpdateAccountForm, RequestResetForm, Rese... | 0.378115 | 0.052352 |
import functools
from pathlib import Path
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
from torchvision.transforms import functional as tf
IMG_EXTENSIONS = [
".jpg",
".JPG",
".jpeg",
".JPEG",
".png",
".PNG",
".ppm",
".PPM",
".bmp",
... | models/datasets.py | import functools
from pathlib import Path
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
from torchvision.transforms import functional as tf
IMG_EXTENSIONS = [
".jpg",
".JPG",
".jpeg",
".JPEG",
".png",
".PNG",
".ppm",
".PPM",
".bmp",
... | 0.865523 | 0.412412 |
from enum import Enum
from functools import lru_cache
from typing import List, Optional, Tuple
class Chat(Enum):
PRIVATE = "private"
GROUP = "group"
SUPERGROUP = "supergroup"
CHANNEL = "channel"
class Incoming(Enum):
"""Represents the type of incoming message"""
NEW_MESSAGE = "message"
E... | aiotelegrambot/types.py | from enum import Enum
from functools import lru_cache
from typing import List, Optional, Tuple
class Chat(Enum):
PRIVATE = "private"
GROUP = "group"
SUPERGROUP = "supergroup"
CHANNEL = "channel"
class Incoming(Enum):
"""Represents the type of incoming message"""
NEW_MESSAGE = "message"
E... | 0.822688 | 0.081155 |
from atc_api.utils import get_client_ip
from atc_thrift.ttypes import Corruption
from atc_thrift.ttypes import Delay
from atc_thrift.ttypes import Loss
from atc_thrift.ttypes import Reorder
from atc_thrift.ttypes import Shaping
from atc_thrift.ttypes import TrafficControlledDevice
from atc_thrift.ttypes import TrafficC... | atc/django-atc-api/atc_api/serializers.py | from atc_api.utils import get_client_ip
from atc_thrift.ttypes import Corruption
from atc_thrift.ttypes import Delay
from atc_thrift.ttypes import Loss
from atc_thrift.ttypes import Reorder
from atc_thrift.ttypes import Shaping
from atc_thrift.ttypes import TrafficControlledDevice
from atc_thrift.ttypes import TrafficC... | 0.710528 | 0.158174 |
# pylint: disable=too-many-lines,too-many-ancestors,too-many-public-methods
from ...abstract_osid.repository import queries as abc_repository_queries
from ..osid import queries as osid_queries
class AssetQuery(abc_repository_queries.AssetQuery,
osid_queries.OsidObjectQuery,
osid_que... | dlkit/filesystem_adapter/repository/queries.py | # pylint: disable=too-many-lines,too-many-ancestors,too-many-public-methods
from ...abstract_osid.repository import queries as abc_repository_queries
from ..osid import queries as osid_queries
class AssetQuery(abc_repository_queries.AssetQuery,
osid_queries.OsidObjectQuery,
osid_que... | 0.726037 | 0.306352 |
"""Api lib for simple life."""
import os
import json
import requests
import time
import uuid
from urllib.request import urlopen
mac_address = uuid.UUID(int=uuid.getnode()).hex[-12:]
def nlu_tuling(question, loc="上海"):
"""图灵 API
"""
url = 'http://www.tuling123.com/openapi/api'
data = {
'key'... | chat/apilib.py |
"""Api lib for simple life."""
import os
import json
import requests
import time
import uuid
from urllib.request import urlopen
mac_address = uuid.UUID(int=uuid.getnode()).hex[-12:]
def nlu_tuling(question, loc="上海"):
"""图灵 API
"""
url = 'http://www.tuling123.com/openapi/api'
data = {
'key'... | 0.17037 | 0.138666 |
import asyncio
import typing
import unittest.mock
import arrow
import discord
import discord.ext.commands
import pytest
from tests import mocks
class TestDiscordMocks:
"""Tests for our specialized discord.py mocks."""
@pytest.mark.parametrize(
["mock_class", "counterpart", "mock_args"],
[
... | tests/test_mocks.py | import asyncio
import typing
import unittest.mock
import arrow
import discord
import discord.ext.commands
import pytest
from tests import mocks
class TestDiscordMocks:
"""Tests for our specialized discord.py mocks."""
@pytest.mark.parametrize(
["mock_class", "counterpart", "mock_args"],
[
... | 0.739611 | 0.432423 |
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from django.db.models import Q
from rest_framework.response import Response
from apps.exceptions import ValidationError
from apps.log_databus.constants import EtlConfig
from apps.log_search.... | apps/log_databus/views/collector_views.py | from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from django.db.models import Q
from rest_framework.response import Response
from apps.exceptions import ValidationError
from apps.log_databus.constants import EtlConfig
from apps.log_search.... | 0.397704 | 0.135461 |
# modified from https://github.com/apache/singa/blob/master/examples/cnn/train_cnn.py
import time
from datetime import datetime
import numpy as np
from PIL import Image
from singa import device, opt, tensor
from tqdm import tqdm
import os
from ..proto.utils import parseargs
from .app import Client
from .data import ... | src/client/main.py |
# modified from https://github.com/apache/singa/blob/master/examples/cnn/train_cnn.py
import time
from datetime import datetime
import numpy as np
from PIL import Image
from singa import device, opt, tensor
from tqdm import tqdm
import os
from ..proto.utils import parseargs
from .app import Client
from .data import ... | 0.708213 | 0.494202 |
import httplib
import os
import urlparse
from twitter.common.contextutil import temporary_file_path, open_tar, temporary_file
from twitter.common.quantity import Amount, Data
from twitter.pants.cache.artifact_cache import ArtifactCache
class RESTfulArtifactCache(ArtifactCache):
"""An artifact cache that stores the ... | src/python/twitter/pants/cache/restful_artifact_cache.py | import httplib
import os
import urlparse
from twitter.common.contextutil import temporary_file_path, open_tar, temporary_file
from twitter.common.quantity import Amount, Data
from twitter.pants.cache.artifact_cache import ArtifactCache
class RESTfulArtifactCache(ArtifactCache):
"""An artifact cache that stores the ... | 0.561335 | 0.198996 |
from django.shortcuts import get_object_or_404
from django.views.generic.base import TemplateView
from rest_framework import parsers, renderers, generics, status
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.permissions import ... | demo/project/accounts/views.py | from django.shortcuts import get_object_or_404
from django.views.generic.base import TemplateView
from rest_framework import parsers, renderers, generics, status
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.permissions import ... | 0.606265 | 0.099689 |
import yaml
import argparse
import simplejson
def read_json(filename):
"""
Read the DrugMechDB paths from a .json file
:param filename: str, the path to the json file to be read
:return: dict, the paths as a dictionary object.
"""
with open(filename, 'r') as f_in:
G = simplejson.load... | utils/json_yaml_convert.py | import yaml
import argparse
import simplejson
def read_json(filename):
"""
Read the DrugMechDB paths from a .json file
:param filename: str, the path to the json file to be read
:return: dict, the paths as a dictionary object.
"""
with open(filename, 'r') as f_in:
G = simplejson.load... | 0.540924 | 0.330188 |
import RLlib as RL
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import torch
import os
import shutil
# plot parameters
plt.rcParams.update({
"font.family":
"serif", # use serif/main font for text elements
"text.usetex":
True, # use inline math for ticks
"pgf.rcfonts":
... | nonLinearTest.py | import RLlib as RL
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import torch
import os
import shutil
# plot parameters
plt.rcParams.update({
"font.family":
"serif", # use serif/main font for text elements
"text.usetex":
True, # use inline math for ticks
"pgf.rcfonts":
... | 0.469763 | 0.424233 |
import argparse
import logging
import pygame
import random
import config
import board
import player
class Text(object):
def __init__(self, text, position, **kwargs):
font_name = kwargs.get('font', 'freesansbold.ttf')
font_size = kwargs.get('size', 32)
self.font = pygame.font.Font(font_nam... | game.py | import argparse
import logging
import pygame
import random
import config
import board
import player
class Text(object):
def __init__(self, text, position, **kwargs):
font_name = kwargs.get('font', 'freesansbold.ttf')
font_size = kwargs.get('size', 32)
self.font = pygame.font.Font(font_nam... | 0.504883 | 0.137822 |
from __future__ import print_function
import sys
import os
import argparse
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
from torch.autograd import Variable
from data import VOC_ROOT, VOC_CLASSES, SHIP_CLASSES
f... | test_kaggle.py | from __future__ import print_function
import sys
import os
import argparse
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
from torch.autograd import Variable
from data import VOC_ROOT, VOC_CLASSES, SHIP_CLASSES
f... | 0.44553 | 0.234703 |
import argparse
import imp
import logging
import os
import pipes
import shlex
import devil_chromium
from devil.android import apk_helper
from devil.android import device_errors
from devil.android import device_utils
from devil.android import flag_changer
from devil.android.sdk import intent
from devil.android.sdk imp... | build/android/apk_operations.py |
import argparse
import imp
import logging
import os
import pipes
import shlex
import devil_chromium
from devil.android import apk_helper
from devil.android import device_errors
from devil.android import device_utils
from devil.android import flag_changer
from devil.android.sdk import intent
from devil.android.sdk imp... | 0.2763 | 0.047382 |
import logging
from typing import Dict
from unittest import mock
import pytest
from great_expectations import DataContext
from great_expectations.core.usage_statistics.schemas import (
anonymized_usage_statistics_record_schema,
)
from great_expectations.core.usage_statistics.usage_statistics import (
UsageSta... | tests/core/usage_statistics/test_usage_statistics_handler_methods.py | import logging
from typing import Dict
from unittest import mock
import pytest
from great_expectations import DataContext
from great_expectations.core.usage_statistics.schemas import (
anonymized_usage_statistics_record_schema,
)
from great_expectations.core.usage_statistics.usage_statistics import (
UsageSta... | 0.747984 | 0.423518 |
from dataclasses import dataclass
from typing import List, Dict
from .cards import Suit, Card, Deck, Trick
from .player import Player
from .partners import Partners, TeamID
from .game_events import BaseEvent
@dataclass
class GameState:
dealer: Player = None
bid_winner: Player = None
players: List[Player]... | whist/gamestate.py | from dataclasses import dataclass
from typing import List, Dict
from .cards import Suit, Card, Deck, Trick
from .player import Player
from .partners import Partners, TeamID
from .game_events import BaseEvent
@dataclass
class GameState:
dealer: Player = None
bid_winner: Player = None
players: List[Player]... | 0.859074 | 0.234845 |
import wradlib
import numpy as np
import gc
import sys
def read_trmm(f):
"""Read TRMM data that comes on NetCDF.
Parameters
----------
f : string (TRMM file path)
Returns
-------
out : X, Y, R
Two dimensional arrays of longitudes, latitudes, and rainfall
""... | trmmlib/products.py |
import wradlib
import numpy as np
import gc
import sys
def read_trmm(f):
"""Read TRMM data that comes on NetCDF.
Parameters
----------
f : string (TRMM file path)
Returns
-------
out : X, Y, R
Two dimensional arrays of longitudes, latitudes, and rainfall
""... | 0.525612 | 0.553264 |
import array
import asyncio
import json
import os
import socket
import sys
import tempfile
import threading
from . import remoteloop
class API:
def __init__(self, socket_address, args, interactive):
self.socket_address = socket_address
self.input = args
self.interactive = interactive
... | osbuild/api.py | import array
import asyncio
import json
import os
import socket
import sys
import tempfile
import threading
from . import remoteloop
class API:
def __init__(self, socket_address, args, interactive):
self.socket_address = socket_address
self.input = args
self.interactive = interactive
... | 0.317955 | 0.070848 |
import django_filters
from .models import Ticket
from .custom_filter_field import DateFromToRangeFilter
from django import forms
import datetime
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
def validate_range(value):... | ticket/filters.py | import django_filters
from .models import Ticket
from .custom_filter_field import DateFromToRangeFilter
from django import forms
import datetime
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
def validate_range(value):... | 0.574634 | 0.182863 |
import functools
import numpy as np
import pandas as pd
def parse_engine(engine):
"""
Choose the best engine available and check if it's valid.
Parameters
----------
engine : str
The name of the engine. If ``"auto"`` will favor numba if it's available.
Returns
-------
engine... | verde/utils.py | import functools
import numpy as np
import pandas as pd
def parse_engine(engine):
"""
Choose the best engine available and check if it's valid.
Parameters
----------
engine : str
The name of the engine. If ``"auto"`` will favor numba if it's available.
Returns
-------
engine... | 0.917451 | 0.626981 |
"""STFT feature extractors"""
import numpy as np
from librosa import stft, magphase
from librosa import amplitude_to_db, get_duration
from librosa.util import fix_length
from .base import FeatureExtractor
__all__ = ['STFT', 'STFTMag', 'STFTPhaseDiff']
class STFT(FeatureExtractor):
'''Short-time Fourier Transfo... | Python_library/pumppExtra/feature/fft.py | """STFT feature extractors"""
import numpy as np
from librosa import stft, magphase
from librosa import amplitude_to_db, get_duration
from librosa.util import fix_length
from .base import FeatureExtractor
__all__ = ['STFT', 'STFTMag', 'STFTPhaseDiff']
class STFT(FeatureExtractor):
'''Short-time Fourier Transfo... | 0.938653 | 0.633013 |
"""Implementation of update command for updating bucket settings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
_CORS_HELP_TEXT = """
Sets the Cross-Origin Reso... | lib/surface/storage/buckets/update.py | """Implementation of update command for updating bucket settings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
_CORS_HELP_TEXT = """
Sets the Cross-Origin Reso... | 0.847274 | 0.211519 |
import os
import pathlib
from typing import Any, Dict, List, Type
from setuptools import Command, find_packages, setup, Extension
HERE = pathlib.Path(__file__).parent
HSE_PACKAGE = pathlib.Path("hse2")
# Distribute the generated C source files so that consumers don't necessarily
# need Cython on their system to bu... | setup.py |
import os
import pathlib
from typing import Any, Dict, List, Type
from setuptools import Command, find_packages, setup, Extension
HERE = pathlib.Path(__file__).parent
HSE_PACKAGE = pathlib.Path("hse2")
# Distribute the generated C source files so that consumers don't necessarily
# need Cython on their system to bu... | 0.482185 | 0.160036 |
import os
import sys
import time
import logging
from pathlib import Path
import wandb
import torch
import torch.nn as nn
import torch.onnx
import poptorch
import popdist
import popdist.poptorch
from poptorch import DataLoader
from poptorch.enums import DataLoaderMode
from transformers import GPT2Config, GPT2LMHeadMo... | pytorch/gpt2/inference_gpt2.py |
import os
import sys
import time
import logging
from pathlib import Path
import wandb
import torch
import torch.nn as nn
import torch.onnx
import poptorch
import popdist
import popdist.poptorch
from poptorch import DataLoader
from poptorch.enums import DataLoaderMode
from transformers import GPT2Config, GPT2LMHeadMo... | 0.641759 | 0.10923 |
from django.contrib.auth.models import User
from django.shortcuts import render, render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from reports import UsersReport
from w_report import simple
from django.db.models import Q
from geraldo.gene... | admin/views.py | from django.contrib.auth.models import User
from django.shortcuts import render, render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from reports import UsersReport
from w_report import simple
from django.db.models import Q
from geraldo.gene... | 0.083885 | 0.049336 |
from tomb_csrf.utils import SAFE_HEADERS
from pyramid.httpexceptions import HTTPForbidden
import urllib
REASON_NO_ORIGIN = "Origin checking failed - no Origin or Referer."
REASON_BAD_ORIGIN = "Origin checking failed - {} does not match {}."
REASON_BAD_TOKEN = "CSRF token missing or incorrect."
class InvalidCSRF(HTT... | tomb_csrf/csrf.py | from tomb_csrf.utils import SAFE_HEADERS
from pyramid.httpexceptions import HTTPForbidden
import urllib
REASON_NO_ORIGIN = "Origin checking failed - no Origin or Referer."
REASON_BAD_ORIGIN = "Origin checking failed - {} does not match {}."
REASON_BAD_TOKEN = "CSRF token missing or incorrect."
class InvalidCSRF(HTT... | 0.387343 | 0.09611 |
from django.test import TestCase
from orchestrator.services.results.main import main
class ResultsTest(TestCase):
def test_ok(self):
payload = {
"portVals": [
{"value": 10000.0, "timestamp": "01/01/2020"},
{"value": 10000.0, "timestamp": "01/02/2020"},
... | orchestrator/tests/test_results.py | from django.test import TestCase
from orchestrator.services.results.main import main
class ResultsTest(TestCase):
def test_ok(self):
payload = {
"portVals": [
{"value": 10000.0, "timestamp": "01/01/2020"},
{"value": 10000.0, "timestamp": "01/02/2020"},
... | 0.516839 | 0.435841 |
import re
import time
import asyncio
from collections import defaultdict
import netdev
from decouple import config
import yaml
INVENTORY_FILE = 'mac_address_table_inventory.yml'
TEST_IP_LIST = ['10.48.18.24', '10.48.18.30']
GLOBAL_DEVICE_PARAMS = {
'device_type': 'cisco_ios',
'username': config('US... | async/collect_mac_address_tables/collection_async.py | import re
import time
import asyncio
from collections import defaultdict
import netdev
from decouple import config
import yaml
INVENTORY_FILE = 'mac_address_table_inventory.yml'
TEST_IP_LIST = ['10.48.18.24', '10.48.18.30']
GLOBAL_DEVICE_PARAMS = {
'device_type': 'cisco_ios',
'username': config('US... | 0.427994 | 0.188175 |
import os
import os.path as osp
from torchvision.datasets.folder import IMG_EXTENSIONS, make_dataset
from .builder import DATASETS
from .video_dataset import VideoDataset
@DATASETS.register_module()
class ImageDataset(VideoDataset):
def __init__(self, ann_file, pipeline, start_index=0, **kwargs):
super... | mmaction/datasets/image_dataset.py | import os
import os.path as osp
from torchvision.datasets.folder import IMG_EXTENSIONS, make_dataset
from .builder import DATASETS
from .video_dataset import VideoDataset
@DATASETS.register_module()
class ImageDataset(VideoDataset):
def __init__(self, ann_file, pipeline, start_index=0, **kwargs):
super... | 0.710528 | 0.220363 |
import json
import cv2
import os
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
class Label:
def __init__(self, p1=None, p2=None, p3=None, p4=None, name=None, path=None):
self.p1 = p1
self.p2 = p2
self.p3 = p3
self.p4 = p4
self.name = name
... | src/utils/manual_label_plate.py | import json
import cv2
import os
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
class Label:
def __init__(self, p1=None, p2=None, p3=None, p4=None, name=None, path=None):
self.p1 = p1
self.p2 = p2
self.p3 = p3
self.p4 = p4
self.name = name
... | 0.303525 | 0.272738 |
import random
import string
from typing import Tuple
from unittest.mock import patch
from ax.core.base_trial import TrialStatus
from ax.core.experiment import Experiment
from ax.modelbridge.generation_strategy import GenerationStrategy
from ax.service.utils.with_db_settings_base import WithDBSettingsBase
from ax.stor... | ax/service/tests/test_with_db_settings_base.py |
import random
import string
from typing import Tuple
from unittest.mock import patch
from ax.core.base_trial import TrialStatus
from ax.core.experiment import Experiment
from ax.modelbridge.generation_strategy import GenerationStrategy
from ax.service.utils.with_db_settings_base import WithDBSettingsBase
from ax.stor... | 0.802439 | 0.198181 |
import os
import sys
import struct
import socket
import SocketServer
import ssl
import threading
import tempfile
import logging
SO_PEERCRED = 17
from SocketServer import TCPServer, UnixStreamServer, ThreadingMixIn, ThreadingTCPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
from lib.sock2proc import Pr... | agt/cloudauth.py | import os
import sys
import struct
import socket
import SocketServer
import ssl
import threading
import tempfile
import logging
SO_PEERCRED = 17
from SocketServer import TCPServer, UnixStreamServer, ThreadingMixIn, ThreadingTCPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
from lib.sock2proc import Pr... | 0.06641 | 0.084985 |
import hashlib
import os
import tempfile
from azure.confidentialledger import (
LedgerUserRole,
TransactionState,
)
from .constants import NETWORK_CERTIFICATE, USER_CERTIFICATE
from .testcase import ConfidentialLedgerTestCase
CONFIDENTIAL_LEDGER_URL = "https://fake-confidential-ledger.azure.com"
class Conf... | sdk/confidentialledger/azure-confidentialledger/tests/_shared/client_test_common.py | import hashlib
import os
import tempfile
from azure.confidentialledger import (
LedgerUserRole,
TransactionState,
)
from .constants import NETWORK_CERTIFICATE, USER_CERTIFICATE
from .testcase import ConfidentialLedgerTestCase
CONFIDENTIAL_LEDGER_URL = "https://fake-confidential-ledger.azure.com"
class Conf... | 0.45181 | 0.211112 |
"""Op compute time files parser."""
import os
import stat
from mindspore.profiler.common.util import fwrite_format
from mindspore.profiler.common.exceptions.exceptions import ProfilerFileNotFoundException, \
ProfilerIOException
from mindspore import log as logger
from mindspore.profiler.common.validator.validate_pa... | mindspore/profiler/parser/optime_parser.py | """Op compute time files parser."""
import os
import stat
from mindspore.profiler.common.util import fwrite_format
from mindspore.profiler.common.exceptions.exceptions import ProfilerFileNotFoundException, \
ProfilerIOException
from mindspore import log as logger
from mindspore.profiler.common.validator.validate_pa... | 0.731155 | 0.223536 |
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")
import copy
import numpy as np
from gurobipy import *
def to_numpy(gurobi_variable):
temp = [gurobi_variable[i].x for i in gurobi_variable.keys()]
return np.asarray(temp)
def MasterProblem(horizon=20, init_vol=[1000, 1000, 1000]... | ctrl_distributed/testing_dist3p.py | import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")
import copy
import numpy as np
from gurobipy import *
def to_numpy(gurobi_variable):
temp = [gurobi_variable[i].x for i in gurobi_variable.keys()]
return np.asarray(temp)
def MasterProblem(horizon=20, init_vol=[1000, 1000, 1000]... | 0.319652 | 0.44734 |
board = [
["-", "-", "-"],
["-", "-", "-"],
["-", "-", "-"]
]
user = True # when true it refers to x, otherwise o
turns = 0
def print_board(board):
for row in board:
for slot in row:
print(f"{slot} ", end="")
print()
def quit(user_input):
if user_input.lower() == "q":
print("Thanks for p... | tictactoe.py | board = [
["-", "-", "-"],
["-", "-", "-"],
["-", "-", "-"]
]
user = True # when true it refers to x, otherwise o
turns = 0
def print_board(board):
for row in board:
for slot in row:
print(f"{slot} ", end="")
print()
def quit(user_input):
if user_input.lower() == "q":
print("Thanks for p... | 0.240596 | 0.229018 |
import json
import boto3
from faassupervisor.utils import ConfigUtils
class Batch():
"""Used for defining Batch jobs in the Batch environment."""
# pylint: disable=too-few-public-methods
def __init__(self, lambda_instance):
self.lambda_instance = lambda_instance
self.script = self._get_u... | faassupervisor/faas/aws_lambda/batch.py | import json
import boto3
from faassupervisor.utils import ConfigUtils
class Batch():
"""Used for defining Batch jobs in the Batch environment."""
# pylint: disable=too-few-public-methods
def __init__(self, lambda_instance):
self.lambda_instance = lambda_instance
self.script = self._get_u... | 0.619241 | 0.112991 |
from __future__ import absolute_import, division, print_function
import unittest
import os
from typing import Sequence, Tuple
import shapely.geometry as geom
import numpy as np
from kraken.lib.segmentation import is_in_region, reading_order, topsort
thisfile = os.path.abspath(os.path.dirname(__file__))
resources =... | tests/test_readingorder.py |
from __future__ import absolute_import, division, print_function
import unittest
import os
from typing import Sequence, Tuple
import shapely.geometry as geom
import numpy as np
from kraken.lib.segmentation import is_in_region, reading_order, topsort
thisfile = os.path.abspath(os.path.dirname(__file__))
resources =... | 0.869244 | 0.607227 |
import base64
import io
import os
import struct
import urllib.parse
import urllib.request
import warnings
import wave
from contextlib import nullcontext
from typing import Optional, Union, BinaryIO, TYPE_CHECKING, Dict, Tuple
import numpy as np
from ... import __windows__
if TYPE_CHECKING:
from . import Document... | jina/types/document/converters.py | import base64
import io
import os
import struct
import urllib.parse
import urllib.request
import warnings
import wave
from contextlib import nullcontext
from typing import Optional, Union, BinaryIO, TYPE_CHECKING, Dict, Tuple
import numpy as np
from ... import __windows__
if TYPE_CHECKING:
from . import Document... | 0.849535 | 0.386995 |
from scipy.stats import lognorm
import numpy as np
def all_true(logical_list):
try:
logical_list[2]
return logical_list[0] and all_true(logical_list[1:])
except IndexError:
return logical_list[0] and logical_list[1]
class MarkovRenewalProcess():
""" Markov renewal process
- t... | stats.py | from scipy.stats import lognorm
import numpy as np
def all_true(logical_list):
try:
logical_list[2]
return logical_list[0] and all_true(logical_list[1:])
except IndexError:
return logical_list[0] and logical_list[1]
class MarkovRenewalProcess():
""" Markov renewal process
- t... | 0.689096 | 0.601828 |
with open('day5_1.txt') as file:
lines = file.readlines()
coord_map = {}
count = 0
max_row = float('-inf')
max_col = float('-inf')
for i in range(len(lines)):
line = [x.strip() for x in lines[i].strip().split("->")]
coord1 = line[0].split(',')
coord2 = line[1].split(',')
... | 2021/5/day5_1.py | with open('day5_1.txt') as file:
lines = file.readlines()
coord_map = {}
count = 0
max_row = float('-inf')
max_col = float('-inf')
for i in range(len(lines)):
line = [x.strip() for x in lines[i].strip().split("->")]
coord1 = line[0].split(',')
coord2 = line[1].split(',')
... | 0.074202 | 0.407274 |
from openapi_schema_to_json_schema import to_json_schema as convert
def test_properties():
schema = {
"type": 'object',
"required": ['bar'],
"properties": {
"foo": {
"type": 'string',
"example": '2017-01-01T12:34:56Z'
},
"... | tests/to_jsonschema/test_properties.py | from openapi_schema_to_json_schema import to_json_schema as convert
def test_properties():
schema = {
"type": 'object',
"required": ['bar'],
"properties": {
"foo": {
"type": 'string',
"example": '2017-01-01T12:34:56Z'
},
"... | 0.726134 | 0.581392 |
u"""cell.py
Copyright (c) 2019 <NAME>
This software is released under BSD license.
セルモジュール。
"""
import pygame as _pygame
import utils.const as _const
class Cell(_pygame.sprite.Sprite):
u"""全てのブロック・空白の基本形。
"""
_SCORE = 0
@classmethod
def get_score(cls):
u"""スコア取得。
"""
ret... | Source/pieces/cells/cell.py | u"""cell.py
Copyright (c) 2019 <NAME>
This software is released under BSD license.
セルモジュール。
"""
import pygame as _pygame
import utils.const as _const
class Cell(_pygame.sprite.Sprite):
u"""全てのブロック・空白の基本形。
"""
_SCORE = 0
@classmethod
def get_score(cls):
u"""スコア取得。
"""
ret... | 0.644784 | 0.37691 |
import opengm
import numpy
#---------------------------------------------------------------
# MinSum with SelfFusion
#---------------------------------------------------------------
numpy.random.seed(42)
#gm=opengm.loadGm("/home/tbeier/datasets/image-seg/3096.bmp.h5","gm")
#gm=opengm.loadGm("/home/tbeier/datasets/ima... | src/interfaces/python/examples/test_fancy_stuff.py | import opengm
import numpy
#---------------------------------------------------------------
# MinSum with SelfFusion
#---------------------------------------------------------------
numpy.random.seed(42)
#gm=opengm.loadGm("/home/tbeier/datasets/image-seg/3096.bmp.h5","gm")
#gm=opengm.loadGm("/home/tbeier/datasets/ima... | 0.284675 | 0.310773 |
import logging
import os
import socket
from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_service import service
from oslo_service import systemd
import pbr.version
from wsgi_basic import config
from wsgi_basic.common import environment
from wsgi_basic.server import common
from wsgi_basic... | wsgi_basic/server/eventlet.py | import logging
import os
import socket
from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_service import service
from oslo_service import systemd
import pbr.version
from wsgi_basic import config
from wsgi_basic.common import environment
from wsgi_basic.server import common
from wsgi_basic... | 0.458106 | 0.126219 |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
"metadata_version": "1.1",
"status": ["preview"],
"supported_by": "community",
}
DOCUMENTATION = """
---
module: oci_network_security_list
short_description: Manage a SecurityList resource in Orac... | plugins/modules/oci_network_security_list.py |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
"metadata_version": "1.1",
"status": ["preview"],
"supported_by": "community",
}
DOCUMENTATION = """
---
module: oci_network_security_list
short_description: Manage a SecurityList resource in Orac... | 0.889577 | 0.340184 |
from OpenGL.GL import *
from OpenGL.GLUT import *
from opengl_app import OpenGLApp
class Pyramids(OpenGLApp):
red = (1.0, 0.0, 0.0)
dark_green = (0.0, 0.4, 0.0)
light_green = (0.0, 0.4, 0.0)
green = light_green
blue = (0.0, 0.0, 1.0)
yellow = (1.0, 1.0, 0.0)
cyan = (0.0, 1.0, 1.0)
w... | python/nehe/pyramids.py |
from OpenGL.GL import *
from OpenGL.GLUT import *
from opengl_app import OpenGLApp
class Pyramids(OpenGLApp):
red = (1.0, 0.0, 0.0)
dark_green = (0.0, 0.4, 0.0)
light_green = (0.0, 0.4, 0.0)
green = light_green
blue = (0.0, 0.0, 1.0)
yellow = (1.0, 1.0, 0.0)
cyan = (0.0, 1.0, 1.0)
w... | 0.794106 | 0.214856 |
import os
from argparse import ArgumentParser
import xml.etree.ElementTree as ET
import copy
import timeit
from operator import itemgetter
from cactus.progressive.seqFile import SeqFile
from cactus.progressive.multiCactusTree import MultiCactusTree
from cactus.shared.common import setupBinaries, importSingularityImag... | src/cactus/refmap/cactus_graphmap_join.py | import os
from argparse import ArgumentParser
import xml.etree.ElementTree as ET
import copy
import timeit
from operator import itemgetter
from cactus.progressive.seqFile import SeqFile
from cactus.progressive.multiCactusTree import MultiCactusTree
from cactus.shared.common import setupBinaries, importSingularityImag... | 0.408395 | 0.083553 |
import sys
from os import path
sys.path.insert(0, '../Solutions/')
from VGuard import VGuard
from DeMONS import DeMONS
sys.path.insert(0, '../Simulators/')
from MethodsSimulator import MethodsSimulator
def help():
print('=========================== HELP =========================')
print('USAGE: python main.p... | Other/main.py | import sys
from os import path
sys.path.insert(0, '../Solutions/')
from VGuard import VGuard
from DeMONS import DeMONS
sys.path.insert(0, '../Simulators/')
from MethodsSimulator import MethodsSimulator
def help():
print('=========================== HELP =========================')
print('USAGE: python main.p... | 0.152852 | 0.102529 |
"""Version representation of evergreen."""
from __future__ import absolute_import
from evergreen.base import _BaseEvergreenObject, evg_attrib, evg_datetime_attrib
from evergreen.metrics.versionmetrics import VersionMetrics
EVG_VERSION_STATUS_SUCCESS = 'success'
EVG_VERSION_STATUS_FAILED = 'failed'
EVG_VERSION_STATUS... | src/evergreen/version.py | """Version representation of evergreen."""
from __future__ import absolute_import
from evergreen.base import _BaseEvergreenObject, evg_attrib, evg_datetime_attrib
from evergreen.metrics.versionmetrics import VersionMetrics
EVG_VERSION_STATUS_SUCCESS = 'success'
EVG_VERSION_STATUS_FAILED = 'failed'
EVG_VERSION_STATUS... | 0.911098 | 0.157299 |
import datetime
import os
import time
from typing import Callable
import gym
import numpy as np
from sacred import Experiment
from sacred.observers import FileStorageObserver, RunObserver
from active_reward_learning.common.constants import LABELS, PLOTS_PATH
from active_reward_learning.envs import (
FirstStateTra... | active_reward_learning/tabular_experiment.py | import datetime
import os
import time
from typing import Callable
import gym
import numpy as np
from sacred import Experiment
from sacred.observers import FileStorageObserver, RunObserver
from active_reward_learning.common.constants import LABELS, PLOTS_PATH
from active_reward_learning.envs import (
FirstStateTra... | 0.761006 | 0.332365 |
import sys
import time
import datetime
import os.path
import decimal
import fnmatch
import copy
import glob
from decimal import Decimal
from seiscomp import logs
from seiscomp.db.seiscomp3 import sc3wrap
from seiscomp.db.seiscomp3.routing import Routing as SC3Routing
from seiscomp.db.seiscomp3.inventory import Invento... | src/nettab/apps/tabutils/nettab2inv.py |
import sys
import time
import datetime
import os.path
import decimal
import fnmatch
import copy
import glob
from decimal import Decimal
from seiscomp import logs
from seiscomp.db.seiscomp3 import sc3wrap
from seiscomp.db.seiscomp3.routing import Routing as SC3Routing
from seiscomp.db.seiscomp3.inventory import Invento... | 0.242564 | 0.0559 |
from . import add_acquisition
from . import add_optimizer
from . import add_models
from . import add_objective
from . import mod_bayesian_optimization
import GPyOpt
class boBASE():
"""
Newly implemented class to handle settings for each Bayesian optimization method.
param f: function to optimiz... | Samples/codes/matopt_review/method.py | from . import add_acquisition
from . import add_optimizer
from . import add_models
from . import add_objective
from . import mod_bayesian_optimization
import GPyOpt
class boBASE():
"""
Newly implemented class to handle settings for each Bayesian optimization method.
param f: function to optimiz... | 0.629319 | 0.169166 |
from django.db import models
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.utils.timezone import now
from core.utils import NONUNIQUE_SLUG_FIELD_PARAMS, is_within_period, set_defaults, set_attrs
class AlternativeProgrammeForm(models.Model):
"""
Most progra... | programme/models/alternative_programme_form.py | from django.db import models
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.utils.timezone import now
from core.utils import NONUNIQUE_SLUG_FIELD_PARAMS, is_within_period, set_defaults, set_attrs
class AlternativeProgrammeForm(models.Model):
"""
Most progra... | 0.744656 | 0.298389 |
from binascii import unhexlify, hexlify
from hashlib import md5
from .exceptions import ParseException
class SentenceParser(object):
cast_map = {'yes': True, 'true': True, 'no': False, 'false': False}
@classmethod
def parse_sentence(cls, sentence, cast_int=True, cast_bool=True):
reply_word = sent... | miktapi/helper.py | from binascii import unhexlify, hexlify
from hashlib import md5
from .exceptions import ParseException
class SentenceParser(object):
cast_map = {'yes': True, 'true': True, 'no': False, 'false': False}
@classmethod
def parse_sentence(cls, sentence, cast_int=True, cast_bool=True):
reply_word = sent... | 0.601242 | 0.234774 |
import xml.etree.ElementTree as ET
import inflect as Plural
output = file("output.txt", "a+")
def create_guid_extension(entity_xml):
entity_name = entity_xml.get("name")
plural_entity_name = Plural.engine().plural(entity_name)
output.write("\n\nextension {}: GUIDMapEntity {} \n".format(entity_name, "{"))... | main.py | import xml.etree.ElementTree as ET
import inflect as Plural
output = file("output.txt", "a+")
def create_guid_extension(entity_xml):
entity_name = entity_xml.get("name")
plural_entity_name = Plural.engine().plural(entity_name)
output.write("\n\nextension {}: GUIDMapEntity {} \n".format(entity_name, "{"))... | 0.19129 | 0.089256 |
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from coinbase import Coinbase
import logging
import sys
import telepot
from mysecrets import Secrets
import pdb
# Telegram
bot = telepot.Bot(Secrets.TELEGRAM_TOKEN)
def sendMessageToTelegram(text):
b... | analyze_product.py | import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from coinbase import Coinbase
import logging
import sys
import telepot
from mysecrets import Secrets
import pdb
# Telegram
bot = telepot.Bot(Secrets.TELEGRAM_TOKEN)
def sendMessageToTelegram(text):
b... | 0.213377 | 0.198084 |
import os
import logging
import clients
import textwrap
from persist import JsonObject
from telegram.ext import Updater, MessageHandler, CommandHandler, Filters
from webpreview import web_preview
class TelegramBot(object):
def __init__(self, token, reddit):
self.chats = JsonObject('chats.json')
s... | src/clients/telegram.py | import os
import logging
import clients
import textwrap
from persist import JsonObject
from telegram.ext import Updater, MessageHandler, CommandHandler, Filters
from webpreview import web_preview
class TelegramBot(object):
def __init__(self, token, reddit):
self.chats = JsonObject('chats.json')
s... | 0.276105 | 0.058939 |
# pylint: disable=line-too-long
import logging
import json
import pytz
import yaml
import requests
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
from cmframework.apis import cmvalidator
from cmdatahandlers.api import validation
class TimeValidation(cmvalidator.C... | validators/src/TimeValidation.py |
# pylint: disable=line-too-long
import logging
import json
import pytz
import yaml
import requests
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
from cmframework.apis import cmvalidator
from cmdatahandlers.api import validation
class TimeValidation(cmvalidator.C... | 0.44553 | 0.089216 |
from common import utils
from common.constants import FUN_ARG, LOC_VAR, ENUM_ABBREV_CODE, UNKNOWN_LABEL
from common.constants import VOID, INT, TTYPES
from collections import Counter
from elements.regs import Reg
from elements.offsets import IndirectOffset
def make_variables(locs, binary):
variables = dict()
... | py/c/variables.py | from common import utils
from common.constants import FUN_ARG, LOC_VAR, ENUM_ABBREV_CODE, UNKNOWN_LABEL
from common.constants import VOID, INT, TTYPES
from collections import Counter
from elements.regs import Reg
from elements.offsets import IndirectOffset
def make_variables(locs, binary):
variables = dict()
... | 0.514888 | 0.184418 |
from PySide6.QtCore import QPoint, Qt, Signal
from PySide6.QtGui import QIntValidator
from PySide6.QtWidgets import QHBoxLayout, QLineEdit, QSizePolicy, QSlider, QToolTip, QWidget, QApplication
class QRangeL(QLineEdit):
newValue = Signal()
def __init__(self, min=0, max=100, value = 0):
super().__ini... | src/lib/QRangeWidgeds.py | from PySide6.QtCore import QPoint, Qt, Signal
from PySide6.QtGui import QIntValidator
from PySide6.QtWidgets import QHBoxLayout, QLineEdit, QSizePolicy, QSlider, QToolTip, QWidget, QApplication
class QRangeL(QLineEdit):
newValue = Signal()
def __init__(self, min=0, max=100, value = 0):
super().__ini... | 0.692642 | 0.134378 |
import os
import sys
from cram._encoding import b, bytestype, stdoutb
from cram._process import execute
__all__ = ['runcli']
def _prompt(question, answers, auto=None):
"""Write a prompt to stdout and ask for answer in stdin.
answers should be a string, with each character a single
answer. An uppercase ... | tests/scripts/cram/_cli.py |
import os
import sys
from cram._encoding import b, bytestype, stdoutb
from cram._process import execute
__all__ = ['runcli']
def _prompt(question, answers, auto=None):
"""Write a prompt to stdout and ask for answer in stdin.
answers should be a string, with each character a single
answer. An uppercase ... | 0.46563 | 0.317744 |
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import jedi
import sys
host = ('127.0.0.1', 34341)
attr_names = ["column", "name", "name_with_symbols", "type", "module_name", "module_path", "is_keyword",
"complete", "full_name", "params","line","description","desc_with_mod... | pythonFiles/codehttpserver.py | from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import jedi
import sys
host = ('127.0.0.1', 34341)
attr_names = ["column", "name", "name_with_symbols", "type", "module_name", "module_path", "is_keyword",
"complete", "full_name", "params","line","description","desc_with_mod... | 0.217254 | 0.093388 |
import matplotlib.pyplot as plt
import numpy as np
from time import time
import pandas as pd
# Underlying informations
S0 = 100
sigma = 0.1
# European option informations
T = 1.0
K = 110.0
r = 0.05
# Simulation parameters
nbr_steps = 100
dt = T/nbr_steps
t = np.linspace(0, T, nbr_steps)
min_nbr_sim... | Variance reduction/importance_sampling_method.py | import matplotlib.pyplot as plt
import numpy as np
from time import time
import pandas as pd
# Underlying informations
S0 = 100
sigma = 0.1
# European option informations
T = 1.0
K = 110.0
r = 0.05
# Simulation parameters
nbr_steps = 100
dt = T/nbr_steps
t = np.linspace(0, T, nbr_steps)
min_nbr_sim... | 0.52683 | 0.552479 |
import mock
import unittest
from coffea.model import Model, Node, NodeIdFilter, NodeIdMapper
class TestModel(unittest.TestCase):
def test_merge(self):
model = Model()
nodes = [Node('node0', ['node1'], 40),
Node('node1', ['external0']),
Node('node2', size=5),
... | coffea/tests/test_model.py |
import mock
import unittest
from coffea.model import Model, Node, NodeIdFilter, NodeIdMapper
class TestModel(unittest.TestCase):
def test_merge(self):
model = Model()
nodes = [Node('node0', ['node1'], 40),
Node('node1', ['external0']),
Node('node2', size=5),
... | 0.591605 | 0.532851 |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import sys
import os
import time
import csv
import re
import random
from datetime import datetime, date
def random_driver(loadstrat="normal",images=True,vi... | Textbooks.py | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import sys
import os
import time
import csv
import re
import random
from datetime import datetime, date
def random_driver(loadstrat="normal",images=True,vi... | 0.083792 | 0.068413 |
from o3seespy.base_model import OpenSeesObject
class TestBase(OpenSeesObject):
op_base_type = "test"
class NormUnbalance(TestBase):
"""
The NormUnbalance Test Class
Create a NormUnbalance test, which uses the norm of the right hand side of the matrix equation to determine if
convergence has... | o3seespy/command/test.py | from o3seespy.base_model import OpenSeesObject
class TestBase(OpenSeesObject):
op_base_type = "test"
class NormUnbalance(TestBase):
"""
The NormUnbalance Test Class
Create a NormUnbalance test, which uses the norm of the right hand side of the matrix equation to determine if
convergence has... | 0.896992 | 0.631395 |
import sys
import os
import unittest
import logging
import inspect
# Extend PYTHONPATH with local 'lib' folder
if __name__ == "__main__":
jasyroot = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir, os.pardir, os.pardir))
sys.path.insert(0, jasyroot)
print("Running from %s.... | jasy/test/style/root.py |
import sys
import os
import unittest
import logging
import inspect
# Extend PYTHONPATH with local 'lib' folder
if __name__ == "__main__":
jasyroot = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir, os.pardir, os.pardir))
sys.path.insert(0, jasyroot)
print("Running from %s.... | 0.303422 | 0.09739 |