code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class InstructionMiss(Base):
"""The InstructionMiss class encapsulates a required instructionMiss node in the ixnetwork hierarchy.
An instance of the class can be obtained by accessing the InstructionMiss property from a p... | RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/openflow/instructionmiss.py |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class InstructionMiss(Base):
"""The InstructionMiss class encapsulates a required instructionMiss node in the ixnetwork hierarchy.
An instance of the class can be obtained by accessing the InstructionMiss property from a p... | 0.787564 | 0.185726 |
from __future__ import absolute_import, division, print_function
from libtbx.utils import Sorry, Usage
from libtbx import slots_getstate_setstate
import re
import sys
master_phil = """
mtz_file = None
.type = path
f_obs_label = F-obs-filtered
.type = str
f_calc_label = F-model
.type = str
r_free_label = R-free-f... | mmtbx/command_line/show_r_factors_by_shell.py | from __future__ import absolute_import, division, print_function
from libtbx.utils import Sorry, Usage
from libtbx import slots_getstate_setstate
import re
import sys
master_phil = """
mtz_file = None
.type = path
f_obs_label = F-obs-filtered
.type = str
f_calc_label = F-model
.type = str
r_free_label = R-free-f... | 0.339061 | 0.202956 |
from django.db import models
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill
from datetime import datetime
from django_extensions.db.models import TimeStampedModel
from django.contrib.auth import get_user_model
User = get_user_model()
def found_thumbnail_path(instance, fi... | back/found/models.py | from django.db import models
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill
from datetime import datetime
from django_extensions.db.models import TimeStampedModel
from django.contrib.auth import get_user_model
User = get_user_model()
def found_thumbnail_path(instance, fi... | 0.654564 | 0.119049 |
import hashlib
import itertools
import tempfile
from celery import shared_task
import structlog
from ..analytics.tasks import repo_analyzers
from ..auditing import runner
from ..auditing.check_discovery import CHECKS as AUDITING_CHECKS
from .exceptions import MissingFilesError, RepositoryNotFoundError
from .github im... | zoo/repos/tasks.py | import hashlib
import itertools
import tempfile
from celery import shared_task
import structlog
from ..analytics.tasks import repo_analyzers
from ..auditing import runner
from ..auditing.check_discovery import CHECKS as AUDITING_CHECKS
from .exceptions import MissingFilesError, RepositoryNotFoundError
from .github im... | 0.365343 | 0.063802 |
from queue import Empty, Queue
import sys
from threading import Event, Thread
from traceback import print_exc
from api import models
from api.models import constants
from peewee import DoesNotExist
import requests
import tracker_init
# Worker thread for taking events off of the event queue and sending them
# Can be ... | api/event_broadcaster.py | from queue import Empty, Queue
import sys
from threading import Event, Thread
from traceback import print_exc
from api import models
from api.models import constants
from peewee import DoesNotExist
import requests
import tracker_init
# Worker thread for taking events off of the event queue and sending them
# Can be ... | 0.519278 | 0.105856 |
from qcloudsdkcore.request import Request
class DescribeNetworkInterfacesRequest(Request):
def __init__(self):
super(DescribeNetworkInterfacesRequest, self).__init__(
'vpc', 'qcloudcliV1', 'DescribeNetworkInterfaces', 'vpc.api.qcloud.com')
def get_eniDescription(self):
return sel... | qcloudsdkvpc/DescribeNetworkInterfacesRequest.py |
from qcloudsdkcore.request import Request
class DescribeNetworkInterfacesRequest(Request):
def __init__(self):
super(DescribeNetworkInterfacesRequest, self).__init__(
'vpc', 'qcloudcliV1', 'DescribeNetworkInterfaces', 'vpc.api.qcloud.com')
def get_eniDescription(self):
return sel... | 0.706798 | 0.114023 |
import numpy as np
from core.node import *
from core.node_socket import *
import os.path
from utils.MECWidgets import SVGLabel
# TODO passar esses metodos para dentro do modulo da porta Serial
class Node_data(Node):
def __init__(self, scene, title="Bloco dados", parent=None, method=None):
super().__init__... | nodes/data_io.py | import numpy as np
from core.node import *
from core.node_socket import *
import os.path
from utils.MECWidgets import SVGLabel
# TODO passar esses metodos para dentro do modulo da porta Serial
class Node_data(Node):
def __init__(self, scene, title="Bloco dados", parent=None, method=None):
super().__init__... | 0.090151 | 0.187207 |
from django.conf import settings
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from django.http import Http404
from django.core.m... | qym_api/views.py | from django.conf import settings
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from django.http import Http404
from django.core.m... | 0.322099 | 0.104798 |
from dtable.models import *
from tokens.models import *
tokens = Token.objects.exclude(cluster__isnull=True)
errors = []
for x in tokens[:5]:
temp_new,_ = NormToken.objects.get_or_create(legacy_id=x.legacy_id)
temp_new.spelling = x.spelling
temp_new.left_context = x.left_context
temp_new.plain_word = x... | Token2NormToken.py | from dtable.models import *
from tokens.models import *
tokens = Token.objects.exclude(cluster__isnull=True)
errors = []
for x in tokens[:5]:
temp_new,_ = NormToken.objects.get_or_create(legacy_id=x.legacy_id)
temp_new.spelling = x.spelling
temp_new.left_context = x.left_context
temp_new.plain_word = x... | 0.164718 | 0.190009 |
import sys
import os
import CppHeaderParser
import globalVar
from config import *
from genJsApi import *
from genJsApiMap import *
from genC import *
from genShell import *
def ParseHeader(name):
try:
printDbg("parsing " + name)
cppHeader = CppHeaderParser.CppHeader(name)
except CppHeade... | utils/autogen/run.py | import sys
import os
import CppHeaderParser
import globalVar
from config import *
from genJsApi import *
from genJsApiMap import *
from genC import *
from genShell import *
def ParseHeader(name):
try:
printDbg("parsing " + name)
cppHeader = CppHeaderParser.CppHeader(name)
except CppHeade... | 0.12768 | 0.065425 |
import torch
from torch import nn
from cosypose.config import DEBUG_DATA_DIR
from cosypose.lib3d.camera_geometry import get_K_crop_resize, boxes_from_uv
from cosypose.lib3d.cropping import deepim_crops_robust as deepim_crops
from cosypose.lib3d.camera_geometry import project_points_robust as project_points
... | models/pose.py | import torch
from torch import nn
from cosypose.config import DEBUG_DATA_DIR
from cosypose.lib3d.camera_geometry import get_K_crop_resize, boxes_from_uv
from cosypose.lib3d.cropping import deepim_crops_robust as deepim_crops
from cosypose.lib3d.camera_geometry import project_points_robust as project_points
... | 0.848314 | 0.349449 |
import math
import pdb
from copy import deepcopy
from functools import partial
from itertools import product
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils import checkpoint as torch_checkpoint
from torch_butterfly import Butterfly
from torch_butterfly.combine... | old/xd-original/xd/xd.py | import math
import pdb
from copy import deepcopy
from functools import partial
from itertools import product
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils import checkpoint as torch_checkpoint
from torch_butterfly import Butterfly
from torch_butterfly.combine... | 0.886666 | 0.46132 |
import numpy as np
import pyqtgraph as pg
from PyQt5 import QtCore
from acconeer_utils.clients.reg.client import RegClient, RegSPIClient
from acconeer_utils.clients.json.client import JSONClient
from acconeer_utils.clients import configs
from acconeer_utils import example_utils
from acconeer_utils.pg_process import PG... | examples/processing/presence_detection_sparse.py | import numpy as np
import pyqtgraph as pg
from PyQt5 import QtCore
from acconeer_utils.clients.reg.client import RegClient, RegSPIClient
from acconeer_utils.clients.json.client import JSONClient
from acconeer_utils.clients import configs
from acconeer_utils import example_utils
from acconeer_utils.pg_process import PG... | 0.502441 | 0.138113 |
# Usage:
# PYTHONPATH='/home/users/arsh/ultrasound' \
# CUDA_VISIBLE_DEVICES=1 \
# taskset --cpu-list 10-19 \
# python src/main/train.py --config va5.yml \
# [--wandb] [--resume]
import argparse
import os
import sys
import time
from pprint import pprint
import torch
sys.path.append('../../')
import src.utils.const... | src/main/train.py |
# Usage:
# PYTHONPATH='/home/users/arsh/ultrasound' \
# CUDA_VISIBLE_DEVICES=1 \
# taskset --cpu-list 10-19 \
# python src/main/train.py --config va5.yml \
# [--wandb] [--resume]
import argparse
import os
import sys
import time
from pprint import pprint
import torch
sys.path.append('../../')
import src.utils.const... | 0.625552 | 0.1918 |
from functools import wraps
from flask import request
from flask.ext.restful import reqparse, abort, Resource
from flask.views import http_method_funcs, View, MethodView
import six
from werkzeug.utils import cached_property
from flask.ext.presst.utils.routes import route_from
from flask_presst.parsing import PresstArgu... | flask_presst/nesting.py | from functools import wraps
from flask import request
from flask.ext.restful import reqparse, abort, Resource
from flask.views import http_method_funcs, View, MethodView
import six
from werkzeug.utils import cached_property
from flask.ext.presst.utils.routes import route_from
from flask_presst.parsing import PresstArgu... | 0.826642 | 0.099645 |
from simulation import cancel_simulation, delete_simulation, delete_simulation_files, load_simulations, cleanup_sim_output, cleanup_sim_workspace
import json
import sys
import logging
from utils import load_sys_cfg
conf = load_sys_cfg()
sims_path = conf['sims_path']
def cleanup_delete(sim_id):
simulations = load_... | cleanup.py | from simulation import cancel_simulation, delete_simulation, delete_simulation_files, load_simulations, cleanup_sim_output, cleanup_sim_workspace
import json
import sys
import logging
from utils import load_sys_cfg
conf = load_sys_cfg()
sims_path = conf['sims_path']
def cleanup_delete(sim_id):
simulations = load_... | 0.117066 | 0.38659 |
import asyncio
from aiohttp import web
from . import utility
from . import communicate
import time
from . import log
from yueban import config
_log_category = 'yueban_schdule'
_slow_log_time = 0.1
_web_app = None
async def log_info(*args):
global _log_category
log.info(_log_category, *args)
async def lo... | yueban/scheduler.py | import asyncio
from aiohttp import web
from . import utility
from . import communicate
import time
from . import log
from yueban import config
_log_category = 'yueban_schdule'
_slow_log_time = 0.1
_web_app = None
async def log_info(*args):
global _log_category
log.info(_log_category, *args)
async def lo... | 0.261237 | 0.060225 |
from typing import List, Optional
from fastapi.encoders import jsonable_encoder
from .models import Participant, ParticipantCreate, ParticipantUpdate
from dispatch.individual.models import IndividualContact
from dispatch.participant_role.models import ParticipantRole
def get(*, db_session, participant_id: int) -> Op... | src/dispatch/participant/service.py | from typing import List, Optional
from fastapi.encoders import jsonable_encoder
from .models import Participant, ParticipantCreate, ParticipantUpdate
from dispatch.individual.models import IndividualContact
from dispatch.participant_role.models import ParticipantRole
def get(*, db_session, participant_id: int) -> Op... | 0.851722 | 0.192558 |
import urllib2, cookielib, csv, sys
from bs4 import BeautifulSoup
# gets company data by sector in the following format
# [ticker, name]
# sector_num:
# Aerospace & Defense - 2710
# Alternative Energy - 0580
# Automobiles & Parts - 3350
# Banks - 8350
# Beverages - 3530
# Chemicals - 1350
# Construction & Materials - ... | src/dialogflow-java-client-master/samples/clients/VirtualTradingAssistant/src/main/java/ai/examples/scraper/sectorsScraper.py | import urllib2, cookielib, csv, sys
from bs4 import BeautifulSoup
# gets company data by sector in the following format
# [ticker, name]
# sector_num:
# Aerospace & Defense - 2710
# Alternative Energy - 0580
# Automobiles & Parts - 3350
# Banks - 8350
# Beverages - 3530
# Chemicals - 1350
# Construction & Materials - ... | 0.086125 | 0.09947 |
from BinaryTree import BinaryTree
class SearchTree(BinaryTree):
def insert(self, key):
self._insert_helper(self, key)
def search(self, key):
return self._search_helper(self, key)
def delete(self, key):
pass
@staticmethod
def _insert_helper(root, key):
if root.key... | myalgorithms/SearchTree.py | from BinaryTree import BinaryTree
class SearchTree(BinaryTree):
def insert(self, key):
self._insert_helper(self, key)
def search(self, key):
return self._search_helper(self, key)
def delete(self, key):
pass
@staticmethod
def _insert_helper(root, key):
if root.key... | 0.805976 | 0.15633 |
import numpy as np
from shogun import TableFactorType
# create the factor type with GT parameters
tid = 0
cards = np.array([2,2], np.int32)
w_gt = np.array([0.3,0.5,1.0,0.2,0.05,0.6,-0.2,0.75])
fac_type = TableFactorType(tid, cards, w_gt)
tid_u = 1
cards_u = np.array([2], np.int32)
w_gt_u = np.array([0.5,0.8,1.0,-0.... | examples/undocumented/python/structure_factor_graph_model.py |
import numpy as np
from shogun import TableFactorType
# create the factor type with GT parameters
tid = 0
cards = np.array([2,2], np.int32)
w_gt = np.array([0.3,0.5,1.0,0.2,0.05,0.6,-0.2,0.75])
fac_type = TableFactorType(tid, cards, w_gt)
tid_u = 1
cards_u = np.array([2], np.int32)
w_gt_u = np.array([0.5,0.8,1.0,-0.... | 0.31216 | 0.496765 |
from __future__ import print_function, division, absolute_import
from Qt.QtCore import Qt, Signal
from Qt.QtWidgets import QSizePolicy, QWidget, QSplitter, QScrollArea
from tpDcc.managers import resources
from tpDcc.libs.qt.core import base
from tpDcc.libs.qt.widgets import layouts, stack, buttons, dividers
class P... | tpDcc/libs/qt/core/preferences.py | from __future__ import print_function, division, absolute_import
from Qt.QtCore import Qt, Signal
from Qt.QtWidgets import QSizePolicy, QWidget, QSplitter, QScrollArea
from tpDcc.managers import resources
from tpDcc.libs.qt.core import base
from tpDcc.libs.qt.widgets import layouts, stack, buttons, dividers
class P... | 0.493409 | 0.08218 |
class _Address:
MAPPING = {
'line_1': '{prefix}_1',
'line_2': '{prefix}_2',
'town': '{prefix}_town',
'county': '{prefix}_county',
'postcode': '{prefix}_postcode',
'country': '{prefix}_country',
}
def __init__(self, field_prefix, company):
"""
... | datahub/omis/order/utils.py | class _Address:
MAPPING = {
'line_1': '{prefix}_1',
'line_2': '{prefix}_2',
'town': '{prefix}_town',
'county': '{prefix}_county',
'postcode': '{prefix}_postcode',
'country': '{prefix}_country',
}
def __init__(self, field_prefix, company):
"""
... | 0.900966 | 0.265083 |
import utils.setting as Setting
from PySide2.QtWidgets import (
QComboBox,
QLabel,
QCheckBox,
QSpinBox,
QHBoxLayout,
QMessageBox
)
def show_message_box(self, msg, title, msg_type='information'):
msgbox = QMessageBox(self)
if msg_type == 'warning':
msgbox.setIcon(QMessageBox.Wa... | iotwin_data_generator/utils/gui_helper.py | import utils.setting as Setting
from PySide2.QtWidgets import (
QComboBox,
QLabel,
QCheckBox,
QSpinBox,
QHBoxLayout,
QMessageBox
)
def show_message_box(self, msg, title, msg_type='information'):
msgbox = QMessageBox(self)
if msg_type == 'warning':
msgbox.setIcon(QMessageBox.Wa... | 0.392104 | 0.107437 |
import statistics
from sklearn import preprocessing
import numpy as np
import math
# Reads data from mentioned dataset, saves the result values and deletes first two columns
# (these are not required for making predictions since they only identify the entry)
def get_data(dataset):
data = np.genfromtxt(dataset, del... | src/data_operator.py | import statistics
from sklearn import preprocessing
import numpy as np
import math
# Reads data from mentioned dataset, saves the result values and deletes first two columns
# (these are not required for making predictions since they only identify the entry)
def get_data(dataset):
data = np.genfromtxt(dataset, del... | 0.47926 | 0.765374 |
import os
import json
import time
import mlflow
import shutil
import getpass
import platform
from typing import Any
from typing import Dict
from typing import Optional
from cftool.misc import lock_manager
from cftool.misc import fix_float_to_length
from mlflow.exceptions import MlflowException
from mlflow.utils.mlflow... | cflow/misc/internal_/callbacks/general.py | import os
import json
import time
import mlflow
import shutil
import getpass
import platform
from typing import Any
from typing import Dict
from typing import Optional
from cftool.misc import lock_manager
from cftool.misc import fix_float_to_length
from mlflow.exceptions import MlflowException
from mlflow.utils.mlflow... | 0.717408 | 0.108779 |
import requests
from requests.auth import HTTPBasicAuth
import os
import json
import logging
logger = logging.getLogger('inventree')
class InvenTreeAPI(object):
"""
Basic class for performing Inventree API requests.
"""
MIN_SUPPORTED_API_VERSION = 6
@staticmethod
def getMinApiVersion():
... | inventree/api.py | import requests
from requests.auth import HTTPBasicAuth
import os
import json
import logging
logger = logging.getLogger('inventree')
class InvenTreeAPI(object):
"""
Basic class for performing Inventree API requests.
"""
MIN_SUPPORTED_API_VERSION = 6
@staticmethod
def getMinApiVersion():
... | 0.641422 | 0.058804 |
"""A sampler for PEARL."""
import numpy as np
from metarl.sampler.utils import rollout_pearl
from metarl.sampler.base import BaseSampler
class PEARLSampler(BaseSampler):
"""A sampler used in meta-RL algorithms involving context.
It stores context and resample belief in the policy every step.
Args:
... | src/metarl/sampler/pearl_sampler.py | """A sampler for PEARL."""
import numpy as np
from metarl.sampler.utils import rollout_pearl
from metarl.sampler.base import BaseSampler
class PEARLSampler(BaseSampler):
"""A sampler used in meta-RL algorithms involving context.
It stores context and resample belief in the policy every step.
Args:
... | 0.913218 | 0.444444 |
import os
import codecs
import json
from setuptools import setup, find_packages
def get_setup_version(reponame):
"""
Helper to get the current version from either git describe or the
.version file (if available).
"""
basepath = os.path.split(__file__)[0]
version_file_path = os.path.join(basep... | setup.py |
import os
import codecs
import json
from setuptools import setup, find_packages
def get_setup_version(reponame):
"""
Helper to get the current version from either git describe or the
.version file (if available).
"""
basepath = os.path.split(__file__)[0]
version_file_path = os.path.join(basep... | 0.357007 | 0.127734 |
import frappe
from frappe.model.document import Document
class ListViewSettings(Document):
def on_update(self):
frappe.clear_document_cache(self.doctype, self.name)
@frappe.whitelist()
def save_listview_settings(doctype, listview_settings, removed_listview_fields):
listview_settings = frappe.parse_json(listvi... | frappe/desk/doctype/list_view_settings/list_view_settings.py |
import frappe
from frappe.model.document import Document
class ListViewSettings(Document):
def on_update(self):
frappe.clear_document_cache(self.doctype, self.name)
@frappe.whitelist()
def save_listview_settings(doctype, listview_settings, removed_listview_fields):
listview_settings = frappe.parse_json(listvi... | 0.306942 | 0.124665 |
import numpy as np
import mindspore.context as context
import mindspore.nn as nn
from mindspore import Tensor
from mindspore.ops.operations import _grad_ops as G
context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
class ResizeBilinearGradAlignCornerT(nn.Cell):
def __init__(self):
super(Res... | tests/st/ops/cpu/test_resize_bilinear_grad_op.py |
import numpy as np
import mindspore.context as context
import mindspore.nn as nn
from mindspore import Tensor
from mindspore.ops.operations import _grad_ops as G
context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
class ResizeBilinearGradAlignCornerT(nn.Cell):
def __init__(self):
super(Res... | 0.742141 | 0.577674 |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
clean_html,
int_or_none,
try_get,
unified_strdate,
unified_timestamp,
)
class AmericasTestKitchenIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?(?:americastestkitchen|cooks(?:count... | youtube_dl/extractor/americastestkitchen.py | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
clean_html,
int_or_none,
try_get,
unified_strdate,
unified_timestamp,
)
class AmericasTestKitchenIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?(?:americastestkitchen|cooks(?:count... | 0.461259 | 0.217483 |
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from ansible_collections.community.general.tests.unit.compat.mock import MagicMock
from ansible.errors import AnsibleError
from ansible.module_utils.six.moves import http_client
from a... | exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/tests/unit/plugins/lookup/test_conjur_variable.py |
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from ansible_collections.community.general.tests.unit.compat.mock import MagicMock
from ansible.errors import AnsibleError
from ansible.module_utils.six.moves import http_client
from a... | 0.651355 | 0.199971 |
from users.models import User
from users.serializers import UserSerializer, UserGroupSerializer
from rest_framework import permissions
from django.contrib.auth import views
from django.contrib.auth import login as auth_login
from django.http import HttpResponse, JsonResponse, HttpResponseBadRequest
from django.sh... | src/users/views.py | from users.models import User
from users.serializers import UserSerializer, UserGroupSerializer
from rest_framework import permissions
from django.contrib.auth import views
from django.contrib.auth import login as auth_login
from django.http import HttpResponse, JsonResponse, HttpResponseBadRequest
from django.sh... | 0.544801 | 0.056757 |
import numpy as np
from ..meshio import form_mesh
from .remove_isolated_vertices import remove_isolated_vertices_raw
from .remove_duplicated_vertices import remove_duplicated_vertices_raw
from .generate_box_mesh import split_hex_into_tets, split_hex_into_tets_symmetrically
from .generate_box_mesh import subdivid... | PyMesh/python/pymesh/meshutils/hex_to_tet.py | import numpy as np
from ..meshio import form_mesh
from .remove_isolated_vertices import remove_isolated_vertices_raw
from .remove_duplicated_vertices import remove_duplicated_vertices_raw
from .generate_box_mesh import split_hex_into_tets, split_hex_into_tets_symmetrically
from .generate_box_mesh import subdivid... | 0.665302 | 0.401776 |
beamtime and details about how to carry out the experiments. """
from datetime import datetime
import pandas as pd
from regolith.builders.basebuilder import LatexBuilderBase
from regolith.tools import all_docs_from_collection, group, id_key
class BeamPlanBuilder(LatexBuilderBase):
"""
Build a file of experi... | regolith/builders/beamplanbuilder.py | beamtime and details about how to carry out the experiments. """
from datetime import datetime
import pandas as pd
from regolith.builders.basebuilder import LatexBuilderBase
from regolith.tools import all_docs_from_collection, group, id_key
class BeamPlanBuilder(LatexBuilderBase):
"""
Build a file of experi... | 0.866571 | 0.480174 |
import os
import sys
import argparse
import numpy as np
from PIL import Image
import cv2
import random
import pickle
import pdb
st = pdb.set_trace
_IMGEXT = 'png'
def get_frames(vidpath, image_size=0, every_nth=1, trim_len=float('Inf')):
# get frames as list of images, return a list of list
vidcap = cv2.Video... | scripts/process_action.py | import os
import sys
import argparse
import numpy as np
from PIL import Image
import cv2
import random
import pickle
import pdb
st = pdb.set_trace
_IMGEXT = 'png'
def get_frames(vidpath, image_size=0, every_nth=1, trim_len=float('Inf')):
# get frames as list of images, return a list of list
vidcap = cv2.Video... | 0.137764 | 0.105763 |
from insights.core.context import OSP
from insights.parsers.haproxy_cfg import HaproxyCfg
from insights.tests import context_wrap
haproxy_osp = """
# This file managed by Puppet
global
daemon
group haproxy
maxconn 10000
pidfile /var/run/haproxy.pid
user haproxy
defaults
log 127.0.0.1 local2 warning
... | insights/parsers/tests/test_haproxy_cfg.py | from insights.core.context import OSP
from insights.parsers.haproxy_cfg import HaproxyCfg
from insights.tests import context_wrap
haproxy_osp = """
# This file managed by Puppet
global
daemon
group haproxy
maxconn 10000
pidfile /var/run/haproxy.pid
user haproxy
defaults
log 127.0.0.1 local2 warning
... | 0.405802 | 0.080864 |
from Crypto.Cipher import AES
from Crypto.Random import random
class TestRule2c:
def __init__(self):
self.g_iv1 = b"1234567812345678"
self.g_iv2 = bytes("1234567812345678", "utf8")
def p_example1_hard_coded1(self, key, data):
cipher = AES.new(key, AES.MODE_CBC, b"1234567812345678")
... | resources/test_cases/python/PyCrypto/TestRule2c.py | from Crypto.Cipher import AES
from Crypto.Random import random
class TestRule2c:
def __init__(self):
self.g_iv1 = b"1234567812345678"
self.g_iv2 = bytes("1234567812345678", "utf8")
def p_example1_hard_coded1(self, key, data):
cipher = AES.new(key, AES.MODE_CBC, b"1234567812345678")
... | 0.732592 | 0.292873 |
from django.shortcuts import render, redirect, HttpResponse
from django.contrib import messages
from django.contrib.auth.models import User
from Shop.models import Customer, Product, Order, CartItem, OrderList
from Shop.sendmail import send_payment_confirmation
from django.conf import settings
from django.views.decorat... | payments/views.py | from django.shortcuts import render, redirect, HttpResponse
from django.contrib import messages
from django.contrib.auth.models import User
from Shop.models import Customer, Product, Order, CartItem, OrderList
from Shop.sendmail import send_payment_confirmation
from django.conf import settings
from django.views.decorat... | 0.386763 | 0.091788 |
from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
from core.helpers import create_user
from core.models import Ingredient
from recipe.serializers import IngredientSerializer
INGEREDIENT_URL = reverse("recipe:ingredient-list")... | app/recipe/tests/test_ingredients_api.py | from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
from core.helpers import create_user
from core.models import Ingredient
from recipe.serializers import IngredientSerializer
INGEREDIENT_URL = reverse("recipe:ingredient-list")... | 0.554953 | 0.306216 |
def main():
import re
import urllib
web=urllib.urlopen('http://ip-lookup.net/') #Getting IP Adress
content=web.read()
m = re.search('(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01... | Old-Version/Insult-IP_0.0.1.py |
def main():
import re
import urllib
web=urllib.urlopen('http://ip-lookup.net/') #Getting IP Adress
content=web.read()
m = re.search('(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01... | 0.050272 | 0.081886 |
import argparse
import sys
from enum import Enum, unique
from pathlib import Path
from typing import Any, Callable, Dict, Union
sys.path.append('../../../..')
import plotly.graph_objects as go
from hyperstyle.src.python.common.tool_arguments import RunToolArgument
from analysis.src.python.evaluation.inspectors.common... | analysis/src/python/evaluation/plots/diffs_plotter.py | import argparse
import sys
from enum import Enum, unique
from pathlib import Path
from typing import Any, Callable, Dict, Union
sys.path.append('../../../..')
import plotly.graph_objects as go
from hyperstyle.src.python.common.tool_arguments import RunToolArgument
from analysis.src.python.evaluation.inspectors.common... | 0.640186 | 0.230346 |
from django.shortcuts import render
import tweepy, requests
import sys, requests, json, time, os
from django.contrib.messages.views import messages
from .forms import InputForm
from django.conf import settings
CONSUMER_KEY = settings.CONSUMER_KEY
CONSUMER_SECRET = settings.CONSUMER_SECRET
ACCESS_TOKEN = settings.ACCE... | twitter_app/twitter_bot/views.py | from django.shortcuts import render
import tweepy, requests
import sys, requests, json, time, os
from django.contrib.messages.views import messages
from .forms import InputForm
from django.conf import settings
CONSUMER_KEY = settings.CONSUMER_KEY
CONSUMER_SECRET = settings.CONSUMER_SECRET
ACCESS_TOKEN = settings.ACCE... | 0.119524 | 0.057335 |
# Use tf version 2.3.0 as 1.x
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import os
import yarp
import time
import argparse
import numpy as np
from scenario import gazebo as scenario
from adherent.data_processing.utils import iCub
from gym_ignition.utils.scenario import init_gazebo_sim
from gym_ignitio... | scripts/trajectory_generation.py |
# Use tf version 2.3.0 as 1.x
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import os
import yarp
import time
import argparse
import numpy as np
from scenario import gazebo as scenario
from adherent.data_processing.utils import iCub
from gym_ignition.utils.scenario import init_gazebo_sim
from gym_ignitio... | 0.620277 | 0.330026 |
from dash.development.base_component import Component, _explicitize_args
class ExampleComponent(Component):
"""A ExampleComponent component.
ExampleComponent is an example component.
It takes a property, `label`, and
displays it.
It renders an input with the property `value`
which is editable by the user.
Keywo... | idest_dash_components/ExampleComponent.py |
from dash.development.base_component import Component, _explicitize_args
class ExampleComponent(Component):
"""A ExampleComponent component.
ExampleComponent is an example component.
It takes a property, `label`, and
displays it.
It renders an input with the property `value`
which is editable by the user.
Keywo... | 0.811564 | 0.318088 |
from datetime import datetime, timedelta
from unittest import mock
import pytest
import rpcq
from dateutil.tz import tzutc
from pytest_mock import MockerFixture
from qcs_api_client.models import EngagementWithCredentials, EngagementCredentials
from rpcq.messages import QPURequest
from pyquil.api._qpu_client import (
... | test/unit/test_qpu_client.py | from datetime import datetime, timedelta
from unittest import mock
import pytest
import rpcq
from dateutil.tz import tzutc
from pytest_mock import MockerFixture
from qcs_api_client.models import EngagementWithCredentials, EngagementCredentials
from rpcq.messages import QPURequest
from pyquil.api._qpu_client import (
... | 0.801354 | 0.205735 |
command += oiiotool ("-pattern constant:color=.5,.1,.1 256x256 3 -text:size=50:x=75:y=140 u1v1 --attrib Make pet --attrib Model dog -d uint8 -otex file_u1v1.tx")
command += oiiotool ("-pattern constant:color=.1,.5,.1 256x256 3 -text:size=50:x=75:y=140 u2v1 --attrib Make pet --attrib Model dog -d uint8 -otex file_u2v... | testsuite/texture-udim2/run.py |
command += oiiotool ("-pattern constant:color=.5,.1,.1 256x256 3 -text:size=50:x=75:y=140 u1v1 --attrib Make pet --attrib Model dog -d uint8 -otex file_u1v1.tx")
command += oiiotool ("-pattern constant:color=.1,.5,.1 256x256 3 -text:size=50:x=75:y=140 u2v1 --attrib Make pet --attrib Model dog -d uint8 -otex file_u2v... | 0.492188 | 0.237642 |
from django.db import models
from django.contrib.sites.models import Site
from django.core.validators import MaxValueValidator, MinValueValidator
class Config(models.Model):
site = models.OneToOneField(Site, on_delete=models.CASCADE)
school = models.BooleanField(
default=True, help_text="Demande de l'... | schedule_booking/models.py | from django.db import models
from django.contrib.sites.models import Site
from django.core.validators import MaxValueValidator, MinValueValidator
class Config(models.Model):
site = models.OneToOneField(Site, on_delete=models.CASCADE)
school = models.BooleanField(
default=True, help_text="Demande de l'... | 0.439507 | 0.267496 |
# Third-party modules
import pytest
# NOC modules
from noc.core.hist.base import Histogram
@pytest.mark.parametrize(
"config,sample,expected",
[
# Empty config, all counts to +inf
([], [], [0]),
([], [1], [1]),
([], [1, 2, 3, 4, 5], [5]),
# One threshold, 1ms
... | tests/test_hist.py |
# Third-party modules
import pytest
# NOC modules
from noc.core.hist.base import Histogram
@pytest.mark.parametrize(
"config,sample,expected",
[
# Empty config, all counts to +inf
([], [], [0]),
([], [1], [1]),
([], [1, 2, 3, 4, 5], [5]),
# One threshold, 1ms
... | 0.476336 | 0.746393 |
import pandas as pd
import time
from GridCal.Engine.basic_structures import Logger
from GridCal.Engine.basic_structures import TimeGrouping, get_time_groups
from GridCal.Engine.Core.multi_circuit import MultiCircuit
from GridCal.Engine.basic_structures import SolverType
from GridCal.Engine.Simulations.OPF.opf_driver ... | src/GridCal/Engine/Simulations/OPF/opf_ts_driver.py |
import pandas as pd
import time
from GridCal.Engine.basic_structures import Logger
from GridCal.Engine.basic_structures import TimeGrouping, get_time_groups
from GridCal.Engine.Core.multi_circuit import MultiCircuit
from GridCal.Engine.basic_structures import SolverType
from GridCal.Engine.Simulations.OPF.opf_driver ... | 0.844313 | 0.325681 |
import argparse
from collections import defaultdict
def read_qrels(qrels):
judged_docids = defaultdict(set)
with open(qrels) as f:
for line in f:
cols = line.split()
qid = cols[0]
docid = cols[2]
judged_docids[qid].add(docid)
return judged_docids
d... | src/main/python/trec-covid/remove_judged_docids.py | import argparse
from collections import defaultdict
def read_qrels(qrels):
judged_docids = defaultdict(set)
with open(qrels) as f:
for line in f:
cols = line.split()
qid = cols[0]
docid = cols[2]
judged_docids[qid].add(docid)
return judged_docids
d... | 0.381796 | 0.099252 |
from django.core.management.base import BaseCommand
from .calculate_nps import STATISTICAL_SIGNIFICANCE, SURVEYS, USER_TYPES, COUNT_TYPES, \
nps, calculate_percentages, calculate_client_percentages
from nps.models import ClientAggregations, ProductAggregations, Products
class Command(BaseCommand):
help = 'Run... | nps/management/commands/calculate_nps_product.py | from django.core.management.base import BaseCommand
from .calculate_nps import STATISTICAL_SIGNIFICANCE, SURVEYS, USER_TYPES, COUNT_TYPES, \
nps, calculate_percentages, calculate_client_percentages
from nps.models import ClientAggregations, ProductAggregations, Products
class Command(BaseCommand):
help = 'Run... | 0.236957 | 0.148386 |
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class ApeMenloVnicConsts:
STATE_CREATE_PEND = "CreatePend"
STATE_CREATING = "Creating"
STATE_DESTROY_PEND = "DestroyPend"
STATE_DESTROYING = "Destroying"
STATE_MODIFY_PEND = "Mo... | ucsmsdk/mometa/ape/ApeMenloVnic.py |
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class ApeMenloVnicConsts:
STATE_CREATE_PEND = "CreatePend"
STATE_CREATING = "Creating"
STATE_DESTROY_PEND = "DestroyPend"
STATE_DESTROYING = "Destroying"
STATE_MODIFY_PEND = "Mo... | 0.31732 | 0.182134 |
import unittest
from airflow import DAG, configuration, settings
from airflow.exceptions import AirflowSensorTimeout
from airflow.models import DagRun, TaskInstance
from airflow.operators.dummy_operator import DummyOperator
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils import ... | tests/sensors/test_base_sensor.py |
import unittest
from airflow import DAG, configuration, settings
from airflow.exceptions import AirflowSensorTimeout
from airflow.models import DagRun, TaskInstance
from airflow.operators.dummy_operator import DummyOperator
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils import ... | 0.704364 | 0.359701 |
import random
import time
from app.utils import ymir_viz as m
from tests.utils.utils import random_lower_string
class TestAsset:
def test_create_asset(self, mocker):
asset_id = random_lower_string()
res = {
"annotations": [
{
"box": random_lower_str... | ymir/backend/src/pymir-app/tests/utils/test_viz.py | import random
import time
from app.utils import ymir_viz as m
from tests.utils.utils import random_lower_string
class TestAsset:
def test_create_asset(self, mocker):
asset_id = random_lower_string()
res = {
"annotations": [
{
"box": random_lower_str... | 0.486819 | 0.404802 |
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing p... | tests/screenshot_test.py |
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing p... | 0.81283 | 0.317863 |
import logging
import os
from astropy.io import fits
from logutils import BraceMessage as __
from matplotlib import pyplot as plt
from spectrum_overload import Spectrum
from mingle.utilities.io import get_filenames
def load_spectrum(name):
"""Load in fits file and return as a Spectrum object.
Tries multipl... | mingle/utilities/spectrum_utils.py | import logging
import os
from astropy.io import fits
from logutils import BraceMessage as __
from matplotlib import pyplot as plt
from spectrum_overload import Spectrum
from mingle.utilities.io import get_filenames
def load_spectrum(name):
"""Load in fits file and return as a Spectrum object.
Tries multipl... | 0.782912 | 0.489137 |
from logging import getLogger
from typing import Dict, NewType
from uuid import uuid4
import eventlet
from eventlet.event import Event
from redis.client import StrictRedis, PubSub
from nameko.extensions import DependencyProvider, SharedExtension, ProviderCollector
from nameko.exceptions import deserialize_to_instance
... | nameko_redis/pubsub_response_listener.py | from logging import getLogger
from typing import Dict, NewType
from uuid import uuid4
import eventlet
from eventlet.event import Event
from redis.client import StrictRedis, PubSub
from nameko.extensions import DependencyProvider, SharedExtension, ProviderCollector
from nameko.exceptions import deserialize_to_instance
... | 0.590543 | 0.084947 |
from __future__ import division, print_function
import json
import os
import datetime
from gym import logger
from gym.wrappers import Monitor
from gym.wrappers.monitor import detect_training_manifests, collapse_env_infos, merge_stats_files
from gym.wrappers.monitoring import video_recorder
from gym.wrappers.monitorin... | rl_agents/trainer/monitor.py | from __future__ import division, print_function
import json
import os
import datetime
from gym import logger
from gym.wrappers import Monitor
from gym.wrappers.monitor import detect_training_manifests, collapse_env_infos, merge_stats_files
from gym.wrappers.monitoring import video_recorder
from gym.wrappers.monitorin... | 0.794345 | 0.19544 |
import sys
import time
import argparse
import logging
import threading
import subprocess
from . import rrlogger, __version__
from .constants import *
from .lib import AttemptResults
def run():
parser = _get_parser()
# ---
# version
f = sys.argv.index('--') if '--' in sys.argv else len(sys.argv)
i... | rretry/main.py | import sys
import time
import argparse
import logging
import threading
import subprocess
from . import rrlogger, __version__
from .constants import *
from .lib import AttemptResults
def run():
parser = _get_parser()
# ---
# version
f = sys.argv.index('--') if '--' in sys.argv else len(sys.argv)
i... | 0.234933 | 0.099208 |
import sys
from pathlib import Path
from distutils import dir_util
import json
import argparse
# Add yolov5 folder to path
ROOT = Path(__file__).parent
def train(overwrite: bool = False):
"""Train models based on existing datasets.
Args:
overwrite (bool, optional): overwrite existing files. Default... | train.py | import sys
from pathlib import Path
from distutils import dir_util
import json
import argparse
# Add yolov5 folder to path
ROOT = Path(__file__).parent
def train(overwrite: bool = False):
"""Train models based on existing datasets.
Args:
overwrite (bool, optional): overwrite existing files. Default... | 0.685213 | 0.405037 |
def detector_distance(val, pvname='13IDE:m19.VAL', wait=True):
"""
Set Sample-detector distance in mm.
Args:
val (float): Sample-detector distance in mm.
pvname (string): Epics PV for sample-detector distance ['13IDE:m19.VAL']
wait (True or False): whether to wait for move to com... | doc/macros/instruments.py |
def detector_distance(val, pvname='13IDE:m19.VAL', wait=True):
"""
Set Sample-detector distance in mm.
Args:
val (float): Sample-detector distance in mm.
pvname (string): Epics PV for sample-detector distance ['13IDE:m19.VAL']
wait (True or False): whether to wait for move to com... | 0.711631 | 0.514644 |
import smtplib
import json
import os
import sys
import time
from sqlalchemy import create_engine, Table, MetaData
with open(os.path.join("/usr/local/submitty/config", 'database.json')) as open_file:
OPEN_JSON = json.load(open_file)
EMAIL_USER = OPEN_JSON['email_user']
EMAIL_PASSWORD = OPEN_JSON['<PASSWORD>']
EMA... | sbin/sendEmail.py |
import smtplib
import json
import os
import sys
import time
from sqlalchemy import create_engine, Table, MetaData
with open(os.path.join("/usr/local/submitty/config", 'database.json')) as open_file:
OPEN_JSON = json.load(open_file)
EMAIL_USER = OPEN_JSON['email_user']
EMAIL_PASSWORD = OPEN_JSON['<PASSWORD>']
EMA... | 0.089933 | 0.053552 |
import pandas as pd
from functions import fao_regions as regions
data = 'data/'
def livestock_pom(POM_data, FAO_animals, ls_proxie, diet_div_ls, diet_source_ls, FAO_pop):
FAO_Livestock = pd.read_csv(data+"FAOSTAT_Livestock Production.csv")
FAO_Livestock = FAO_Livestock.dropna(subset = ['Value'])
FAO_Lives... | functions/Livestock_build.py | import pandas as pd
from functions import fao_regions as regions
data = 'data/'
def livestock_pom(POM_data, FAO_animals, ls_proxie, diet_div_ls, diet_source_ls, FAO_pop):
FAO_Livestock = pd.read_csv(data+"FAOSTAT_Livestock Production.csv")
FAO_Livestock = FAO_Livestock.dropna(subset = ['Value'])
FAO_Lives... | 0.159087 | 0.341281 |
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
__NAMESPACE__ = "NISTSchema-SV-IV-list-NMTOKENS-enumeration-3-NS"
class NistschemaSvIvListNmtokensEnumeration3Type(Enum):
IM_D_NIST_NAVAL_APPROPRIATE_AND_THESE_REVOLUTION_MANIPULATE_COMMERCE_APPLICATIONS_TH_AND_TEST_THE_RE... | output/models/nist_data/list_pkg/nmtokens/schema_instance/nistschema_sv_iv_list_nmtokens_enumeration_3_xsd/nistschema_sv_iv_list_nmtokens_enumeration_3.py | from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
__NAMESPACE__ = "NISTSchema-SV-IV-list-NMTOKENS-enumeration-3-NS"
class NistschemaSvIvListNmtokensEnumeration3Type(Enum):
IM_D_NIST_NAVAL_APPROPRIATE_AND_THESE_REVOLUTION_MANIPULATE_COMMERCE_APPLICATIONS_TH_AND_TEST_THE_RE... | 0.656108 | 0.15925 |
from __future__ import absolute_import
import unittest
from ..clipboard import clipboard
class TestObject(object):
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
def __eq__(self, other):
if isinstance(other, TestObject):
ret... | Latest/venv/Lib/site-packages/pyface/tests/test_clipboard.py | from __future__ import absolute_import
import unittest
from ..clipboard import clipboard
class TestObject(object):
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
def __eq__(self, other):
if isinstance(other, TestObject):
ret... | 0.848816 | 0.362151 |
import tensorflow as tf
from ops import conv, lrelu, global_avg_pooling, global_max_pooling, fully_connected
class DiscriminatorSPatch:
"""SPatchGAN discriminator."""
def __init__(self, ch, n_downsample_init, n_scales, n_adapt, n_mix,
logits_type: str, stats: list, sn):
self._ch = ch
... | discriminator/discriminator_spatch.py | import tensorflow as tf
from ops import conv, lrelu, global_avg_pooling, global_max_pooling, fully_connected
class DiscriminatorSPatch:
"""SPatchGAN discriminator."""
def __init__(self, ch, n_downsample_init, n_scales, n_adapt, n_mix,
logits_type: str, stats: list, sn):
self._ch = ch
... | 0.797596 | 0.2194 |
import pprint
import re # noqa: F401
import six
class VulnerabilityOccurrencesSummaryFixableTotalByDigest(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute n... | grafeas/models/vulnerability_occurrences_summary_fixable_total_by_digest.py | import pprint
import re # noqa: F401
import six
class VulnerabilityOccurrencesSummaryFixableTotalByDigest(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute n... | 0.755817 | 0.156459 |
import sys
from webhook.utils.time_tools import utc_to_local
reload(sys)
sys.setdefaultencoding('utf8')
def _do_data(data, url_cate, action, project_name, project_guid, todos_title):
"""
:param data:
:param action:
:param project_name:
:param project_guid:
:param todos_title:
:return:
... | webhook/tower.py | import sys
from webhook.utils.time_tools import utc_to_local
reload(sys)
sys.setdefaultencoding('utf8')
def _do_data(data, url_cate, action, project_name, project_guid, todos_title):
"""
:param data:
:param action:
:param project_name:
:param project_guid:
:param todos_title:
:return:
... | 0.132094 | 0.167491 |
import inspect
from typing import Any, Type
from fastapi import FastAPI, Form
from pydantic import BaseModel
def as_form(cls: Type[BaseModel]) -> Any:
"""Adds an as_form class method to decorated models.
The as_form class method can be used with FastAPI endpoints
"""
new_params = [
inspect.... | mkgui/base/api/fastapi_utils.py |
import inspect
from typing import Any, Type
from fastapi import FastAPI, Form
from pydantic import BaseModel
def as_form(cls: Type[BaseModel]) -> Any:
"""Adds an as_form class method to decorated models.
The as_form class method can be used with FastAPI endpoints
"""
new_params = [
inspect.... | 0.70416 | 0.163479 |
from ._trade_sys import (SelectorBase, SE_Fixed)
from hikyuu.util.unicode import (unicodeFunc, reprFunc)
SelectorBase.__unicode__ = unicodeFunc
SelectorBase.__repr__ = reprFunc
#------------------------------------------------------------------
# add doc-string
#----------------------------------------------------... | tools/hikyuu/trade_sys/selector.py |
from ._trade_sys import (SelectorBase, SE_Fixed)
from hikyuu.util.unicode import (unicodeFunc, reprFunc)
SelectorBase.__unicode__ = unicodeFunc
SelectorBase.__repr__ = reprFunc
#------------------------------------------------------------------
# add doc-string
#----------------------------------------------------... | 0.351422 | 0.117623 |
import logging
import sys
import uuid
from typing import Mapping, Iterator, Optional
import time
import tempfile
import pandas as pd
from google.cloud.storage import Bucket
from google.cloud.storage import Client as GCSClient
from google.cloud.pubsub_v1 import PublisherClient
from thor.main import runTHOROrbit
from ... | thor/taskqueue/client.py | import logging
import sys
import uuid
from typing import Mapping, Iterator, Optional
import time
import tempfile
import pandas as pd
from google.cloud.storage import Bucket
from google.cloud.storage import Client as GCSClient
from google.cloud.pubsub_v1 import PublisherClient
from thor.main import runTHOROrbit
from ... | 0.791982 | 0.180215 |
import argparse
import shlex
import subprocess
import tempfile
import os, sys
import time
import datetime
from pprint import pprint
from fabric.tasks import execute
import uuid
import re
import json
import threading
import socket
import getpass
import logging
import yaml
import sh
import itertools
import shutil
# Impo... | tool/cstar_perf/tool/benchmark.py | import argparse
import shlex
import subprocess
import tempfile
import os, sys
import time
import datetime
from pprint import pprint
from fabric.tasks import execute
import uuid
import re
import json
import threading
import socket
import getpass
import logging
import yaml
import sh
import itertools
import shutil
# Impo... | 0.365683 | 0.086864 |
import pandas as pd
import json
import numpy as np
import ast
from datetime import datetime
import plotly.graph_objs as go
from plotly.offline import plot
import plotly.offline as offline
import plotly.figure_factory as ff
from pandas.core.indexes import interval
import re
# 2021-07-16T19:31:13+08:00
def get_interval_... | 20210720/test.py | import pandas as pd
import json
import numpy as np
import ast
from datetime import datetime
import plotly.graph_objs as go
from plotly.offline import plot
import plotly.offline as offline
import plotly.figure_factory as ff
from pandas.core.indexes import interval
import re
# 2021-07-16T19:31:13+08:00
def get_interval_... | 0.227555 | 0.207656 |
import csv
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.model_selection import train_test_split
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
train_set = pd.read_csv('../data/train.csv')
test_set = pd.read_csv('../data/test.csv')
xs = (train_set.iloc[: ,... | kaggle/Digit_Recognizer/model/dense_net.py | import csv
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.model_selection import train_test_split
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
train_set = pd.read_csv('../data/train.csv')
test_set = pd.read_csv('../data/test.csv')
xs = (train_set.iloc[: ,... | 0.463444 | 0.447038 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
__all__ = ['ProviderArgs', 'Provider']
@pulumi.input_type
class ProviderArgs:
def __init__(__self__, *,
client_id: pulumi.Input[str],
... | sdk/python/pulumi_keycloak/provider.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
__all__ = ['ProviderArgs', 'Provider']
@pulumi.input_type
class ProviderArgs:
def __init__(__self__, *,
client_id: pulumi.Input[str],
... | 0.807461 | 0.06354 |
import logging
import rdflib
L = logging.getLogger(__name__)
__all__ = ["DatatypePropertyMixin",
"ObjectPropertyMixin",
"UnionPropertyMixin"]
class DatatypePropertyMixin(object):
def __init__(self, resolver, **kwargs):
"""
Parameters
----------
resolver : R... | yarom/propertyMixins.py | import logging
import rdflib
L = logging.getLogger(__name__)
__all__ = ["DatatypePropertyMixin",
"ObjectPropertyMixin",
"UnionPropertyMixin"]
class DatatypePropertyMixin(object):
def __init__(self, resolver, **kwargs):
"""
Parameters
----------
resolver : R... | 0.705176 | 0.170094 |
from pathlib import Path
from typing import Protocol, runtime_checkable
from src.core.coral.coral_model import Coral
from src.core.output.output_model import ModelParameters
@runtime_checkable
class OutputProtocol(Protocol):
"""
Protocol defining how an Output model should look like.
"""
@property
... | src/core/output/output_protocol.py | from pathlib import Path
from typing import Protocol, runtime_checkable
from src.core.coral.coral_model import Coral
from src.core.output.output_model import ModelParameters
@runtime_checkable
class OutputProtocol(Protocol):
"""
Protocol defining how an Output model should look like.
"""
@property
... | 0.918503 | 0.57684 |
from typing import List, Tuple
import matplotlib.pyplot as plt
import random
from sys import stderr
from parameters import *
"""
Represents an individual in our population (in our case, a path going through
each city exactly once)
"""
class Individual:
# used to assign an individual id for each individual
... | individual.py | from typing import List, Tuple
import matplotlib.pyplot as plt
import random
from sys import stderr
from parameters import *
"""
Represents an individual in our population (in our case, a path going through
each city exactly once)
"""
class Individual:
# used to assign an individual id for each individual
... | 0.699665 | 0.600716 |
import string
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib
from .FigureCommon import Igs, FcgRidx, texRename, texRenameList, FcgRidxL, FcgRlist, FcgRlistL
def makeFigure():
from ..StoneHelper import read_chain, getFitMeasMergedSummarized
from .FigureCommon import getSetup, Le... | recepmod/figures/Figure2.py | import string
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib
from .FigureCommon import Igs, FcgRidx, texRename, texRenameList, FcgRidxL, FcgRlist, FcgRlistL
def makeFigure():
from ..StoneHelper import read_chain, getFitMeasMergedSummarized
from .FigureCommon import getSetup, Le... | 0.752468 | 0.372676 |
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import permissions
from apps.permissions import has_owner_access, check_has_shipment_owner_access, shipment_exists, check_permission_link
from .models import PermissionLink
class IsShipmentOwner(permissions.BasePermission):
"""
Custom ... | apps/shipments/permissions.py | from django.core.exceptions import ObjectDoesNotExist
from rest_framework import permissions
from apps.permissions import has_owner_access, check_has_shipment_owner_access, shipment_exists, check_permission_link
from .models import PermissionLink
class IsShipmentOwner(permissions.BasePermission):
"""
Custom ... | 0.599954 | 0.111531 |
def add_project_node(tx, github_short_url):
tx.run("MERGE (p:Project {{id: '{}'}});".format(github_short_url))
def add_project_depends_project_edge(tx, github_short_url, parent_github_short_url):
tx.run("MATCH (d:Project {{id: '{}'}}), (p:Project {{id: '{}'}}) MERGE (d)-[:Depends]->(p);".format(
githu... | pom-parsing-queue/src/neo4j_queries.py | def add_project_node(tx, github_short_url):
tx.run("MERGE (p:Project {{id: '{}'}});".format(github_short_url))
def add_project_depends_project_edge(tx, github_short_url, parent_github_short_url):
tx.run("MATCH (d:Project {{id: '{}'}}), (p:Project {{id: '{}'}}) MERGE (d)-[:Depends]->(p);".format(
githu... | 0.504394 | 0.132908 |
import json
from pprint import pprint
from itertools import combinations
from gensim.models import TfidfModel
from gensim.corpora import Dictionary
from nltk import ngrams
from scipy.spatial.distance import cosine
from sklearn.cluster import DBSCAN
import numpy as np
from settings import *
def preprocess_blob(blob):
... | ml_pipeline/clustering.py | import json
from pprint import pprint
from itertools import combinations
from gensim.models import TfidfModel
from gensim.corpora import Dictionary
from nltk import ngrams
from scipy.spatial.distance import cosine
from sklearn.cluster import DBSCAN
import numpy as np
from settings import *
def preprocess_blob(blob):
... | 0.61451 | 0.250225 |
import numpy as np
import json
import sys
import os
from subprocess import call
from config import *
import pdb
usage = 'process_remesh.py [model-cat]_[model-id]_[list-of-parts]'
def load_obj(fn):
fin = open(fn, 'r')
lines = [line.rstrip() for line in fin]
fin.close()
vertices = []; faces = [];
fo... | server/python/process_remesh.py | import numpy as np
import json
import sys
import os
from subprocess import call
from config import *
import pdb
usage = 'process_remesh.py [model-cat]_[model-id]_[list-of-parts]'
def load_obj(fn):
fin = open(fn, 'r')
lines = [line.rstrip() for line in fin]
fin.close()
vertices = []; faces = [];
fo... | 0.176885 | 0.11221 |
import io
import urllib.request
import urllib.parse
import json
import csv
import subprocess
import sys
import platform
import getopt
import re
import shutil
all_flag = False
download_flag = False
filename = None
offcore_events = []
core_events = []
try:
opts, args = getopt.getopt(sys.argv[1:], "a,f:,d", ["all", ... | pmu-query.py | import io
import urllib.request
import urllib.parse
import json
import csv
import subprocess
import sys
import platform
import getopt
import re
import shutil
all_flag = False
download_flag = False
filename = None
offcore_events = []
core_events = []
try:
opts, args = getopt.getopt(sys.argv[1:], "a,f:,d", ["all", ... | 0.07618 | 0.076926 |
import os
from shutil import copyfile
import nibabel as nib
import numpy as np
import pytest
from nilearn.image import resample_img
import nimare
from nimare.tests.utils import get_test_data_path
from nimare.utils import get_resource_path
# Only enable the following once in a while for a check for SettingWithCopyWar... | nimare/tests/conftest.py | import os
from shutil import copyfile
import nibabel as nib
import numpy as np
import pytest
from nilearn.image import resample_img
import nimare
from nimare.tests.utils import get_test_data_path
from nimare.utils import get_resource_path
# Only enable the following once in a while for a check for SettingWithCopyWar... | 0.611266 | 0.311453 |
import sdf
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
mpl.style.use('seaborn-talk')
mpl.rcParams['font.size'] = 24
# plt.rcParams['font.family'] = 'sans-serif'
# plt.rcParams['font.sans-serif'] = 'Tahoma'
# # plt.rcParams['font.monospace'] = 'Ubuntu Mono'
# plt.rcParams['font.size'] = ... | py3/PartSpec.py | import sdf
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
mpl.style.use('seaborn-talk')
mpl.rcParams['font.size'] = 24
# plt.rcParams['font.family'] = 'sans-serif'
# plt.rcParams['font.sans-serif'] = 'Tahoma'
# # plt.rcParams['font.monospace'] = 'Ubuntu Mono'
# plt.rcParams['font.size'] = ... | 0.207777 | 0.53358 |
import requests
import pickle
def get_data(year):
# Set up API Call Variables
game_data = []
season_type = '02' #regular season
max_game_ID = 1300 #game events in the year
# Loop over the counder and format the API call
for i in range(0,max_game_ID):
pk = str(year+season_type+str(i)... | get_hockey.py | import requests
import pickle
def get_data(year):
# Set up API Call Variables
game_data = []
season_type = '02' #regular season
max_game_ID = 1300 #game events in the year
# Loop over the counder and format the API call
for i in range(0,max_game_ID):
pk = str(year+season_type+str(i)... | 0.074064 | 0.084871 |
from twisted.internet.defer import inlineCallbacks
from vumi.tests.helpers import VumiTestCase
from vxsandbox.resources.tests.utils import ResourceTestCaseBase
from vxsandbox.resources.metrics import (
MetricEvent, MetricEventError, MetricsResource)
class TestMetricEvent(VumiTestCase):
SUM = MetricEvent.AG... | vxsandbox/resources/tests/test_metrics.py |
from twisted.internet.defer import inlineCallbacks
from vumi.tests.helpers import VumiTestCase
from vxsandbox.resources.tests.utils import ResourceTestCaseBase
from vxsandbox.resources.metrics import (
MetricEvent, MetricEventError, MetricsResource)
class TestMetricEvent(VumiTestCase):
SUM = MetricEvent.AG... | 0.788176 | 0.417093 |
import datetime
import os
import pytest
from dynamorm.exceptions import ValidationError
from dynamorm.model import DynaModel
from dynamorm.indexes import GlobalIndex, ProjectKeys
from dynamorm.relationships import OneToOne, OneToMany, ManyToOne
if "marshmallow" in (os.getenv("SERIALIZATION_PKG") or ""):
from mar... | tests/test_relationships.py | import datetime
import os
import pytest
from dynamorm.exceptions import ValidationError
from dynamorm.model import DynaModel
from dynamorm.indexes import GlobalIndex, ProjectKeys
from dynamorm.relationships import OneToOne, OneToMany, ManyToOne
if "marshmallow" in (os.getenv("SERIALIZATION_PKG") or ""):
from mar... | 0.58818 | 0.394901 |
import choice.quest_guid as quest_guid
import choice.result as result
import choice.responses as responses
from choice.utils import has_flag, get_plot
def mages_dead(data):
circle_data = get_plot(data, quest_guid.BROKEN_CIRCLE)
return has_flag(circle_data, cullen.MAGES_DEAD_FLAG)
def wynne_killed(data):
quest_data... | choice/circle.py | import choice.quest_guid as quest_guid
import choice.result as result
import choice.responses as responses
from choice.utils import has_flag, get_plot
def mages_dead(data):
circle_data = get_plot(data, quest_guid.BROKEN_CIRCLE)
return has_flag(circle_data, cullen.MAGES_DEAD_FLAG)
def wynne_killed(data):
quest_data... | 0.302803 | 0.116714 |
import arrow
from libweasyl import staff
from weasyl import define as d
from weasyl import ignoreuser
from weasyl import macro as m
from weasyl import media
from weasyl import welcome
from weasyl.error import WeasylError
_MAX_LEVEL = 8
_PER_LEVEL = 50
def _thread(query, result, i):
parent = result[-1]
fo... | weasyl/comment.py |
import arrow
from libweasyl import staff
from weasyl import define as d
from weasyl import ignoreuser
from weasyl import macro as m
from weasyl import media
from weasyl import welcome
from weasyl.error import WeasylError
_MAX_LEVEL = 8
_PER_LEVEL = 50
def _thread(query, result, i):
parent = result[-1]
fo... | 0.18743 | 0.157947 |
import string
import random
import time
import datetime
from flask import render_template, redirect, url_for, request, session, Flask
from functools import wraps
from exts import db
from config import Config
from models import User, Note
from forms import CreateNoteForm
app = Flask(__name__)
app.config.from_object(Con... | web-oh-my-note/docker/source/app/app.py | import string
import random
import time
import datetime
from flask import render_template, redirect, url_for, request, session, Flask
from functools import wraps
from exts import db
from config import Config
from models import User, Note
from forms import CreateNoteForm
app = Flask(__name__)
app.config.from_object(Con... | 0.255529 | 0.086864 |
# In[ ]:
# Importing the libraries
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.preprocessing import StandardScaler
from matplotlib import pyplot as plt
import seaborn as sns
import warnin... | downloaded_kernels/house_sales/parsed_kernels/kernel_64.py |
# In[ ]:
# Importing the libraries
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.preprocessing import StandardScaler
from matplotlib import pyplot as plt
import seaborn as sns
import warnin... | 0.842215 | 0.610744 |
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import six
import numpy as np
from lspopt.data import C, WEIGHTS
def lspopt_ref(n, c_parameter=20.0):
"""Reference implementation of the multitaper window calculat... | tests/lspopt_ref.py | from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import six
import numpy as np
from lspopt.data import C, WEIGHTS
def lspopt_ref(n, c_parameter=20.0):
"""Reference implementation of the multitaper window calculat... | 0.908914 | 0.4133 |
import numpy as np
import pytest
from packaging.version import parse as parse_version
pytestmark = pytest.mark.gpu
import dask.array as da
from dask.array.utils import assert_eq, same_keys
cupy = pytest.importorskip("cupy")
cupy_version = parse_version(cupy.__version__)
def test_overlap_internal():
x = cupy.ar... | dask/array/tests/test_cupy_overlap.py | import numpy as np
import pytest
from packaging.version import parse as parse_version
pytestmark = pytest.mark.gpu
import dask.array as da
from dask.array.utils import assert_eq, same_keys
cupy = pytest.importorskip("cupy")
cupy_version = parse_version(cupy.__version__)
def test_overlap_internal():
x = cupy.ar... | 0.680242 | 0.728084 |
import calendar
from calendar import TextCalendar
import time
# print(calendar.month(2018, 11))
class CalStr(TextCalendar):
def __init__(self, start_year, start_month, end_year, end_month):
super(CalStr, self).__init__()
self.start_year = start_year
self.start_month = start_month
... | cal_diy.py | import calendar
from calendar import TextCalendar
import time
# print(calendar.month(2018, 11))
class CalStr(TextCalendar):
def __init__(self, start_year, start_month, end_year, end_month):
super(CalStr, self).__init__()
self.start_year = start_year
self.start_month = start_month
... | 0.146179 | 0.185578 |
import os
import posixpath
import shutil
from unittest import mock
import pytest
from dvc.data.stage import stage
from dvc.fs.repo import RepoFileSystem
from dvc.hash_info import HashInfo
from tests.utils import clean_staging
def test_exists(tmp_dir, dvc):
tmp_dir.gen("foo", "foo")
dvc.add("foo")
(tmp_d... | tests/unit/fs/test_repo.py | import os
import posixpath
import shutil
from unittest import mock
import pytest
from dvc.data.stage import stage
from dvc.fs.repo import RepoFileSystem
from dvc.hash_info import HashInfo
from tests.utils import clean_staging
def test_exists(tmp_dir, dvc):
tmp_dir.gen("foo", "foo")
dvc.add("foo")
(tmp_d... | 0.370909 | 0.26815 |
import os
from collections import Counter
from multiprocessing import Pool
from . import util
from . import multi_processing
class WordPairsProcessing(object):
def __init__(self, max_vocab_size, min_count, window_size, dicts_folder, edges_folder, graph_folder,
safe_files_number_per_processor):
... | corpus2graph/wordpair_processing.py | import os
from collections import Counter
from multiprocessing import Pool
from . import util
from . import multi_processing
class WordPairsProcessing(object):
def __init__(self, max_vocab_size, min_count, window_size, dicts_folder, edges_folder, graph_folder,
safe_files_number_per_processor):
... | 0.273477 | 0.159971 |