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 numpy as np import math from typing import List def image2tiles(im: np.ndarray, h: int, w: int): """Transforms an image to a list of tiles Parameters ---------- im : numpy array Image h : int Height of the tiles w : int Width of the tiles Returns -----...
cv/image_processing.py
import numpy as np import math from typing import List def image2tiles(im: np.ndarray, h: int, w: int): """Transforms an image to a list of tiles Parameters ---------- im : numpy array Image h : int Height of the tiles w : int Width of the tiles Returns -----...
0.899892
0.727104
from typing import List import torch import torch.hub import torchvision as tv class AlgaeSegmentationToClassification(torch.nn.Module): def __init__(self, chip_size: int = 32): super().__init__() self.pool = torch.nn.AdaptiveAvgPool2d(output_size=1) self.conv2d = torch.nn.Conv2d(in_chann...
algae.py
from typing import List import torch import torch.hub import torchvision as tv class AlgaeSegmentationToClassification(torch.nn.Module): def __init__(self, chip_size: int = 32): super().__init__() self.pool = torch.nn.AdaptiveAvgPool2d(output_size=1) self.conv2d = torch.nn.Conv2d(in_chann...
0.931533
0.357147
import pytest import numpy as np from cobaya.yaml import yaml_load from cobaya.model import get_model import os import pdb def get_demo_xcorr_model(theory): if theory == "camb": info_yaml = r""" likelihood: soliket.XcorrLikelihood: stop_at_error: True ...
soliket/tests/test_xcorr.py
import pytest import numpy as np from cobaya.yaml import yaml_load from cobaya.model import get_model import os import pdb def get_demo_xcorr_model(theory): if theory == "camb": info_yaml = r""" likelihood: soliket.XcorrLikelihood: stop_at_error: True ...
0.660282
0.341994
import pytest from insanic import Insanic, status, __version__ from insanic.conf import settings from insanic.loading import get_service from insanic.services.registry import registry def test_view_invalid_method(): app_name = "test" app = Insanic(app_name) request, response = app.test_client.get(f"/{a...
tests/test_monitor.py
import pytest from insanic import Insanic, status, __version__ from insanic.conf import settings from insanic.loading import get_service from insanic.services.registry import registry def test_view_invalid_method(): app_name = "test" app = Insanic(app_name) request, response = app.test_client.get(f"/{a...
0.577614
0.448245
import fileinput from collections import defaultdict from typing import Callable, DefaultDict, Dict, List, Optional, TypeVar, Union import numpy as np from sspipe import p, px # type: ignore T = TypeVar("T") def main(input_path: Optional[str] = None): """ >>> main('../3.in') 852500 1007985 """ ...
2021/Python/3.py
import fileinput from collections import defaultdict from typing import Callable, DefaultDict, Dict, List, Optional, TypeVar, Union import numpy as np from sspipe import p, px # type: ignore T = TypeVar("T") def main(input_path: Optional[str] = None): """ >>> main('../3.in') 852500 1007985 """ ...
0.846117
0.563918
from __future__ import unicode_literals from django.contrib.admin.views.decorators import staff_member_required, user_passes_test from django.http import HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404, render, redirect from django.urls import reverse from django.utils.http import ur...
isiscb/curation/bulk_views/citation_views.py
from __future__ import unicode_literals from django.contrib.admin.views.decorators import staff_member_required, user_passes_test from django.http import HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404, render, redirect from django.urls import reverse from django.utils.http import ur...
0.568655
0.063251
import os import sys import tempfile import time from multiprocessing import Process import mitzasql.constants as const test_sessions_file = os.path.join(tempfile.gettempdir(), 'mitzasql-ui-test-sessions' + str(time.time()) + '.ini') def get_macro_path(name): macro_path = os.path.dirname(os.path.realpath...
tests/macros/run.py
import os import sys import tempfile import time from multiprocessing import Process import mitzasql.constants as const test_sessions_file = os.path.join(tempfile.gettempdir(), 'mitzasql-ui-test-sessions' + str(time.time()) + '.ini') def get_macro_path(name): macro_path = os.path.dirname(os.path.realpath...
0.180431
0.102305
import json import logging import traceback from threading import Thread from lcm.pub.database.models import NfInstModel from lcm.pub.exceptions import NFLCMException from lcm.pub.exceptions import NFLCMExceptionConflict from lcm.pub.msapi.gvnfmdriver import prepare_notification_data from lcm.pub.msapi.gvnfmdriver im...
lcm/lcm/nf/biz/instantiate_vnf.py
import json import logging import traceback from threading import Thread from lcm.pub.database.models import NfInstModel from lcm.pub.exceptions import NFLCMException from lcm.pub.exceptions import NFLCMExceptionConflict from lcm.pub.msapi.gvnfmdriver import prepare_notification_data from lcm.pub.msapi.gvnfmdriver im...
0.322633
0.054525
from mahjong.hand_calculating.hand import HandCalculator from mahjong.meld import Meld from mahjong.hand_calculating.hand_config import HandConfig, OptionalRules from mahjong.tile import TilesConverter as tc from mahjong.utils import is_chi, is_pon, is_honor from enum import IntEnum MAX_TILE_NUM = 4 * 4 + 2 MIN_TILE_N...
server/tile_score.py
from mahjong.hand_calculating.hand import HandCalculator from mahjong.meld import Meld from mahjong.hand_calculating.hand_config import HandConfig, OptionalRules from mahjong.tile import TilesConverter as tc from mahjong.utils import is_chi, is_pon, is_honor from enum import IntEnum MAX_TILE_NUM = 4 * 4 + 2 MIN_TILE_N...
0.642545
0.322433
import os import sys import dj_database_url from decouple import Csv, config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) ROOT = os.path.dirname(os.path.join(BASE_DIR, '..')) # Quick-start development settings - unsuitable for producti...
{{ cookiecutter.project_name }}/{{ cookiecutter.project_name }}/settings.py
import os import sys import dj_database_url from decouple import Csv, config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) ROOT = os.path.dirname(os.path.join(BASE_DIR, '..')) # Quick-start development settings - unsuitable for producti...
0.403332
0.054299
import sys import os import configparser import argparse # Проверяет, что путь соответствует фильтрам def is_ignored(filename): for ignore_dir in ignore_dirs: if filename.startswith(ignore_dir): return True _, cur_ext = os.path.splitext(filename) return cur_ext not in extensions ...
deponizator.py
import sys import os import configparser import argparse # Проверяет, что путь соответствует фильтрам def is_ignored(filename): for ignore_dir in ignore_dirs: if filename.startswith(ignore_dir): return True _, cur_ext = os.path.splitext(filename) return cur_ext not in extensions ...
0.121738
0.150091
from flask import Flask, render_template, request, jsonify import os import requests import json import datetime import time import glob import json app = Flask(__name__) UPLOAD_PATH = 'static/uploads' APP_ROOT = os.path.dirname(os.path.abspath(__file__)) UPLOAD_FOLDER = os.path.join(APP_ROOT, UPLOAD_PATH) TEMP_FOLDER...
flask-dropzonejs_copy.py
from flask import Flask, render_template, request, jsonify import os import requests import json import datetime import time import glob import json app = Flask(__name__) UPLOAD_PATH = 'static/uploads' APP_ROOT = os.path.dirname(os.path.abspath(__file__)) UPLOAD_FOLDER = os.path.join(APP_ROOT, UPLOAD_PATH) TEMP_FOLDER...
0.152852
0.057098
import os import string import random import shutil import numpy import dask.array as dsarray import pyarrow import zarr import cbox.lib.boost as cbox class Data(cbox.create.Data): """Default class to store data""" type_ = "default" def __init__(self, **attributes): """Initialize the class obj...
bubblebox/library/create/_data.py
import os import string import random import shutil import numpy import dask.array as dsarray import pyarrow import zarr import cbox.lib.boost as cbox class Data(cbox.create.Data): """Default class to store data""" type_ = "default" def __init__(self, **attributes): """Initialize the class obj...
0.559049
0.278305
import glob import logging import os import optparse import sys # logging config logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s [%(filename)s:%(funcName)s]') from lxml import etree as et from ioc_writer import ioc_api, xmlutils class IOCParseError(Exception): pass cl...
examples/10_to_11_upgrade/openioc_10_to_11.py
import glob import logging import os import optparse import sys # logging config logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s [%(filename)s:%(funcName)s]') from lxml import etree as et from ioc_writer import ioc_api, xmlutils class IOCParseError(Exception): pass cl...
0.199581
0.099252
from django.test import TestCase from authorization.views import LoginView, LoginRefreshView, RegisterView class TestRegisterView(TestCase): def setUp(self): self.view = RegisterView() def test_queryset_belongs_to_user_model(self): self.assertEqual("User", self.view.queryset.model.__name__) ...
app/authorization/tests/unit/views_tests.py
from django.test import TestCase from authorization.views import LoginView, LoginRefreshView, RegisterView class TestRegisterView(TestCase): def setUp(self): self.view = RegisterView() def test_queryset_belongs_to_user_model(self): self.assertEqual("User", self.view.queryset.model.__name__) ...
0.570212
0.278833
# pylint: disable=W0223 """DCASGD optimizer.""" from __future__ import absolute_import from ..ndarray import (zeros, clip, square) from .optimizer import Optimizer, register __all__ = ['DCASGD'] @register class DCASGD(Optimizer): """The DCASGD optimizer. This class implements the optimizer described in *As...
python/mxnet/optimizer/dcasgd.py
# pylint: disable=W0223 """DCASGD optimizer.""" from __future__ import absolute_import from ..ndarray import (zeros, clip, square) from .optimizer import Optimizer, register __all__ = ['DCASGD'] @register class DCASGD(Optimizer): """The DCASGD optimizer. This class implements the optimizer described in *As...
0.949318
0.414306
import os import sys def initialize_dynamic_lines(): return [ '---\n', 'layout: default\n', '---\n' ] def initialize_static_lines(): return [ '# A lightweight range slider with expandable timeline\n\n', 'See this project at [artoonie.github.io/timeline-range-slider...
docs/generate-readme.py
import os import sys def initialize_dynamic_lines(): return [ '---\n', 'layout: default\n', '---\n' ] def initialize_static_lines(): return [ '# A lightweight range slider with expandable timeline\n\n', 'See this project at [artoonie.github.io/timeline-range-slider...
0.432543
0.417628
import heapq import math import sys from typing import List, Tuple def convert_input(data: List[str]) -> List[List[int]]: return [list(map(int, line)) for line in data if line] def get_neighbours(x, y: int, limit: int) -> List[Tuple[int, int]]: return [ (i, j) for i, j in [(x + 1, y), (x - 1...
2021/day_15/chiton.py
import heapq import math import sys from typing import List, Tuple def convert_input(data: List[str]) -> List[List[int]]: return [list(map(int, line)) for line in data if line] def get_neighbours(x, y: int, limit: int) -> List[Tuple[int, int]]: return [ (i, j) for i, j in [(x + 1, y), (x - 1...
0.383064
0.506713
import torch import torch.nn as nn class VGG(nn.Module): def __init__(self, features, num_classes=1000, init_weight=True): super(VGG, self).__init__() self.features = features self.avgpool = nn.AdaptiveAvgPool2d((7, 7)) self.classifier = nn.Sequential( nn.Linear(512 * 7 ...
Classification/vgg.py
import torch import torch.nn as nn class VGG(nn.Module): def __init__(self, features, num_classes=1000, init_weight=True): super(VGG, self).__init__() self.features = features self.avgpool = nn.AdaptiveAvgPool2d((7, 7)) self.classifier = nn.Sequential( nn.Linear(512 * 7 ...
0.928433
0.425187
import scrapy import regex from bs4 import BeautifulSoup import urllib import pandas class QuotesSpider(scrapy.Spider): name = "CO_Spider" Search_Url = r"http://www.coloradoshines.com/search?location={0}" Main_Url = r"http://www.coloradoshines.com/search" Detail_Url = r"http://www.coloradoshines.com/p...
First_Spider/spiders/CO_Spider.py
import scrapy import regex from bs4 import BeautifulSoup import urllib import pandas class QuotesSpider(scrapy.Spider): name = "CO_Spider" Search_Url = r"http://www.coloradoshines.com/search?location={0}" Main_Url = r"http://www.coloradoshines.com/search" Detail_Url = r"http://www.coloradoshines.com/p...
0.204183
0.125413
from allure import title, description, suite, parent_suite from data import AUTH_DATA_FAIL_BAD_TOKEN, API_USERS_SUCCESS, API_PUT_METHOD_NOT_ALLOWED, API_AUTH_TOKEN_EMPTY, \ API_BAD_REQUEST_LENGTH_TOKEN, AUTH_DATA_LENGTH_TOKEN, API_BAD_REQUEST_EMPTY_OBJECTS, \ API_BAD_REQUEST_LENGTH_MATERIALS_100_CHARACTERS, AP...
tests/api/test_objects_update.py
from allure import title, description, suite, parent_suite from data import AUTH_DATA_FAIL_BAD_TOKEN, API_USERS_SUCCESS, API_PUT_METHOD_NOT_ALLOWED, API_AUTH_TOKEN_EMPTY, \ API_BAD_REQUEST_LENGTH_TOKEN, AUTH_DATA_LENGTH_TOKEN, API_BAD_REQUEST_EMPTY_OBJECTS, \ API_BAD_REQUEST_LENGTH_MATERIALS_100_CHARACTERS, AP...
0.417509
0.256969
import os import random import unittest from common import format class FormatTestCase(unittest.TestCase): def test_rendering_text(self): text = u"toto{%toto%}tata{%toto%}:{%titi%}" self.assertEqual(u"totoatataa:b", format.render_text(text, toto...
common/format_test.py
import os import random import unittest from common import format class FormatTestCase(unittest.TestCase): def test_rendering_text(self): text = u"toto{%toto%}tata{%toto%}:{%titi%}" self.assertEqual(u"totoatataa:b", format.render_text(text, toto...
0.441432
0.479382
from sklearn.feature_extraction.text import TfidfVectorizer import pandas as pd import numpy as np import liwc from collections import Counter import textstat import string from nltk.corpus import stopwords from settings.scraper import TARGET_LANGS import stanza nlp = stanza.Pipeline('en', use_gpu=False) # stanza.down...
tools/features_extraction.py
from sklearn.feature_extraction.text import TfidfVectorizer import pandas as pd import numpy as np import liwc from collections import Counter import textstat import string from nltk.corpus import stopwords from settings.scraper import TARGET_LANGS import stanza nlp = stanza.Pipeline('en', use_gpu=False) # stanza.down...
0.435421
0.296699
import collections import unittest from unittest.mock import call, patch, MagicMock from .. import mc_default_task_handler class BaseTestCase(unittest.TestCase): def setUp(self): super().setUp() self.task = collections.defaultdict(MagicMock) self.task_ctx = collections.defaultdict(MagicMo...
mc/task_handlers/tests/test_mc_default_task_handler.py
import collections import unittest from unittest.mock import call, patch, MagicMock from .. import mc_default_task_handler class BaseTestCase(unittest.TestCase): def setUp(self): super().setUp() self.task = collections.defaultdict(MagicMock) self.task_ctx = collections.defaultdict(MagicMo...
0.565179
0.292078
import json import imageio from tqdm.auto import tqdm import time from PIL import Image, ImageFont, ImageDraw import re import random from matplotlib import pyplot as plt import os import string from IPython.display import FileLink, HTML, display def random_string_id(L=6): """Random ID.""" char_set = string.as...
causal_analysis/plot_gif_model.py
import json import imageio from tqdm.auto import tqdm import time from PIL import Image, ImageFont, ImageDraw import re import random from matplotlib import pyplot as plt import os import string from IPython.display import FileLink, HTML, display def random_string_id(L=6): """Random ID.""" char_set = string.as...
0.557725
0.16248
from __future__ import division import unittest import numpy as np import pandas as pd from nimbusml import DataSchema, FileDataStream, Pipeline, Role from nimbusml.datasets import get_dataset from nimbusml.ensemble import LightGbmRegressor, VotingRegressor from nimbusml.feature_extraction.categorical import OneHotVe...
src/python/nimbusml/tests/ensemble/test_votingregressor.py
from __future__ import division import unittest import numpy as np import pandas as pd from nimbusml import DataSchema, FileDataStream, Pipeline, Role from nimbusml.datasets import get_dataset from nimbusml.ensemble import LightGbmRegressor, VotingRegressor from nimbusml.feature_extraction.categorical import OneHotVe...
0.716119
0.538741
import sys import pandas as pd from sqlalchemy import create_engine import sqlite3 def load_data(messages_filepath, categories_filepath): """ Load messages and categories datasets Merge these datasets into a dataframe Args: messages_filepath : filepath of messages.read_csv categories_fi...
data/process_data.py
import sys import pandas as pd from sqlalchemy import create_engine import sqlite3 def load_data(messages_filepath, categories_filepath): """ Load messages and categories datasets Merge these datasets into a dataframe Args: messages_filepath : filepath of messages.read_csv categories_fi...
0.580352
0.511412
from warnings import warn from logging import getLogger from re import sub lg = getLogger(__name__) def find_root(filename, target='bids'): """Find base directory (root) for a filename. Parameters ---------- filename : instance of Path search the root for this file target: str 'b...
bidso/find.py
from warnings import warn from logging import getLogger from re import sub lg = getLogger(__name__) def find_root(filename, target='bids'): """Find base directory (root) for a filename. Parameters ---------- filename : instance of Path search the root for this file target: str 'b...
0.700895
0.208119
from typing import Any, Optional, TYPE_CHECKING from azure.core import AsyncPipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential from ._configuration import EntitySearchCli...
sdk/EntitySearch/entity_search_client/aio/_entity_search_client.py
from typing import Any, Optional, TYPE_CHECKING from azure.core import AsyncPipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential from ._configuration import EntitySearchCli...
0.806205
0.115586
import json import time import sqlite3 as lite import os def save_json_file(BASE_DIR): # Serialize data into file: global save_dict file_path = "\\".join([BASE_DIR,'data','save_options.json']) json.dump( save_dict, open(file_path, 'w' ) ) def load_json_file(BASE_DIR): # Read ...
extraPacks/Utils.py
import json import time import sqlite3 as lite import os def save_json_file(BASE_DIR): # Serialize data into file: global save_dict file_path = "\\".join([BASE_DIR,'data','save_options.json']) json.dump( save_dict, open(file_path, 'w' ) ) def load_json_file(BASE_DIR): # Read ...
0.047791
0.048406
import importlib from typing import Dict, Sequence, Iterator import torch import tvl.backend from tvl.backend import BackendFactory # Explicitly set backends for particular device types. _device_backends: Dict[str, BackendFactory] = {} # Known backends. These will be searched if a device type does not have a backend...
src/tvl/__init__.py
import importlib from typing import Dict, Sequence, Iterator import torch import tvl.backend from tvl.backend import BackendFactory # Explicitly set backends for particular device types. _device_backends: Dict[str, BackendFactory] = {} # Known backends. These will be searched if a device type does not have a backend...
0.887375
0.101012
import logging from mimetypes import guess_extension, guess_type import re from spycis.compat import * from spycis.utils import session, urlparse, RequestException from .common import BaseExtractor class GorillaVidExtractor(BaseExtractor): """ gorillavid extractor """ def __init__(self): super(...
spycis/extractors/gorillavid.py
import logging from mimetypes import guess_extension, guess_type import re from spycis.compat import * from spycis.utils import session, urlparse, RequestException from .common import BaseExtractor class GorillaVidExtractor(BaseExtractor): """ gorillavid extractor """ def __init__(self): super(...
0.35209
0.137099
import pytest import Dragon_Tokens from Cas_Format import CasFormat, LEADER, SYNC, NAME_FILE_BLOCK, BASIC_FILE_IDENTIFIER, ASCII_FILE_FLAG, \ CONTINUOUS_FILE, DATA_BLOCK, END_OF_FILE_BLOCK, DATA_FILE_IDENTIFIER def test_given_a_valid_byte_array_returns_a_formatted_string(): stream = [LEADER, SYNC, NAME_FILE_...
test_Cas_Format.py
import pytest import Dragon_Tokens from Cas_Format import CasFormat, LEADER, SYNC, NAME_FILE_BLOCK, BASIC_FILE_IDENTIFIER, ASCII_FILE_FLAG, \ CONTINUOUS_FILE, DATA_BLOCK, END_OF_FILE_BLOCK, DATA_FILE_IDENTIFIER def test_given_a_valid_byte_array_returns_a_formatted_string(): stream = [LEADER, SYNC, NAME_FILE_...
0.446495
0.364085
from __future__ import print_function, division, absolute_import __author__ = "<NAME>" __license__ = "MIT" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" from functools import partial from collections import OrderedDict from Qt.QtCore import Qt, Signal, QObject from Qt.QtWidgets import QMenu from tpDcc.managers im...
tpRigToolkit/tools/jointorient/widgets/rotationaxis.py
from __future__ import print_function, division, absolute_import __author__ = "<NAME>" __license__ = "MIT" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" from functools import partial from collections import OrderedDict from Qt.QtCore import Qt, Signal, QObject from Qt.QtWidgets import QMenu from tpDcc.managers im...
0.520253
0.090293
import io import mmh3 # type:ignore import struct from operator import itemgetter from typing import Iterable from functools import lru_cache MAX_INDEX = 4294967295 # 2^32 - 1 STRUCT_DEF = "I I I" # 4 byte unsigned int, 4 byte unsigned int, 4 byte unsigned int RECORD_SIZE = struct.calcsize(STRUCT_DEF) # this shou...
mabel/index/index.py
import io import mmh3 # type:ignore import struct from operator import itemgetter from typing import Iterable from functools import lru_cache MAX_INDEX = 4294967295 # 2^32 - 1 STRUCT_DEF = "I I I" # 4 byte unsigned int, 4 byte unsigned int, 4 byte unsigned int RECORD_SIZE = struct.calcsize(STRUCT_DEF) # this shou...
0.838283
0.54353
import numpy as np from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_true from ActiveModel.quantile import RandomForestQu...
generator_labeler/ActiveModel/quantile/tests/test_ensemble.py
import numpy as np from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_true from ActiveModel.quantile import RandomForestQu...
0.866951
0.835517
import wx # Define events for communication by threads EVT_PROGRESS_ID = wx.NewIdRef() def EVT_PROGRESS(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_PROGRESS_ID, func) class ProgressEvent(wx.PyEvent): """Simple event to carry arbitrary progress data.""" def __init__(self, data): ...
src/Common/CustomEvents.py
import wx # Define events for communication by threads EVT_PROGRESS_ID = wx.NewIdRef() def EVT_PROGRESS(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_PROGRESS_ID, func) class ProgressEvent(wx.PyEvent): """Simple event to carry arbitrary progress data.""" def __init__(self, data): ...
0.718199
0.230616
import ctypes from contextlib import contextmanager import errno import logging import os import platform import pwd import grp import subprocess from .exceptions import CommandFailed _logger = logging.getLogger(__name__) def get_current_user_shell(): return pwd.getpwuid(os.getuid()).pw_shell def execute_command...
dwight_chroot/platform_utils.py
import ctypes from contextlib import contextmanager import errno import logging import os import platform import pwd import grp import subprocess from .exceptions import CommandFailed _logger = logging.getLogger(__name__) def get_current_user_shell(): return pwd.getpwuid(os.getuid()).pw_shell def execute_command...
0.146606
0.075346
from skeleton_tools.openpose_layouts.graph_layout import GraphLayout BODY_25_LAYOUT = GraphLayout( 'BODY_25', 1, { 0: "Nose", 1: "Neck", 2: "RShoulder", 3: "RElbow", 4: "RWrist", 5: "LShoulder", 6: "LElbow", 7: "LWrist", 8: "MidHip", ...
src/skeleton_tools/openpose_layouts/body.py
from skeleton_tools.openpose_layouts.graph_layout import GraphLayout BODY_25_LAYOUT = GraphLayout( 'BODY_25', 1, { 0: "Nose", 1: "Neck", 2: "RShoulder", 3: "RElbow", 4: "RWrist", 5: "LShoulder", 6: "LElbow", 7: "LWrist", 8: "MidHip", ...
0.498291
0.285976
import nixio import numpy as np import matplotlib.pyplot as plt def create_data(interval=0.001): time = np.arange(0., 1.0, interval) freq = 5. signal = np.sin(time * 2 * np.pi * freq) + np.sin(time * 2 * np.pi * 2 * freq) * 0.4 events = time[(signal > 0.5) & (np.roll(signal, -1) <= 0.5)] return si...
docs/source/examples/multiple_points.py
import nixio import numpy as np import matplotlib.pyplot as plt def create_data(interval=0.001): time = np.arange(0., 1.0, interval) freq = 5. signal = np.sin(time * 2 * np.pi * freq) + np.sin(time * 2 * np.pi * 2 * freq) * 0.4 events = time[(signal > 0.5) & (np.roll(signal, -1) <= 0.5)] return si...
0.54698
0.652975
from .auth import Auth from . import config as Config from .lib.Gen.ttypes import * from typing import Union, Any, List from .connections import Connection from random import randint import asyncio, json class Talk(Connection): _unsendMessageReq = 0 def __init__(self, auth): super().__init__("/S4") self.auth =...
AsyncLine/talk.py
from .auth import Auth from . import config as Config from .lib.Gen.ttypes import * from typing import Union, Any, List from .connections import Connection from random import randint import asyncio, json class Talk(Connection): _unsendMessageReq = 0 def __init__(self, auth): super().__init__("/S4") self.auth =...
0.657758
0.17259
from nose.plugins.attrib import attr from ion_functions.test.base_test import BaseUnitTestCase import numpy as np from ion_functions.data import ph_functions as ph @attr('UNIT', group='func') class TestpHFunctionsUnit(BaseUnitTestCase): def setUp(self): """ Test values for the PHWATER unit tests,...
ion_functions/data/test/test_ph_functions.py
from nose.plugins.attrib import attr from ion_functions.test.base_test import BaseUnitTestCase import numpy as np from ion_functions.data import ph_functions as ph @attr('UNIT', group='func') class TestpHFunctionsUnit(BaseUnitTestCase): def setUp(self): """ Test values for the PHWATER unit tests,...
0.592077
0.449332
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from base64 import b64decode from collections import OrderedDict import json from kube_obj import KubeObj from kube_types import * from kube_vartypes import Base64, JSO...
lib/kube_objs/secret.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from base64 import b64decode from collections import OrderedDict import json from kube_obj import KubeObj from kube_types import * from kube_vartypes import Base64, JSO...
0.599368
0.102979
import os import re from enum import Enum from urllib.parse import urlparse import colorama from tldextract import tldextract class YDLHelper(object): """"""""""""""" Initializer """"""""""""""" def __init__(self): self.__preprocess_queue_index = 0 self.__preprocess_queue_total = 0 ...
core/youtube_dl.py
import os import re from enum import Enum from urllib.parse import urlparse import colorama from tldextract import tldextract class YDLHelper(object): """"""""""""""" Initializer """"""""""""""" def __init__(self): self.__preprocess_queue_index = 0 self.__preprocess_queue_total = 0 ...
0.661376
0.132599
import PIL import random import unittest import numpy as np import chainer from chainer import testing from chainercv.transforms import flip from chainercv.transforms import rotate try: import cv2 # NOQA _cv2_available = True except ImportError: _cv2_available = False @testing.parameterize(*testing.pr...
tests/transforms_tests/image_tests/test_rotate.py
import PIL import random import unittest import numpy as np import chainer from chainer import testing from chainercv.transforms import flip from chainercv.transforms import rotate try: import cv2 # NOQA _cv2_available = True except ImportError: _cv2_available = False @testing.parameterize(*testing.pr...
0.601008
0.493287
from tensorflow.keras import regularizers from tensorflow.keras.models import Sequential from tensorflow.keras.models import load_model from tensorflow.keras.layers import Dense, Activation, Dropout, Flatten, LSTM, RNN, Bidirectional, Flatten, Activation, \ RepeatVector, Permute, Multiply, Lambda, Concatenate, Batc...
mlearning/dl_models.py
from tensorflow.keras import regularizers from tensorflow.keras.models import Sequential from tensorflow.keras.models import load_model from tensorflow.keras.layers import Dense, Activation, Dropout, Flatten, LSTM, RNN, Bidirectional, Flatten, Activation, \ RepeatVector, Permute, Multiply, Lambda, Concatenate, Batc...
0.856722
0.489931
import numpy as np from util import Saver class PI2(Saver): saved_names = ('theta',) def __init__(self, dmps, n_updates, n_reps, n_dims, n_bfs, n_times, r_gain, r_normalize): self.dmps = dmps self.n_updates = n_updates self.n_reps = n_reps self.n_dims = n_dims...
agents/pi2.py
import numpy as np from util import Saver class PI2(Saver): saved_names = ('theta',) def __init__(self, dmps, n_updates, n_reps, n_dims, n_bfs, n_times, r_gain, r_normalize): self.dmps = dmps self.n_updates = n_updates self.n_reps = n_reps self.n_dims = n_dims...
0.350977
0.347745
from t import T import requests,urllib2,json,urlparse class P(T): def __init__(self): T.__init__(self) def verify(self,head='',context='',ip='',port='',productname={},keywords='',hackinfo=''): target_url = "http://"+ip+":"+str(port)+"/plugins/weathermap/editor.php" result = {} r...
component/cacti/cactiweathermap.py
from t import T import requests,urllib2,json,urlparse class P(T): def __init__(self): T.__init__(self) def verify(self,head='',context='',ip='',port='',productname={},keywords='',hackinfo=''): target_url = "http://"+ip+":"+str(port)+"/plugins/weathermap/editor.php" result = {} r...
0.105567
0.063279
import matplotlib.pyplot as plt import os BASE_PATH = os.path.join(os.path.dirname(__file__), "Object-Detection-Metrics") results_name = [] results_paths = [] colours = [] """ results_name.append("yolov5l_dsv1") results_paths.append(os.path.join(BASE_PATH, "results_yolov5l_dsv1", "results.txt")) colours.append('-b') ...
evaluation/plot_results.py
import matplotlib.pyplot as plt import os BASE_PATH = os.path.join(os.path.dirname(__file__), "Object-Detection-Metrics") results_name = [] results_paths = [] colours = [] """ results_name.append("yolov5l_dsv1") results_paths.append(os.path.join(BASE_PATH, "results_yolov5l_dsv1", "results.txt")) colours.append('-b') ...
0.252937
0.192027
from __future__ import unicode_literals import re import xml.etree.ElementTree as ET def _equals(search_str, attr_str): """Equals-operator which is used to find a view""" return search_str == attr_str def _contains(search_str, attr_str): """Contains-operator which is used to find a view""" return se...
phoneauto/scriptgenerator/view_hierarchy_dump.py
from __future__ import unicode_literals import re import xml.etree.ElementTree as ET def _equals(search_str, attr_str): """Equals-operator which is used to find a view""" return search_str == attr_str def _contains(search_str, attr_str): """Contains-operator which is used to find a view""" return se...
0.890806
0.171408
import argparse import functools import json import multiprocessing from typing import Optional, Union import musdb import museval import torch import tqdm import random from xumx_slicq import utils def separate_and_evaluate( track: musdb.MultiTrack, model_str_or_path: str, niter: int, output_dir: s...
xumx_slicq/evaluate.py
import argparse import functools import json import multiprocessing from typing import Optional, Union import musdb import museval import torch import tqdm import random from xumx_slicq import utils def separate_and_evaluate( track: musdb.MultiTrack, model_str_or_path: str, niter: int, output_dir: s...
0.868074
0.167253
import itertools import json import os import numpy as np from .roberta import Tokenizer as Roberta from ...tokens.utils import ( AddedToken, BatchEncoding, PaddingStrategy, TruncationStrategy, _is_tensorflow, _is_torch, to_py_obj, ) from ...tokens.utils import is_tf_available, is_torch_a...
qnarre/prep/tokens/luke.py
import itertools import json import os import numpy as np from .roberta import Tokenizer as Roberta from ...tokens.utils import ( AddedToken, BatchEncoding, PaddingStrategy, TruncationStrategy, _is_tensorflow, _is_torch, to_py_obj, ) from ...tokens.utils import is_tf_available, is_torch_a...
0.464416
0.164718
from mpl_toolkits.mplot3d import Axes3D from matplotlib import animation, pyplot as plt import h5py import argparse import numpy as np class AnimatedGif: def __init__(self, zlim, size=(800, 800)): self.fig = plt.figure() self.fig.set_size_inches(size[0] / 100, size[1] / 100) self.ax = sel...
module4/ShallowWater/visual.py
from mpl_toolkits.mplot3d import Axes3D from matplotlib import animation, pyplot as plt import h5py import argparse import numpy as np class AnimatedGif: def __init__(self, zlim, size=(800, 800)): self.fig = plt.figure() self.fig.set_size_inches(size[0] / 100, size[1] / 100) self.ax = sel...
0.465145
0.432782
from ooo.oenv.env_const import UNO_NONE import typing from ...mozilla.mozilla_product_type import MozillaProductType as MozillaProductType_2e210f5b class NSSProfile(object): """ Struct Class **since** LibreOffice 7.1 See Also: `API NSSProfile <https://api.libreoffice.org/do...
ooobuild/lo/xml/crypto/nss_profile.py
from ooo.oenv.env_const import UNO_NONE import typing from ...mozilla.mozilla_product_type import MozillaProductType as MozillaProductType_2e210f5b class NSSProfile(object): """ Struct Class **since** LibreOffice 7.1 See Also: `API NSSProfile <https://api.libreoffice.org/do...
0.677047
0.22673
import pandas as pd import logging import time from goose3 import Goose from selenium import webdriver import threading import concurrent.futures from typing import Dict from tweetfinder import Article logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(levelname)s | %(name)s | %(message)s') l...
evaluate-from-csv.py
import pandas as pd import logging import time from goose3 import Goose from selenium import webdriver import threading import concurrent.futures from typing import Dict from tweetfinder import Article logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(levelname)s | %(name)s | %(message)s') l...
0.525369
0.070528
import sys import png def buf_emu(not_buffer): """Buffer emulation, mostly for `array` object""" if hasattr(not_buffer, 'tostring'): return not_buffer.tostring() else: try: return bytes(not_buffer) except NameError: return str(not_buffer) try: buffer e...
extools/pngrepack.py
import sys import png def buf_emu(not_buffer): """Buffer emulation, mostly for `array` object""" if hasattr(not_buffer, 'tostring'): return not_buffer.tostring() else: try: return bytes(not_buffer) except NameError: return str(not_buffer) try: buffer e...
0.287768
0.187133
from collections import deque import numpy as np import argparse import imutils import math import cv2 import rospy import os from sensor_msgs.msg import Image # define the lower and upper boundaries of the "green" # ball in the HSV color space, then initialize the # list of tracked points greenLower = (29, 86, 6) gre...
scripts/scale.py
from collections import deque import numpy as np import argparse import imutils import math import cv2 import rospy import os from sensor_msgs.msg import Image # define the lower and upper boundaries of the "green" # ball in the HSV color space, then initialize the # list of tracked points greenLower = (29, 86, 6) gre...
0.311741
0.279584
import re import json import logging from abc import ABC, abstractmethod from enum import auto, Enum from wallabag.config import Options, Sections import requests from packaging import version MINIMUM_API_VERSION = "2.1.1" class ApiException(Exception): error_text = None error_description = None def...
src/wallabag/api/api.py
import re import json import logging from abc import ABC, abstractmethod from enum import auto, Enum from wallabag.config import Options, Sections import requests from packaging import version MINIMUM_API_VERSION = "2.1.1" class ApiException(Exception): error_text = None error_description = None def...
0.459804
0.064271
from sym_lis3 import GlobalEnv import pytest @pytest.mark.parametrize("noneref", [ ("None", None), ]) def test_none(noneref): g = GlobalEnv() assert g.eval_str(noneref[0]) is noneref[1] @pytest.mark.parametrize("test_input,expected", [ ("(+ 1 2)", 3), ("(+ (+ 11 28) 2)", 41), ("(+ (+ 11 28) (...
tests/test_passed.py
from sym_lis3 import GlobalEnv import pytest @pytest.mark.parametrize("noneref", [ ("None", None), ]) def test_none(noneref): g = GlobalEnv() assert g.eval_str(noneref[0]) is noneref[1] @pytest.mark.parametrize("test_input,expected", [ ("(+ 1 2)", 3), ("(+ (+ 11 28) 2)", 41), ("(+ (+ 11 28) (...
0.553505
0.654343
import numpy as np class FourMomentum: def __init__(self, vec, basis='x,y,z,m'): self.set_basis(vec,basis) def set_basis(self, vec, basis='x,y,z,m'): """ @brief Set the four-momentum where vec is a four vector in the basis defined by the string basis, e.g 'xyzm' corresponds to ...
ostrawling/event/four_momentum.py
import numpy as np class FourMomentum: def __init__(self, vec, basis='x,y,z,m'): self.set_basis(vec,basis) def set_basis(self, vec, basis='x,y,z,m'): """ @brief Set the four-momentum where vec is a four vector in the basis defined by the string basis, e.g 'xyzm' corresponds to ...
0.853882
0.517449
from secrets import choice from decimal import Decimal from django.core.management.base import BaseCommand from django.contrib.auth import get_user_model from django.db import transaction from django.conf import settings from website.utils import get_log_url_for_user from website.models import UserProfile from websit...
annotater/memetext/management/commands/setup_demo.py
from secrets import choice from decimal import Decimal from django.core.management.base import BaseCommand from django.contrib.auth import get_user_model from django.db import transaction from django.conf import settings from website.utils import get_log_url_for_user from website.models import UserProfile from websit...
0.402862
0.107766
# Friday Command_Executing # Some parts are inspired by: https://github.com/aazuspan/Voithos/blob/master/backend/src/Voithos/CommandHandler.py import importlib import pkgutil import os from .scripts.Function_Module import Function_Module class command_executing: defaultReturnUnable = "Sorry Sir, I ...
FRIDAY/command_executing/command_executing.py
# Friday Command_Executing # Some parts are inspired by: https://github.com/aazuspan/Voithos/blob/master/backend/src/Voithos/CommandHandler.py import importlib import pkgutil import os from .scripts.Function_Module import Function_Module class command_executing: defaultReturnUnable = "Sorry Sir, I ...
0.561816
0.146881
import preprocessing.config as cfg import uuid import argparse import gc import os from preprocessing import select_gpu # choose GPU through import from keras.callbacks import EarlyStopping, ReduceLROnPlateau from preprocessing.data import LightDataManager import preprocessing.file_utils as futils from preprocessing...
pmsm/hp_tune_rnn.py
import preprocessing.config as cfg import uuid import argparse import gc import os from preprocessing import select_gpu # choose GPU through import from keras.callbacks import EarlyStopping, ReduceLROnPlateau from preprocessing.data import LightDataManager import preprocessing.file_utils as futils from preprocessing...
0.482185
0.102709
from setuptools import setup, find_packages def get_version(): """ Get version number from the seirmo module. The easiest way would be to just ``import seirmo ``, but note that this may # noqa fail if the dependencies have not been installed yet. Instead, we've put the version number in a simple ...
setup.py
from setuptools import setup, find_packages def get_version(): """ Get version number from the seirmo module. The easiest way would be to just ``import seirmo ``, but note that this may # noqa fail if the dependencies have not been installed yet. Instead, we've put the version number in a simple ...
0.357231
0.219735
import logging import torch import torch.nn as nn import yaml from .args import Args from .stats import Stats logger = logging.getLogger(__name__) def load_checkpoint(args: Args) -> dict: info_file = args.work_path.joinpath("info.yaml") checkpoint_file = args.work_path.joinpath("checkpoint.yaml") # Lo...
src/pagnn/training/dcn_old/utils.py
import logging import torch import torch.nn as nn import yaml from .args import Args from .stats import Stats logger = logging.getLogger(__name__) def load_checkpoint(args: Args) -> dict: info_file = args.work_path.joinpath("info.yaml") checkpoint_file = args.work_path.joinpath("checkpoint.yaml") # Lo...
0.839208
0.251269
from mutable import mutates, scope from unittest import TestCase, main class MutableTest(TestCase): def setUp(self): @mutates def fib(n): return n if n<2 else fib(n-1)+fib(n-2) self.fib = fib def tearDown(self): del self.fib def test_update(self): fib...
tests/test_basic.py
from mutable import mutates, scope from unittest import TestCase, main class MutableTest(TestCase): def setUp(self): @mutates def fib(n): return n if n<2 else fib(n-1)+fib(n-2) self.fib = fib def tearDown(self): del self.fib def test_update(self): fib...
0.664976
0.714516
from __future__ import absolute_import import logging from contextlib import contextmanager from PySide import QtGui from PySide.QtCore import Qt from mcedit2.command import SimpleRevisionCommand from mcedit2.ui.panels.worldinfo import Ui_worldInfoWidget from mcedit2.util.resources import resourcePath from mcedit2.ut...
src/mcedit2/panels/worldinfo.py
from __future__ import absolute_import import logging from contextlib import contextmanager from PySide import QtGui from PySide.QtCore import Qt from mcedit2.command import SimpleRevisionCommand from mcedit2.ui.panels.worldinfo import Ui_worldInfoWidget from mcedit2.util.resources import resourcePath from mcedit2.ut...
0.558086
0.125815
import pathlib import sys sys.path.append(str(pathlib.Path(__file__).absolute().parent.parent)) """ Shows a simple interface to control NL2 stations using a tkinter GUI Launch NoLimits 2 with the "--telemetry" option, then execute. """ import tkinter as tk from typing import Union from nl2telemetry.message import A...
demos/dispatch_control.py
import pathlib import sys sys.path.append(str(pathlib.Path(__file__).absolute().parent.parent)) """ Shows a simple interface to control NL2 stations using a tkinter GUI Launch NoLimits 2 with the "--telemetry" option, then execute. """ import tkinter as tk from typing import Union from nl2telemetry.message import A...
0.631367
0.167015
import webbrowser from base64 import b64encode from dataclasses import dataclass from http import HTTPStatus from http.server import BaseHTTPRequestHandler, HTTPServer from json import dumps, loads from threading import Thread from time import time from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, ove...
playlister/spotify.py
import webbrowser from base64 import b64encode from dataclasses import dataclass from http import HTTPStatus from http.server import BaseHTTPRequestHandler, HTTPServer from json import dumps, loads from threading import Thread from time import time from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, ove...
0.765067
0.082401
class Connection: """Lazy proxy for database connection.""" def __init__(self, factory, *args, **keywords): """Initialize with factory method to generate DB connection (e.g. odbc.odbc, cx_Oracle.connect) plus any positional and/or keyword arguments required when factory is called.""...
recipes/Python/66423_LazyDB/recipe-66423.py
class Connection: """Lazy proxy for database connection.""" def __init__(self, factory, *args, **keywords): """Initialize with factory method to generate DB connection (e.g. odbc.odbc, cx_Oracle.connect) plus any positional and/or keyword arguments required when factory is called.""...
0.860384
0.133868
"""A simple command line application to download youtube videos.""" import argparse import datetime as dt import gzip import json import logging import os import shutil import sys from io import BufferedWriter from typing import Any, Optional, List from pytube import __version__, CaptionQuery, Stream, Playlist from p...
pytube/cli.py
"""A simple command line application to download youtube videos.""" import argparse import datetime as dt import gzip import json import logging import os import shutil import sys from io import BufferedWriter from typing import Any, Optional, List from pytube import __version__, CaptionQuery, Stream, Playlist from p...
0.68763
0.211356
import datetime import multiprocessing import time import pytest from edera.exceptions import ExcusableError from edera.exceptions import ExcusableMasterSlaveInvocationError from edera.exceptions import MasterSlaveInvocationError from edera.invokers import MultiProcessInvoker from edera.routine import routine def t...
tests/integration/invokers/test_multiprocess_invoker.py
import datetime import multiprocessing import time import pytest from edera.exceptions import ExcusableError from edera.exceptions import ExcusableMasterSlaveInvocationError from edera.exceptions import MasterSlaveInvocationError from edera.invokers import MultiProcessInvoker from edera.routine import routine def t...
0.483892
0.427755
import serial import threading import time from multiprocessing import Process, Queue import config try: from queue import Empty except ImportError: from Queue import Empty class SerialManager(Process): """ This class has been written by <NAME> and can be found on https://gist.github.com/4...
server/SerialInterface.py
import serial import threading import time from multiprocessing import Process, Queue import config try: from queue import Empty except ImportError: from Queue import Empty class SerialManager(Process): """ This class has been written by <NAME> and can be found on https://gist.github.com/4...
0.251005
0.064359
from django import forms from django.conf import settings from django.forms import models, inlineformset_factory from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ from competitions.models import ( Submission, Competition, Student as CompetitionStudent, ...
pucadmin/frontoffice/forms.py
from django import forms from django.conf import settings from django.forms import models, inlineformset_factory from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ from competitions.models import ( Submission, Competition, Student as CompetitionStudent, ...
0.645343
0.206654
import vobject import json class Task: def __init__(self, vdata): self.data_dict = vobject.readOne(vdata) self.categories = self._parse_categories() self.created = self._parse_created() self.task_class = self._parse_class() self.description = self._parse_description() ...
task.py
import vobject import json class Task: def __init__(self, vdata): self.data_dict = vobject.readOne(vdata) self.categories = self._parse_categories() self.created = self._parse_created() self.task_class = self._parse_class() self.description = self._parse_description() ...
0.493164
0.124372
from datetime import date, datetime from django.core.management.base import BaseCommand, CommandError from django.db import transaction from tradeaccounts.models import Positions, TradeAccount, TradeAccountSnapshot from tradeaccounts.utils import calibrate_realtime_position from users.models import User class Comma...
siteadmins/management/commands/snapshot.py
from datetime import date, datetime from django.core.management.base import BaseCommand, CommandError from django.db import transaction from tradeaccounts.models import Positions, TradeAccount, TradeAccountSnapshot from tradeaccounts.utils import calibrate_realtime_position from users.models import User class Comma...
0.479991
0.14777
import os import sys from pprint import pprint from pathlib import Path import xlwt import model2 import mcutils as mc class ConfigFiles: working_dir = Path(os.path.abspath(__file__)).parent.parent working_dir = Path(os.getcwd()).parent input_data_path = os.path.join(working_dir, 'input_data') outpu...
CODE/utilities.py
import os import sys from pprint import pprint from pathlib import Path import xlwt import model2 import mcutils as mc class ConfigFiles: working_dir = Path(os.path.abspath(__file__)).parent.parent working_dir = Path(os.getcwd()).parent input_data_path = os.path.join(working_dir, 'input_data') outpu...
0.111205
0.149035
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from functionhelper.matrixhelper import delete_const_dims, pca_transform from functionhelper.preprocessinghelper import normalize from functionhelper.baseclassification import predict class BaseFMNNClassifier(object): ...
functionhelper/basefmnnclassifier.py
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from functionhelper.matrixhelper import delete_const_dims, pca_transform from functionhelper.preprocessinghelper import normalize from functionhelper.baseclassification import predict class BaseFMNNClassifier(object): ...
0.733643
0.605333
_base_ = [ # 'configs/_base_/models/upernet_swin.py', 'configs/_base_/datasets/cityscapes.py', 'configs/_base_/default_runtime.py', 'configs/_base_/schedules/schedule_160k.py' ] # By default, models are trained on 8 GPUs with 2 images per GPU data = dict(samples_per_gpu=4) # model settings norm_cfg = di...
upernet_swin_small_patch4_window7_512x512_320000_cityscape.py
_base_ = [ # 'configs/_base_/models/upernet_swin.py', 'configs/_base_/datasets/cityscapes.py', 'configs/_base_/default_runtime.py', 'configs/_base_/schedules/schedule_160k.py' ] # By default, models are trained on 8 GPUs with 2 images per GPU data = dict(samples_per_gpu=4) # model settings norm_cfg = di...
0.716814
0.150434
from __future__ import print_function import os import datetime class Log(object): def __init__(self, logdir_path='./log'): ''' Log - used for writing information to console and files about experimental runs. Arguments: logdir_path: path to the base log directory. ''' super(Log, self).__init__() ...
core/log.py
from __future__ import print_function import os import datetime class Log(object): def __init__(self, logdir_path='./log'): ''' Log - used for writing information to console and files about experimental runs. Arguments: logdir_path: path to the base log directory. ''' super(Log, self).__init__() ...
0.489015
0.12031
from __future__ import annotations from .. import exc from typing import TypeVar, Union, ClassVar, Iterator, Generic, Sized, \ SupportsInt, Iterable, Callable, Any class Skip: """Used to mark a field to be skipped during iteration.""" pass NOARG = type("NOARGE_TYPE", (), {})() class SkipInt(Skip, int)...
candejar/utilities/skip.py
from __future__ import annotations from .. import exc from typing import TypeVar, Union, ClassVar, Iterator, Generic, Sized, \ SupportsInt, Iterable, Callable, Any class Skip: """Used to mark a field to be skipped during iteration.""" pass NOARG = type("NOARGE_TYPE", (), {})() class SkipInt(Skip, int)...
0.906863
0.238772
import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans def euclideanDistance(centroid, datapoint): ''' Description:{ Calculates the Euclidean distance between a centroid and a data point } inputs: { centroid: centroid position datapoint:...
Semester 6/DWM/k_means.py
import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans def euclideanDistance(centroid, datapoint): ''' Description:{ Calculates the Euclidean distance between a centroid and a data point } inputs: { centroid: centroid position datapoint:...
0.754463
0.886322
import logging import environ env = environ.Env() # Build paths inside the project like this: os.path.join(ROOT_DIR, ...) # ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT_DIR = environ.Path(__file__) - 3 APPS_DIR = ROOT_DIR.path('apps') # https://docs.djangoproject.com/en/3.2/ref/settin...
config/settings/base.py
import logging import environ env = environ.Env() # Build paths inside the project like this: os.path.join(ROOT_DIR, ...) # ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT_DIR = environ.Path(__file__) - 3 APPS_DIR = ROOT_DIR.path('apps') # https://docs.djangoproject.com/en/3.2/ref/settin...
0.321993
0.0713
from django.shortcuts import render, redirect from django.http import HttpResponse, Http404,HttpResponseRedirect import datetime as dt from .models import Project, ProjectUpdateRecipients from .forms import ProjectUpdatesForm, NewProjectForm from .email import send_welcome_email from django.contrib.auth.decorators impo...
reviews/views.py
from django.shortcuts import render, redirect from django.http import HttpResponse, Http404,HttpResponseRedirect import datetime as dt from .models import Project, ProjectUpdateRecipients from .forms import ProjectUpdatesForm, NewProjectForm from .email import send_welcome_email from django.contrib.auth.decorators impo...
0.308815
0.068662
from kf_lib_data_ingest.common import constants from kf_lib_data_ingest.common.concept_schema import CONCEPT from common.utils import make_identifier, make_select, get RESOURCE_TYPE = "Patient" # https://hl7.org/fhir/us/core/ValueSet-omb-ethnicity-category.html omb_ethnicity_category = { constants.ETHNICITY.HISP...
kf_model_fhir/mappers/resources/kfdrc_patient.py
from kf_lib_data_ingest.common import constants from kf_lib_data_ingest.common.concept_schema import CONCEPT from common.utils import make_identifier, make_select, get RESOURCE_TYPE = "Patient" # https://hl7.org/fhir/us/core/ValueSet-omb-ethnicity-category.html omb_ethnicity_category = { constants.ETHNICITY.HISP...
0.675444
0.379091
from pytest import raises from jqfilters.operations import Operation, OPERATORS def test_identity(): f = OPERATORS['identity'] x = 'a' expected = x result = f(x) assert result == expected def test_toset(): f = OPERATORS['to_set'] x = 'a' expected = {'a'} result = f(x) assert...
tests/test_operations.py
from pytest import raises from jqfilters.operations import Operation, OPERATORS def test_identity(): f = OPERATORS['identity'] x = 'a' expected = x result = f(x) assert result == expected def test_toset(): f = OPERATORS['to_set'] x = 'a' expected = {'a'} result = f(x) assert...
0.792143
0.804828
import torch torch.manual_seed(123) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False import torch.nn as nn import torch.utils.data as data import torchvision import numpy as np np.random.seed(0) import hickle as hkl import pdb def unnormalize(X, nt=1, norm=True): mean = np.array([9...
src/utils/data_generator.py
import torch torch.manual_seed(123) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False import torch.nn as nn import torch.utils.data as data import torchvision import numpy as np np.random.seed(0) import hickle as hkl import pdb def unnormalize(X, nt=1, norm=True): mean = np.array([9...
0.718989
0.451931
import warnings warnings.simplefilter('ignore',DeprecationWarning) import os import sys from numpy import median, savez from optparse import OptionParser # Command-line args from qfed import QFED from qfed.Date import Date from qfed.met import MET #----------------------------------------------...
src/Components/qfed/qfed_l2c.py
import warnings warnings.simplefilter('ignore',DeprecationWarning) import os import sys from numpy import median, savez from optparse import OptionParser # Command-line args from qfed import QFED from qfed.Date import Date from qfed.met import MET #----------------------------------------------...
0.147647
0.101902
from config.protobuf import * # Rigid Bodies --------------------------------------------------------------------------------------------------------- # Single Joint Robot # Base Link points_0 = [Point(x=0, y=0, z=0), Point(x=-100, y=0, z=0), Point(x=100, y=0, z=0), Point(x=0, y=100, z=0)] lines_0 = [Line(point_0=poin...
python_prototype/config/robot_2.py
from config.protobuf import * # Rigid Bodies --------------------------------------------------------------------------------------------------------- # Single Joint Robot # Base Link points_0 = [Point(x=0, y=0, z=0), Point(x=-100, y=0, z=0), Point(x=100, y=0, z=0), Point(x=0, y=100, z=0)] lines_0 = [Line(point_0=poin...
0.462716
0.414247
import astroid from astroid.bases import BUILTINS from pylint.utils import OPTION_RGX from pylint.checkers.base import NameChecker from pylint.checkers.classes import ClassChecker from pylint.checkers.utils import node_frame_class from pylint.checkers.format import FormatChecker, _EMPTY_LINE from python_ta.check...
venv/lib/python3.6/site-packages/python_ta/patches/checkers.py
import astroid from astroid.bases import BUILTINS from pylint.utils import OPTION_RGX from pylint.checkers.base import NameChecker from pylint.checkers.classes import ClassChecker from pylint.checkers.utils import node_frame_class from pylint.checkers.format import FormatChecker, _EMPTY_LINE from python_ta.check...
0.58439
0.088781
import enum class ContractType(enum.Enum): """CT :: Contract Type. The ContractType is the most important information. It defines the cash flow generating pattern of a contract. The ContractType information in combination with a given state of the risk factors will produce a deterministic sequence of cash fl...
pyactus/domain/enums/contract_type.py
import enum class ContractType(enum.Enum): """CT :: Contract Type. The ContractType is the most important information. It defines the cash flow generating pattern of a contract. The ContractType information in combination with a given state of the risk factors will produce a deterministic sequence of cash fl...
0.751466
0.796253
from django.shortcuts import render,redirect from django.contrib.contenttypes.models import ContentType from django.contrib.auth.decorators import login_required from django.db.models import Count from django.http import JsonResponse from account.forms import UserCreationForm, LoginForm, RegisterForm from analytics.si...
src/srvup/views.py
from django.shortcuts import render,redirect from django.contrib.contenttypes.models import ContentType from django.contrib.auth.decorators import login_required from django.db.models import Count from django.http import JsonResponse from account.forms import UserCreationForm, LoginForm, RegisterForm from analytics.si...
0.281801
0.063919
from django.test import TestCase from django.test.client import RequestFactory from mysqlapi.api.models import Instance from mysqlapi.api.tests import mocks from mysqlapi.api.views import Healthcheck import mock class HealthcheckTestCase(TestCase): def setUp(self): self.instance = Instance.objects.cre...
mysqlapi/api/tests/test_healthcheck.py
from django.test import TestCase from django.test.client import RequestFactory from mysqlapi.api.models import Instance from mysqlapi.api.tests import mocks from mysqlapi.api.views import Healthcheck import mock class HealthcheckTestCase(TestCase): def setUp(self): self.instance = Instance.objects.cre...
0.57093
0.125627
import numpy as np def verifica_quadrada(matriz_A): linhas, colunas = np.shape(matriz_A) return linhas == colunas def verifica_inversa(matriz_A): if verifica_quadrada(matriz_A): print("A matriz é quadrada") det = np.linalg.det(matriz_A) print("O determinante da matriz é:", det) ...
criterios.py
import numpy as np def verifica_quadrada(matriz_A): linhas, colunas = np.shape(matriz_A) return linhas == colunas def verifica_inversa(matriz_A): if verifica_quadrada(matriz_A): print("A matriz é quadrada") det = np.linalg.det(matriz_A) print("O determinante da matriz é:", det) ...
0.270577
0.809916
from flask_restful import Resource, reqparse from models.user import UserModel from models.user_info import UserInfoModel from flask_jwt import jwt_required class UserInfo(Resource): root_parser = reqparse.RequestParser() root_parser.add_argument( "address", type=dict, help="This field cannot be left...
resources/user_info.py
from flask_restful import Resource, reqparse from models.user import UserModel from models.user_info import UserInfoModel from flask_jwt import jwt_required class UserInfo(Resource): root_parser = reqparse.RequestParser() root_parser.add_argument( "address", type=dict, help="This field cannot be left...
0.484868
0.073763
import datetime import logging import pandas as pd from modules.utils import get_season logger = logging.getLogger('client_data') class UtilTablesError(Exception): pass def create_utility_tables(conn, start_date, end_date, start_peak, end_peak): ''' Populates tables used to provide attributes to days ...
src/python/modules/utility_tables.py
import datetime import logging import pandas as pd from modules.utils import get_season logger = logging.getLogger('client_data') class UtilTablesError(Exception): pass def create_utility_tables(conn, start_date, end_date, start_peak, end_peak): ''' Populates tables used to provide attributes to days ...
0.385837
0.244622
import jsonpickle, csv class Commit(object): date = "" commitkey = "" author = "" description = "" filesModified = [] filesAdded = [] filesDeleted = [] def __init__(self, date, commitkey, author, description, filesModified, filesAdded, filesDeleted): self.date = date sel...
tools/commit.py
import jsonpickle, csv class Commit(object): date = "" commitkey = "" author = "" description = "" filesModified = [] filesAdded = [] filesDeleted = [] def __init__(self, date, commitkey, author, description, filesModified, filesAdded, filesDeleted): self.date = date sel...
0.14777
0.067301
import math import pyglet from pyglet.gl import * from .shape import Shape class Triangle(Shape): ''' Triangle shape. This is a class for rendering a triangle. ''' # _________________________________________________________________ __init__ def __init__(self, direction='up', *args, **kwargs): ...
PyWidget3/shape/triangle.py
import math import pyglet from pyglet.gl import * from .shape import Shape class Triangle(Shape): ''' Triangle shape. This is a class for rendering a triangle. ''' # _________________________________________________________________ __init__ def __init__(self, direction='up', *args, **kwargs): ...
0.747339
0.40489
from cryptography import x509 from cryptography.hazmat.backends.openssl.decode_asn1 import ( _DISTPOINT_TYPE_FULLNAME, _DISTPOINT_TYPE_RELATIVENAME, ) from cryptography.x509.name import _ASN1Type from cryptography.x509.oid import ExtensionOID def _encode_asn1_int(backend, x): """ Converts a python i...
src/cryptography/hazmat/backends/openssl/encode_asn1.py
from cryptography import x509 from cryptography.hazmat.backends.openssl.decode_asn1 import ( _DISTPOINT_TYPE_FULLNAME, _DISTPOINT_TYPE_RELATIVENAME, ) from cryptography.x509.name import _ASN1Type from cryptography.x509.oid import ExtensionOID def _encode_asn1_int(backend, x): """ Converts a python i...
0.484868
0.225182
from __future__ import division, print_function # Import Python modules import os import unittest # Import Broadband modules import cmp_bbp import seqnum import bband_utils from install_cfg import InstallCfg from wcc_siteamp_cfg import WccSiteampCfg from wcc_siteamp import WccSiteamp class TestWccSiteamp(unittest.Te...
bbp/tests/test_wcc_siteamp.py
from __future__ import division, print_function # Import Python modules import os import unittest # Import Broadband modules import cmp_bbp import seqnum import bband_utils from install_cfg import InstallCfg from wcc_siteamp_cfg import WccSiteampCfg from wcc_siteamp import WccSiteamp class TestWccSiteamp(unittest.Te...
0.342681
0.147647