code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from datetime import datetime, timedelta
from django.core.exceptions import ObjectDoesNotExist
from django.core.paginator import EmptyPage
from django.http import JsonResponse
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import AllowAny
from common.models import Sign
from mmapi.ser... | mmapi/views/sign.py | from datetime import datetime, timedelta
from django.core.exceptions import ObjectDoesNotExist
from django.core.paginator import EmptyPage
from django.http import JsonResponse
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import AllowAny
from common.models import Sign
from mmapi.ser... | 0.268462 | 0.143427 |
import threading
from contextlib import contextmanager
from geobox.model.tasks import Task
from geobox.utils import join_threads
import logging
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
class ProcessThread(threading.Thread):
def __init__(self, app_state, task_class_mapping, tas... | app/geobox/process/base.py |
import threading
from contextlib import contextmanager
from geobox.model.tasks import Task
from geobox.utils import join_threads
import logging
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
class ProcessThread(threading.Thread):
def __init__(self, app_state, task_class_mapping, tas... | 0.375592 | 0.146423 |
import signature_dispatch as sd, pytest
from typing import List, Callable
@pytest.fixture(autouse=True, params=[False, True])
def currentframe(request, monkeypatch):
# Not all python implementations support `inspect.currentframe()`, so run
# every test with and without it.
if request.param:
impor... | tests/test_dispatch.py |
import signature_dispatch as sd, pytest
from typing import List, Callable
@pytest.fixture(autouse=True, params=[False, True])
def currentframe(request, monkeypatch):
# Not all python implementations support `inspect.currentframe()`, so run
# every test with and without it.
if request.param:
impor... | 0.891899 | 0.734572 |
from BTrees.OOBTree import OOBTree # pylint: disable=import-error
from persistent.list import PersistentList
from pyramid.threadlocal import get_current_registry
from zope.container.interfaces import IContained, IContainer
from zope.container.ordered import OrderedContainer
from zope.lifecycleevent.interfaces import I... | src/pyams_utils/container.py | from BTrees.OOBTree import OOBTree # pylint: disable=import-error
from persistent.list import PersistentList
from pyramid.threadlocal import get_current_registry
from zope.container.interfaces import IContained, IContainer
from zope.container.ordered import OrderedContainer
from zope.lifecycleevent.interfaces import I... | 0.768125 | 0.187728 |
import probe_config as conf
import socket
import re
import os
import tempfile
import shutil
class Swift:
def __init__(self, myname, is_storage):
self.myname = myname
print "Myname = " + self.myname
self.allnodes = conf.swift_nodes
print "all nodes=" + str(self.allnodes)
self.all_ips = [socket.gethostbyname... | server/scripts/probe/swift.py |
import probe_config as conf
import socket
import re
import os
import tempfile
import shutil
class Swift:
def __init__(self, myname, is_storage):
self.myname = myname
print "Myname = " + self.myname
self.allnodes = conf.swift_nodes
print "all nodes=" + str(self.allnodes)
self.all_ips = [socket.gethostbyname... | 0.122143 | 0.069795 |
import subprocess
def run():
subprocess.call(["python", "incremental_learning.py",
"--train_data_path", "../data/slovenian/slo_train_binarized.tsv",
"--test_data_path", "../data/slovenian/slo_internal_test_binarized.tsv",
"--eval_data_path", "../data/s... | src/start_script_shebert2.py | import subprocess
def run():
subprocess.call(["python", "incremental_learning.py",
"--train_data_path", "../data/slovenian/slo_train_binarized.tsv",
"--test_data_path", "../data/slovenian/slo_internal_test_binarized.tsv",
"--eval_data_path", "../data/s... | 0.3295 | 0.135289 |
import json
import pickle
import numpy as np
import pytest
from mockredis import MockRedis
from .conftest import models
from cf_predict import __version__
from cf_predict.resources import get_db
from cf_predict.errors import NoPredictMethod
@pytest.mark.usefixtures("client_class")
class TestCf_predict:
def test... | cf_predict/test/test_cf_predict.py | import json
import pickle
import numpy as np
import pytest
from mockredis import MockRedis
from .conftest import models
from cf_predict import __version__
from cf_predict.resources import get_db
from cf_predict.errors import NoPredictMethod
@pytest.mark.usefixtures("client_class")
class TestCf_predict:
def test... | 0.584271 | 0.32342 |
from pathlib import Path
import diplib as dip
import numpy as np
import os
import pandas as pd
def GaussianSmoothing(x, sigma, mask=None):
""" Compute n-dimentional gaussian smoothing on nd array.
Parameters
----------
x : numpy nd-array
The imput array to be smoothed
sigma : float
... | pvtseg/features_3d.py | from pathlib import Path
import diplib as dip
import numpy as np
import os
import pandas as pd
def GaussianSmoothing(x, sigma, mask=None):
""" Compute n-dimentional gaussian smoothing on nd array.
Parameters
----------
x : numpy nd-array
The imput array to be smoothed
sigma : float
... | 0.898805 | 0.739281 |
from __future__ import print_function
import numpy as np
from paddle.io import IterableDataset
import cv2
import os
class RecDataset(IterableDataset):
def __init__(self, file_list, config):
super(RecDataset, self).__init__()
self.file_list = file_list
self.config = config
self.n_w... | models/multitask/maml/omniglot_reader.py |
from __future__ import print_function
import numpy as np
from paddle.io import IterableDataset
import cv2
import os
class RecDataset(IterableDataset):
def __init__(self, file_list, config):
super(RecDataset, self).__init__()
self.file_list = file_list
self.config = config
self.n_w... | 0.295738 | 0.132374 |
from typing import TYPE_CHECKING, Dict
import anyio.abc
from .component import Component
if TYPE_CHECKING:
from ..base import ComponentInteraction
__all__ = ('ComponentHandler',)
class ComponentHandler:
"""Handler for components, dispatching waiting components.
Attributes:
components:
... | library/wumpy-interactions/wumpy/interactions/components/handler.py | from typing import TYPE_CHECKING, Dict
import anyio.abc
from .component import Component
if TYPE_CHECKING:
from ..base import ComponentInteraction
__all__ = ('ComponentHandler',)
class ComponentHandler:
"""Handler for components, dispatching waiting components.
Attributes:
components:
... | 0.889852 | 0.199503 |
from msrest.serialization import Model
class Model(Model):
"""An Azure Machine Learning Model.
:param id: The Model Id.
:type id: str
:param name: The Model name.
:type name: str
:param framework: The Model framework.
:type framework: str
:param framework_version: The Mo... | venv/lib/python3.8/site-packages/azureml/_restclient/models/model.py |
from msrest.serialization import Model
class Model(Model):
"""An Azure Machine Learning Model.
:param id: The Model Id.
:type id: str
:param name: The Model name.
:type name: str
:param framework: The Model framework.
:type framework: str
:param framework_version: The Mo... | 0.827271 | 0.484868 |
import abc
import configparser
import datetime
import logging
from typing import Any, Dict, Union
import requests_cache
from ..consts import CACHE_PATH, CONFIG, USE_CACHE
LOGGER = logging.getLogger(__name__)
class AbstractProvider(abc.ABC):
"""
Abstract class to indicate what other providers should provide... | mtgjson5/providers/abstract.py | import abc
import configparser
import datetime
import logging
from typing import Any, Dict, Union
import requests_cache
from ..consts import CACHE_PATH, CONFIG, USE_CACHE
LOGGER = logging.getLogger(__name__)
class AbstractProvider(abc.ABC):
"""
Abstract class to indicate what other providers should provide... | 0.773901 | 0.126812 |
from os.path import abspath, basename, join, dirname
from seisflows.tools import unix
from seisflows.tools.code import call, findpath, saveobj
from seisflows.tools.config import ParameterError, custom_import, \
SeisflowsParameters, SeisflowsPaths
PAR = SeisflowsParameters()
PATH = SeisflowsPaths()
class pbs_sm(... | seisflows/system/pbs_sm.py | from os.path import abspath, basename, join, dirname
from seisflows.tools import unix
from seisflows.tools.code import call, findpath, saveobj
from seisflows.tools.config import ParameterError, custom_import, \
SeisflowsParameters, SeisflowsPaths
PAR = SeisflowsParameters()
PATH = SeisflowsPaths()
class pbs_sm(... | 0.383641 | 0.182808 |
from devsetgo_lib.file_functions import save_json
from starlette.testclient import TestClient
from src.core.gen_user import user_test_info
from src.main import app
client = TestClient(app)
directory_to__files: str = "data"
def test_users_post_error(bearer_session):
test_password = "<PASSWORD>"
user_name = ... | src/tests/test_api_1_users/test_users_create.py |
from devsetgo_lib.file_functions import save_json
from starlette.testclient import TestClient
from src.core.gen_user import user_test_info
from src.main import app
client = TestClient(app)
directory_to__files: str = "data"
def test_users_post_error(bearer_session):
test_password = "<PASSWORD>"
user_name = ... | 0.383872 | 0.285248 |
import numpy as np
from pupil.models.clustering import FaissKMeansClustering
class RepresentativeSampler:
"""
Cluster your training data and your unlabeled data independently,
identify the clusters that are most representative of your
unlabeled data, and oversample from them.
This approach gives y... | pupil/sampling/representative.py | import numpy as np
from pupil.models.clustering import FaissKMeansClustering
class RepresentativeSampler:
"""
Cluster your training data and your unlabeled data independently,
identify the clusters that are most representative of your
unlabeled data, and oversample from them.
This approach gives y... | 0.816113 | 0.596991 |
import os
if False:
from shotgun_api3_registry import connect
sg = connect(use_cache=False)
else:
from tests import Shotgun
url = 'http://127.0.0.1:8010'
sg = Shotgun(url,
os.environ.get('SGCACHE_SHOTGUN_SCRIPT_name', 'script_name'),
os.environ.get('SGCACHE_SHOTGUN_API_KEY', 'api_k... | sandbox/multi_entities.py |
import os
if False:
from shotgun_api3_registry import connect
sg = connect(use_cache=False)
else:
from tests import Shotgun
url = 'http://127.0.0.1:8010'
sg = Shotgun(url,
os.environ.get('SGCACHE_SHOTGUN_SCRIPT_name', 'script_name'),
os.environ.get('SGCACHE_SHOTGUN_API_KEY', 'api_k... | 0.30013 | 0.134691 |
import re
import pytest
import responses
from quickbuild import AsyncQBClient
TOKEN_XML = r"""<?xml version="1.0" encoding="UTF-8"?>
<list>
<com.pmease.quickbuild.model.Token>
<id>120204</id>
<value>84858611-a1fe-4f88-a49c-f600cf0ecf11</value>
<ip>192.168.1.100</ip>
<port>8811</port>
<test>fal... | tests/test_tokens.py | import re
import pytest
import responses
from quickbuild import AsyncQBClient
TOKEN_XML = r"""<?xml version="1.0" encoding="UTF-8"?>
<list>
<com.pmease.quickbuild.model.Token>
<id>120204</id>
<value>84858611-a1fe-4f88-a49c-f600cf0ecf11</value>
<ip>192.168.1.100</ip>
<port>8811</port>
<test>fal... | 0.343672 | 0.222838 |
import pytest
import ngraph as ng
from ngraph.op_graph.comm_nodes import RecvOp, ScatterRecvOp, GatherRecvOp
from ngraph.op_graph.comm_nodes import SendOp, ScatterSendOp, GatherSendOp
from ngraph.testing.hetr_utils import create_send_recv_graph, create_scatter_gather_graph
from ngraph.transformers.hetr.hetr_utils impo... | tests/hetr_tests/test_hetr_utils.py | import pytest
import ngraph as ng
from ngraph.op_graph.comm_nodes import RecvOp, ScatterRecvOp, GatherRecvOp
from ngraph.op_graph.comm_nodes import SendOp, ScatterSendOp, GatherSendOp
from ngraph.testing.hetr_utils import create_send_recv_graph, create_scatter_gather_graph
from ngraph.transformers.hetr.hetr_utils impo... | 0.599368 | 0.443721 |
from PyQt6 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(468, 304)
self.logo = QtWidgets.QLabel(Dialog)
self.logo.setGeometry(QtCore.QRect(10, 10, 171, 281))
self.logo.setCursor(QtGui.QCurs... | UpdateManagerUI.py |
from PyQt6 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(468, 304)
self.logo = QtWidgets.QLabel(Dialog)
self.logo.setGeometry(QtCore.QRect(10, 10, 171, 281))
self.logo.setCursor(QtGui.QCurs... | 0.446253 | 0.070848 |
import json
import os
import time
from datetime import datetime
import cherrypy
from . import pdp_client
from .config import Config
from .deploy_handler import DeployHandler, PolicyUpdateMessage
from .onap.audit import Audit, AuditHttpCode
from .policy_receiver import PolicyReceiver
from .utils import Utils
class P... | policyhandler/web_server.py | import json
import os
import time
from datetime import datetime
import cherrypy
from . import pdp_client
from .config import Config
from .deploy_handler import DeployHandler, PolicyUpdateMessage
from .onap.audit import Audit, AuditHttpCode
from .policy_receiver import PolicyReceiver
from .utils import Utils
class P... | 0.474388 | 0.094929 |
from torch import nn, Tensor, Size
from typing import Optional, Union, List
import torch
from . import register_norm_fn
@register_norm_fn(name="layer_norm")
class LayerNorm(nn.LayerNorm):
"""
Applies `Layer Normalization <https://arxiv.org/abs/1607.06450>`_ over a input tensor
Args:
normalized_... | cvnets/layers/normalization/layer_norm.py |
from torch import nn, Tensor, Size
from typing import Optional, Union, List
import torch
from . import register_norm_fn
@register_norm_fn(name="layer_norm")
class LayerNorm(nn.LayerNorm):
"""
Applies `Layer Normalization <https://arxiv.org/abs/1607.06450>`_ over a input tensor
Args:
normalized_... | 0.97553 | 0.803367 |
import numpy as np
from pysgpp import HashGridPoint
from pysgpp.extensions.datadriven.uq.operations import createGrid, getBasis
from pysgpp.extensions.datadriven.uq.quadrature.linearform.LinearGaussQuadratureStrategy import LinearGaussQuadratureStrategy
from pysgpp.extensions.datadriven.uq.quadrature import getIntegra... | lib/pysgpp/extensions/datadriven/uq/quadrature/marginalization/marginalization.py | import numpy as np
from pysgpp import HashGridPoint
from pysgpp.extensions.datadriven.uq.operations import createGrid, getBasis
from pysgpp.extensions.datadriven.uq.quadrature.linearform.LinearGaussQuadratureStrategy import LinearGaussQuadratureStrategy
from pysgpp.extensions.datadriven.uq.quadrature import getIntegra... | 0.609175 | 0.619615 |
# Import TensorFlow and other library
import tensorflow as tf
import numpy as np
import os
import time
# Download the Shakespeare dataset
path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'https://storage.googleapis.com/download.tensorflow.org'
'/data/... | Experts_tutorial/Text/text_generation.py | # Import TensorFlow and other library
import tensorflow as tf
import numpy as np
import os
import time
# Download the Shakespeare dataset
path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'https://storage.googleapis.com/download.tensorflow.org'
'/data/... | 0.863794 | 0.696449 |
from django.urls import path
from userextensions import views
from userextensions.views import ajax
from userextensions.views import action
app_name = 'userextensions'
urlpatterns = [
# list views
path('list_recents/', views.ListRecents.as_view(), name='list_recents'),
path('list_favorites/', views.ListF... | userextensions/urls.py | from django.urls import path
from userextensions import views
from userextensions.views import ajax
from userextensions.views import action
app_name = 'userextensions'
urlpatterns = [
# list views
path('list_recents/', views.ListRecents.as_view(), name='list_recents'),
path('list_favorites/', views.ListF... | 0.293404 | 0.060502 |
__all__ = ('ClipboardAndroid', )
from kivy.core.clipboard import ClipboardBase
from kivy.clock import Clock
from jnius import autoclass, cast
from android.runnable import run_on_ui_thread
AndroidString = autoclass('java.lang.String')
PythonActivity = autoclass('org.renpy.android.PythonActivity')
Context = autoclass('... | kivy/core/clipboard/clipboard_android.py | __all__ = ('ClipboardAndroid', )
from kivy.core.clipboard import ClipboardBase
from kivy.clock import Clock
from jnius import autoclass, cast
from android.runnable import run_on_ui_thread
AndroidString = autoclass('java.lang.String')
PythonActivity = autoclass('org.renpy.android.PythonActivity')
Context = autoclass('... | 0.540439 | 0.10942 |
from yoti_python_sdk.doc_scan.constants import SUPPLEMENTARY_DOCUMENT
from yoti_python_sdk.utils import remove_null_values
from .required_document import RequiredDocument
class RequiredSupplementaryDocument(RequiredDocument):
def __init__(self, objective, document_types=None, country_codes=None):
"""
... | yoti_python_sdk/doc_scan/session/create/filter/required_supplementary_document.py | from yoti_python_sdk.doc_scan.constants import SUPPLEMENTARY_DOCUMENT
from yoti_python_sdk.utils import remove_null_values
from .required_document import RequiredDocument
class RequiredSupplementaryDocument(RequiredDocument):
def __init__(self, objective, document_types=None, country_codes=None):
"""
... | 0.830181 | 0.324222 |
import os
import copy
from box import Box
from kopf.structs.diffs import diff
import digi.util as util
from digi.util import deep_set
class ModelView:
"""
Return all models in the current world/root view
keyed by the namespaced name; if the nsn starts
with default, it will be trimmed off; the origina... | runtime/driver/digi/view.py | import os
import copy
from box import Box
from kopf.structs.diffs import diff
import digi.util as util
from digi.util import deep_set
class ModelView:
"""
Return all models in the current world/root view
keyed by the namespaced name; if the nsn starts
with default, it will be trimmed off; the origina... | 0.595022 | 0.264706 |
# pylint: disable=missing-docstring
import asyncio
import logging
import socket
import aiohttp
import async_timeout
from pycfdns.const import GET_EXT_IP_URL, NAME
from pycfdns.exceptions import (
CloudflareAuthenticationException,
CloudflareConnectionException,
CloudflareException,
)
_LOGGER = logging.get... | pycfdns/models.py | # pylint: disable=missing-docstring
import asyncio
import logging
import socket
import aiohttp
import async_timeout
from pycfdns.const import GET_EXT_IP_URL, NAME
from pycfdns.exceptions import (
CloudflareAuthenticationException,
CloudflareConnectionException,
CloudflareException,
)
_LOGGER = logging.get... | 0.719482 | 0.108425 |
import base64
import numpy as np
import io
from PIL import Image
import pandas as pd
from keras.models import load_model
from flask import request
from flask import jsonify
from flask import Flask
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import tensorflow as tf
import pymysql... | predict.py | import base64
import numpy as np
import io
from PIL import Image
import pandas as pd
from keras.models import load_model
from flask import request
from flask import jsonify
from flask import Flask
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import tensorflow as tf
import pymysql... | 0.199659 | 0.09401 |
import carla
import math
import numpy as np
from collections import deque
from agents.tools.misc import get_speed
import time
class VehiclePIDController:
"""
VehiclePIDController is the combination of two PID controllers (lateral and longitudinal)
"""
def __init__(self, vehicle, args_lateral=None, ... | agents/navigation/pid_controller.py |
import carla
import math
import numpy as np
from collections import deque
from agents.tools.misc import get_speed
import time
class VehiclePIDController:
"""
VehiclePIDController is the combination of two PID controllers (lateral and longitudinal)
"""
def __init__(self, vehicle, args_lateral=None, ... | 0.741955 | 0.345975 |
import torch.nn as nn
import dgl
from net.blocks import MLPReadout
from net.layer import GraphTransformerLayer
class GraphTransformerNet(nn.Module):
def __init__(self, net_params):
super().__init__()
num_atom_features = net_params['num_atom_features']
num_edge_input_dim = net_params['num_... | net/model.py | import torch.nn as nn
import dgl
from net.blocks import MLPReadout
from net.layer import GraphTransformerLayer
class GraphTransformerNet(nn.Module):
def __init__(self, net_params):
super().__init__()
num_atom_features = net_params['num_atom_features']
num_edge_input_dim = net_params['num_... | 0.925949 | 0.303833 |
import dataclasses
import os
from typing import Any, Dict, Optional
import yahp as hp
from composer.utils.libcloud_object_store import LibcloudObjectStore
@dataclasses.dataclass
class LibcloudObjectStoreHparams(hp.Hparams):
""":class:`~.LibcloudObjectStore` hyperparameters.
.. rubric:: Example
Here's ... | composer/utils/libcloud_object_store_hparams.py | import dataclasses
import os
from typing import Any, Dict, Optional
import yahp as hp
from composer.utils.libcloud_object_store import LibcloudObjectStore
@dataclasses.dataclass
class LibcloudObjectStoreHparams(hp.Hparams):
""":class:`~.LibcloudObjectStore` hyperparameters.
.. rubric:: Example
Here's ... | 0.808672 | 0.171408 |
from rest_framework import serializers
from website.models import Monster, MonsterBase, MonsterFamily, Rune, RuneSet, Artifact, SiegeRecord, DungeonRun
class RuneFullSerializer(serializers.ModelSerializer):
quality = serializers.CharField(source='get_quality_display')
quality_original = serializers.CharField(... | swstats_web/serializers.py | from rest_framework import serializers
from website.models import Monster, MonsterBase, MonsterFamily, Rune, RuneSet, Artifact, SiegeRecord, DungeonRun
class RuneFullSerializer(serializers.ModelSerializer):
quality = serializers.CharField(source='get_quality_display')
quality_original = serializers.CharField(... | 0.711732 | 0.11088 |
import discord
from discord.ext import commands
from src.file_verification import file_verification
# Le token de votre Bot Discord:
token = "TOKEN"
# Les mots bannis dans les fichiers envoyés, par défaut 'token':
key = "token"
# Fichiers autorisés, laisser vide pour enlever la restriction:
authoriz... | File Verification/keter.py |
import discord
from discord.ext import commands
from src.file_verification import file_verification
# Le token de votre Bot Discord:
token = "TOKEN"
# Les mots bannis dans les fichiers envoyés, par défaut 'token':
key = "token"
# Fichiers autorisés, laisser vide pour enlever la restriction:
authoriz... | 0.23292 | 0.202621 |
import os
import re
import sys
from lxml import etree
from skilletlib import Panoply
from skilletlib.exceptions import LoginException
from skilletlib.exceptions import SkilletLoaderException
config_source = os.environ.get("skillet_source", "offline")
if config_source == "offline":
# grab our two configs from the... | generate_skillet_preview.py | import os
import re
import sys
from lxml import etree
from skilletlib import Panoply
from skilletlib.exceptions import LoginException
from skilletlib.exceptions import SkilletLoaderException
config_source = os.environ.get("skillet_source", "offline")
if config_source == "offline":
# grab our two configs from the... | 0.120322 | 0.088112 |
from Compartilhados.utilitarios import utilitarios
from Compartilhados.Excecoes.valoresInvalidosException import ValoresInvalidosException
from Servicos.UsuariosServico import UsuariosServico
class UsuariosControlador:
def __init__(self):
self.usuariosServico = UsuariosServico()
def createUsuario(sel... | Controladores/UsuariosControlador.py | from Compartilhados.utilitarios import utilitarios
from Compartilhados.Excecoes.valoresInvalidosException import ValoresInvalidosException
from Servicos.UsuariosServico import UsuariosServico
class UsuariosControlador:
def __init__(self):
self.usuariosServico = UsuariosServico()
def createUsuario(sel... | 0.40028 | 0.153899 |
import torch
import pdb
import torch.nn.functional as F
def mse_loss(input, target, mask=None, needSigmoid=True):
if needSigmoid:
input = torch.sigmoid(input)
if mask is not None:
input = input * mask
#target = target * mask
loss = F.mse_loss(input, target)
return loss
... | python/util/loss.py | import torch
import pdb
import torch.nn.functional as F
def mse_loss(input, target, mask=None, needSigmoid=True):
if needSigmoid:
input = torch.sigmoid(input)
if mask is not None:
input = input * mask
#target = target * mask
loss = F.mse_loss(input, target)
return loss
... | 0.66061 | 0.506897 |
import json
import os
from Utils.WorkspaceAdminUtils import WorkspaceAdminUtils
class MiscIndexer:
def __init__(self, config):
self.ws = WorkspaceAdminUtils(config)
self.schema_dir = config['schema-dir']
def _tf(self, val):
if val == 0:
return False
else:
... | lib/Utils/MiscIndexer.py | import json
import os
from Utils.WorkspaceAdminUtils import WorkspaceAdminUtils
class MiscIndexer:
def __init__(self, config):
self.ws = WorkspaceAdminUtils(config)
self.schema_dir = config['schema-dir']
def _tf(self, val):
if val == 0:
return False
else:
... | 0.317109 | 0.121217 |
import uuid
from datetime import datetime
from typing import Any
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship
db: Any = SQLAlchemy()
def save(instance):
db.session.add(instance)
db.session.commit()
def get_verification_email_by_email(email):
return VerificationEmail... | server/models.py | import uuid
from datetime import datetime
from typing import Any
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship
db: Any = SQLAlchemy()
def save(instance):
db.session.add(instance)
db.session.commit()
def get_verification_email_by_email(email):
return VerificationEmail... | 0.439747 | 0.068725 |
from typing import Dict, List
import numpy as np
import torch as th
import torch.distributions as td
from rls.algorithms.base.sarl_on_policy import SarlOnPolicy
from rls.common.data import Data
from rls.common.decorator import iton
from rls.nn.models import (ActorCriticValueCts, ActorCriticValueDct, ActorD... | rls/algorithms/single/ppo.py |
from typing import Dict, List
import numpy as np
import torch as th
import torch.distributions as td
from rls.algorithms.base.sarl_on_policy import SarlOnPolicy
from rls.common.data import Data
from rls.common.decorator import iton
from rls.nn.models import (ActorCriticValueCts, ActorCriticValueDct, ActorD... | 0.837487 | 0.320462 |
import numpy as np
class DefaultFunctions:
def __init__(self):
self.T = None
self.N = None
self.K_cus = None
self.K_pol = None
self.coeff_rr_u = None
self.coeff_rr_uu = None
self.coeff_rr_xu = None
self.coeff_rr_xx = None
self.coeff_rr_c = No... | objects/misc/default_functions.py | import numpy as np
class DefaultFunctions:
def __init__(self):
self.T = None
self.N = None
self.K_cus = None
self.K_pol = None
self.coeff_rr_u = None
self.coeff_rr_uu = None
self.coeff_rr_xu = None
self.coeff_rr_xx = None
self.coeff_rr_c = No... | 0.759582 | 0.234472 |
from .Graphics.objects.object2d import Connection, Pointer
from collections import deque
def create_bin_adj_list(Nodes, Edges, weighted=False):
'''
Binary Adj. List Format:
Weighted:
[(From, To, Weight),
...,
(From, None, None)]
... | VisualGraphTheory/algorithms.py | from .Graphics.objects.object2d import Connection, Pointer
from collections import deque
def create_bin_adj_list(Nodes, Edges, weighted=False):
'''
Binary Adj. List Format:
Weighted:
[(From, To, Weight),
...,
(From, None, None)]
... | 0.695752 | 0.414306 |
import hypothesis.extra.numpy as hnp
import hypothesis.strategies as st
import numpy as np
from hypothesis import given
from numpy.testing import assert_allclose
from mygrad import Tensor
from mygrad.nnet.activations import logsoftmax, softmax
from tests.utils.checkers import is_float_arr
from tests.custom_strategies ... | tests/nnet/activations/test_softmax.py | import hypothesis.extra.numpy as hnp
import hypothesis.strategies as st
import numpy as np
from hypothesis import given
from numpy.testing import assert_allclose
from mygrad import Tensor
from mygrad.nnet.activations import logsoftmax, softmax
from tests.utils.checkers import is_float_arr
from tests.custom_strategies ... | 0.705278 | 0.548553 |
import idfy_rest_client.models.merchant_error
class SignResponse(object):
"""Implementation of the 'SignResponse' model.
TODO: type model description here.
Attributes:
signed_data (string): base 64 encoded signed data
audit_log_reference (uuid|string): Reference Id to audit log... | idfy_rest_client/models/sign_response.py | import idfy_rest_client.models.merchant_error
class SignResponse(object):
"""Implementation of the 'SignResponse' model.
TODO: type model description here.
Attributes:
signed_data (string): base 64 encoded signed data
audit_log_reference (uuid|string): Reference Id to audit log... | 0.580233 | 0.248865 |
from datetime import datetime
from flask import (
Blueprint,
current_app,
flash,
jsonify,
redirect,
render_template,
request,
url_for
)
from flask_login import (
current_user,
login_user,
login_required,
logout_user
)
from .models import (
Campaign,
Character,
... | pbp/blueprint.py | from datetime import datetime
from flask import (
Blueprint,
current_app,
flash,
jsonify,
redirect,
render_template,
request,
url_for
)
from flask_login import (
current_user,
login_user,
login_required,
logout_user
)
from .models import (
Campaign,
Character,
... | 0.249264 | 0.051177 |
import json
import numpy as np
class EarlyStopping:
def __init__(self, patience, name, is_better_fn):
self.patience = patience
self.name = 'main_cost/avg'
self.is_better_fn = is_better_fn
self.metric_class_name = is_better_fn.__self__.__class__.__name__
self.best = None # b... | utils/early_stopping.py | import json
import numpy as np
class EarlyStopping:
def __init__(self, patience, name, is_better_fn):
self.patience = patience
self.name = 'main_cost/avg'
self.is_better_fn = is_better_fn
self.metric_class_name = is_better_fn.__self__.__class__.__name__
self.best = None # b... | 0.427516 | 0.165357 |
import click
import json
import logging
import pandas as pd
from tqdm import tqdm
import sys
origins = {
1:'ARGs',
2:'MGEs',
4:'MRGs',
3:'Functional Genes'
}
pathogens = {
1352: 'Enterococcus faecium',
1280: 'Staphylococcus aureus',
573: 'Klebsiella pneumonia',
470: 'Acinetobacter baum... | GeneTools/nanoarg/mapping_table.py | import click
import json
import logging
import pandas as pd
from tqdm import tqdm
import sys
origins = {
1:'ARGs',
2:'MGEs',
4:'MRGs',
3:'Functional Genes'
}
pathogens = {
1352: 'Enterococcus faecium',
1280: 'Staphylococcus aureus',
573: 'Klebsiella pneumonia',
470: 'Acinetobacter baum... | 0.183923 | 0.286806 |
from Qt_Viewer import Qt_Viewer
from pvaccess import *
from threading import Event
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QObject,pyqtSignal
import numpy as np
import sys
class PVAPYProvider(QObject) :
monitorCallbacksignal = pyqtSignal()
connectCallbacksignal = pyqtSignal()
def... | qtimage/PVAPY_Qt_Viewer.py |
from Qt_Viewer import Qt_Viewer
from pvaccess import *
from threading import Event
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QObject,pyqtSignal
import numpy as np
import sys
class PVAPYProvider(QObject) :
monitorCallbacksignal = pyqtSignal()
connectCallbacksignal = pyqtSignal()
def... | 0.290679 | 0.127381 |
import logging
LOGGER = logging.getLogger(__name__)
def sql_tables(bosslet_config):
"""
List all tables in sql.
Args:
bosslet_config (BossConfiguration): Bosslet configuration object
Returns:
tables(list): Lookup key.
"""
query = "show tables"
with bosslet_config.call.con... | lib/boss_rds.py |
import logging
LOGGER = logging.getLogger(__name__)
def sql_tables(bosslet_config):
"""
List all tables in sql.
Args:
bosslet_config (BossConfiguration): Bosslet configuration object
Returns:
tables(list): Lookup key.
"""
query = "show tables"
with bosslet_config.call.con... | 0.644001 | 0.361756 |
import math
from typing import Callable, Final, Sequence, Tuple
from hw1.solution1 import root_finding, secant
SEG_DEFAULT_BEG: Final = -1
SEG_DEFAULT_END: Final = 1
EPS_DEFAULT_VAL: Final = 10 ** (-20)
def _legendre(x_val, num_nodes) -> float:
"""
Calculates legendre function using recurrent formula for ho... | hw5/solution5.py | import math
from typing import Callable, Final, Sequence, Tuple
from hw1.solution1 import root_finding, secant
SEG_DEFAULT_BEG: Final = -1
SEG_DEFAULT_END: Final = 1
EPS_DEFAULT_VAL: Final = 10 ** (-20)
def _legendre(x_val, num_nodes) -> float:
"""
Calculates legendre function using recurrent formula for ho... | 0.844985 | 0.732424 |
from .lib import (
waf_detect,
infoga
)
from .utils import (
infoga_modules,
show,
log,
description,
proto,
no_proto,
waf_debug,
json_respon
)
import requests,readline,marshal,whois
from bs4 import BeautifulSoup as bs
log = log(__name__)
mod = infoga_modules
uag = {'User-Agent'... | zeeb_src/recon_src.py | from .lib import (
waf_detect,
infoga
)
from .utils import (
infoga_modules,
show,
log,
description,
proto,
no_proto,
waf_debug,
json_respon
)
import requests,readline,marshal,whois
from bs4 import BeautifulSoup as bs
log = log(__name__)
mod = infoga_modules
uag = {'User-Agent'... | 0.094482 | 0.090454 |
from django import forms
from django.contrib import admin, messages
from django.urls import reverse
from django.utils.html import mark_safe
from reversion_compare.admin import CompareVersionAdmin
from notesfrombelow.admin import editor_site
from . import models
class TagAdmin(CompareVersionAdmin):
list_display ... | django/journal/admin.py | from django import forms
from django.contrib import admin, messages
from django.urls import reverse
from django.utils.html import mark_safe
from reversion_compare.admin import CompareVersionAdmin
from notesfrombelow.admin import editor_site
from . import models
class TagAdmin(CompareVersionAdmin):
list_display ... | 0.477067 | 0.116613 |
from mealy.constants import ErrorAnalyzerConstants
from sklearn.metrics import accuracy_score, balanced_accuracy_score
import numpy as np
def compute_confidence_decision(primary_model_true_accuracy, primary_model_predicted_accuracy):
difference_true_pred_accuracy = np.abs(primary_model_true_accuracy - primary_mod... | mealy/metrics.py | from mealy.constants import ErrorAnalyzerConstants
from sklearn.metrics import accuracy_score, balanced_accuracy_score
import numpy as np
def compute_confidence_decision(primary_model_true_accuracy, primary_model_predicted_accuracy):
difference_true_pred_accuracy = np.abs(primary_model_true_accuracy - primary_mod... | 0.700383 | 0.421195 |
import copy
import re
import urlparse
from django.core.cache import cache
from django.core.exceptions import ImproperlyConfigured
from django.contrib.sites.shortcuts import get_current_site
from django.utils.translation import get_language
from .base import Menu, DEFAULT, ONCE, PER_REQUEST, POST_SELECT
from .utils impo... | nodes/processor.py | import copy
import re
import urlparse
from django.core.cache import cache
from django.core.exceptions import ImproperlyConfigured
from django.contrib.sites.shortcuts import get_current_site
from django.utils.translation import get_language
from .base import Menu, DEFAULT, ONCE, PER_REQUEST, POST_SELECT
from .utils impo... | 0.389547 | 0.081374 |
from email.utils import parseaddr
from pony.orm import *
import bcrypt
from . import custom_exceptions as PyUserExceptions
from .auth_type_enum import AUTH_TYPE
class user:
"""
A Class to manage Users in the Database
"""
def __str__(self):
if len(self.__dict__) > 0:
return str(sel... | pyusermanager/user_funcs.py | from email.utils import parseaddr
from pony.orm import *
import bcrypt
from . import custom_exceptions as PyUserExceptions
from .auth_type_enum import AUTH_TYPE
class user:
"""
A Class to manage Users in the Database
"""
def __str__(self):
if len(self.__dict__) > 0:
return str(sel... | 0.721645 | 0.143038 |
jossa data on esitetty vertailuarvoina"""
#Version: 3.9.5
#API:n osoitteet
def getAPIkeys():
with open("keyfile.txt", 'r') as keyfile:
keys = keyfile.read()
keys = keys.split(" ")
return keys
keys=getAPIkeys()
city = "Tampere"
provider1 = "openweathermap"
requestProvider1 ... | main.py | jossa data on esitetty vertailuarvoina"""
#Version: 3.9.5
#API:n osoitteet
def getAPIkeys():
with open("keyfile.txt", 'r') as keyfile:
keys = keyfile.read()
keys = keys.split(" ")
return keys
keys=getAPIkeys()
city = "Tampere"
provider1 = "openweathermap"
requestProvider1 ... | 0.208824 | 0.195998 |
from os import getenv
import numpy
from dotenv import load_dotenv
from shapely import geometry
from cu_pass.dpa_calculator.population_retriever.population_retriever import PopulationRetriever
from reference_models.geo.utils import GridPolygon
from reference_models.geo.zones import GetUsBorder
from src.lib.geo import ... | src/harness/cu_pass/dpa_calculator/population_retriever/population_retriever_census.py | from os import getenv
import numpy
from dotenv import load_dotenv
from shapely import geometry
from cu_pass.dpa_calculator.population_retriever.population_retriever import PopulationRetriever
from reference_models.geo.utils import GridPolygon
from reference_models.geo.zones import GetUsBorder
from src.lib.geo import ... | 0.679391 | 0.368747 |
import logging
import mimetypes
import os
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.mime.text ... | src/sendemail.py |
import logging
import mimetypes
import os
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.mime.text ... | 0.206974 | 0.082734 |
from dataclasses import dataclass
from functools import partial
from itertools import zip_longest
from pprint import pformat
from typing import Any, Optional
__all__ = [
"Task",
]
def parse_task_set(task_list_str: Optional[str]) -> frozenset[int]:
result = []
for task in (task_list_str or "").split():
... | tools/jasmine_tracker/tasks.py | from dataclasses import dataclass
from functools import partial
from itertools import zip_longest
from pprint import pformat
from typing import Any, Optional
__all__ = [
"Task",
]
def parse_task_set(task_list_str: Optional[str]) -> frozenset[int]:
result = []
for task in (task_list_str or "").split():
... | 0.822403 | 0.308028 |
import unittest
import os
import numpy as np
from openmdao.api import Problem, Group
from openmdao.utils.assert_utils import assert_near_equal, assert_check_partials
from pycycle.mp_cycle import Cycle
from pycycle.thermo.cea.species_data import janaf
from pycycle.elements.duct import Duct
from pycycle.elements.flow... | pycycle/elements/test/test_duct.py |
import unittest
import os
import numpy as np
from openmdao.api import Problem, Group
from openmdao.utils.assert_utils import assert_near_equal, assert_check_partials
from pycycle.mp_cycle import Cycle
from pycycle.thermo.cea.species_data import janaf
from pycycle.elements.duct import Duct
from pycycle.elements.flow... | 0.305801 | 0.459925 |
import configparser
import logging
import os
import time
import json
import requests
import pygame
from logging.handlers import RotatingFileHandler
from datetime import datetime
import sys
config = configparser.ConfigParser()
config.read('config.ini')
auth_key = config['general'].get('auth_key')
device_uid = config['... | liarbird.py | import configparser
import logging
import os
import time
import json
import requests
import pygame
from logging.handlers import RotatingFileHandler
from datetime import datetime
import sys
config = configparser.ConfigParser()
config.read('config.ini')
auth_key = config['general'].get('auth_key')
device_uid = config['... | 0.200558 | 0.038975 |
import pandas as pd
from sklearn.model_selection import train_test_split
TRAINING_DOWNLOAD_URL = 'https://www.dropbox.com/s/newxt7ifuipiezp/train.csv?dl=1'
TEST_DOWNLOAD_URL = 'https://www.dropbox.com/s/dhqm40csvi0mhhz/test.csv?dl=1'
TARGET = 'Choice'
def get_training_data(validation: bool=False, validation_size: fl... | assignment_1/data/data_reader.py | import pandas as pd
from sklearn.model_selection import train_test_split
TRAINING_DOWNLOAD_URL = 'https://www.dropbox.com/s/newxt7ifuipiezp/train.csv?dl=1'
TEST_DOWNLOAD_URL = 'https://www.dropbox.com/s/dhqm40csvi0mhhz/test.csv?dl=1'
TARGET = 'Choice'
def get_training_data(validation: bool=False, validation_size: fl... | 0.724188 | 0.439627 |
import os, time
from flask import request, jsonify, g, send_from_directory
from . import api
from authentication import auth
from .. import db
from ..models import User, Comment, News, Group
from errors import not_found, forbidden, bad_request
from datetime import datetime
UPLOAD_FOLDER = os.path.join(api.root_path, ... | app/api_1_0/files.py | import os, time
from flask import request, jsonify, g, send_from_directory
from . import api
from authentication import auth
from .. import db
from ..models import User, Comment, News, Group
from errors import not_found, forbidden, bad_request
from datetime import datetime
UPLOAD_FOLDER = os.path.join(api.root_path, ... | 0.228845 | 0.061171 |
import math
from dataclasses import dataclass
from typing import Optional, List, Dict
from rlbot.agents.base_agent import SimpleControllerState
from rlbot.utils.game_state_util import GameState, CarState, Vector3, Physics, Rotator
from choreography.drone import Drone
from util.vec import Vec3
@dataclass
class State... | ChoreographyHive/cnc/cnc_instructions.py | import math
from dataclasses import dataclass
from typing import Optional, List, Dict
from rlbot.agents.base_agent import SimpleControllerState
from rlbot.utils.game_state_util import GameState, CarState, Vector3, Physics, Rotator
from choreography.drone import Drone
from util.vec import Vec3
@dataclass
class State... | 0.792263 | 0.395455 |
from flask import Blueprint, render_template, request, send_file
from flask import current_app as app
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.fields.html5 import DateField
from wtforms.validators import InputRequired, Length
import datetime, io
from types import SimpleNamespace
f... | zeugs/flask_app/text_cover/text_cover0.py | from flask import Blueprint, render_template, request, send_file
from flask import current_app as app
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.fields.html5 import DateField
from wtforms.validators import InputRequired, Length
import datetime, io
from types import SimpleNamespace
f... | 0.244453 | 0.118947 |
from sfini.execution import _execution as tscr
import pytest
from unittest import mock
import sfini
import datetime
import json
from sfini.execution import history
@pytest.fixture
def session():
"""AWS session mock."""
return mock.MagicMock(autospec=sfini.AWSSession)
class TestExecution:
"""Test ``sfin... | tests/test_execution.py |
from sfini.execution import _execution as tscr
import pytest
from unittest import mock
import sfini
import datetime
import json
from sfini.execution import history
@pytest.fixture
def session():
"""AWS session mock."""
return mock.MagicMock(autospec=sfini.AWSSession)
class TestExecution:
"""Test ``sfin... | 0.835484 | 0.589007 |
import types, sys, re
try:
import logging
except:
import DummyLogger as logging
import simpleTAL
from plasTeX.Renderers.PageTemplate import simpletal
__version__ = simpletal.__version__
DEFAULTVALUE = "This represents a Default value."
class PathNotFoundException (Exception):
pass
class ContextContentExcept... | plasTeX/Renderers/PageTemplate/simpletal/simpleTALES.py | import types, sys, re
try:
import logging
except:
import DummyLogger as logging
import simpleTAL
from plasTeX.Renderers.PageTemplate import simpletal
__version__ = simpletal.__version__
DEFAULTVALUE = "This represents a Default value."
class PathNotFoundException (Exception):
pass
class ContextContentExcept... | 0.155976 | 0.210594 |
from typing import List
from model import Entry, Directory, NormalFile, VirusFile
def __dir_arg_parse(directory: Directory, directory_path: str) -> Entry:
"""Parses a concatenated directory path to return the proper target
which may be a file or directory
"""
dir_split = directory_path.split("/")
... | model/util/command.py | from typing import List
from model import Entry, Directory, NormalFile, VirusFile
def __dir_arg_parse(directory: Directory, directory_path: str) -> Entry:
"""Parses a concatenated directory path to return the proper target
which may be a file or directory
"""
dir_split = directory_path.split("/")
... | 0.620737 | 0.208179 |
import enum
from typing import Any, Iterable, Optional, Tuple, Type, TypeVar, Union
__all__ = [
"Choices",
"Enum",
"auto", # also export auto for convenience
"Switch",
"is_choices",
"is_enum",
"is_optional",
"unwrap_optional",
]
auto = enum.auto
NoneType = type(None)
T = TypeVar('T')... | argtyped/custom_types.py | import enum
from typing import Any, Iterable, Optional, Tuple, Type, TypeVar, Union
__all__ = [
"Choices",
"Enum",
"auto", # also export auto for convenience
"Switch",
"is_choices",
"is_enum",
"is_optional",
"unwrap_optional",
]
auto = enum.auto
NoneType = type(None)
T = TypeVar('T')... | 0.839438 | 0.376021 |
class Collect:
"""Collect data from the loader relevant to the specific task.
This keeps the items in ``keys`` as it is, and collect items in
``meta_keys`` into a meta item called ``meta_name``.This is usually
the last stage of the data loader pipeline.
For example, when keys='imgs', meta_keys=('fi... | features_extraction/dataloader/collect.py | class Collect:
"""Collect data from the loader relevant to the specific task.
This keeps the items in ``keys`` as it is, and collect items in
``meta_keys`` into a meta item called ``meta_name``.This is usually
the last stage of the data loader pipeline.
For example, when keys='imgs', meta_keys=('fi... | 0.931127 | 0.68875 |
import gc
from itertools import chain
from random import sample
from nltk import ngrams
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_selection import SelectFromModel
from sklearn.model_selection import train_test_split
from pathlib import Path
import SQLite_handler
from joblib import du... | fake_classfier.py |
import gc
from itertools import chain
from random import sample
from nltk import ngrams
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_selection import SelectFromModel
from sklearn.model_selection import train_test_split
from pathlib import Path
import SQLite_handler
from joblib import du... | 0.441673 | 0.26943 |
from datetime import datetime
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.datastructures import SortedDict
from django.utils.encoding import force_text
from django.views.debug import get_exception_reporter_filter
import l... | congo/maintenance/logs/handlers.py | from datetime import datetime
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.datastructures import SortedDict
from django.utils.encoding import force_text
from django.views.debug import get_exception_reporter_filter
import l... | 0.171061 | 0.046877 |
import bpy
class OrderByX():
def __init__(self):
"""
This will search all of the objects in the room, and apply a suffix to objects with a specified name in ascending order, E.G name.000, name.001.
This order is determined by their x coordinate (lower number = lower suffix), so things will need to be ordered... | Scripts/OrderByX.py | import bpy
class OrderByX():
def __init__(self):
"""
This will search all of the objects in the room, and apply a suffix to objects with a specified name in ascending order, E.G name.000, name.001.
This order is determined by their x coordinate (lower number = lower suffix), so things will need to be ordered... | 0.177882 | 0.621024 |
from bs4 import BeautifulSoup
import pytest
def test_home_page(test_client):
response = test_client.get('/')
assert response.status_code == 200
text_list = ['RCS Gugulethu AC', 'Home', 'Search Runner',
'Search Race', 'Predict Race Time', 'Login']
text_list_bytes = [str.encode(x) for x... | tests/test_wsgi.py | from bs4 import BeautifulSoup
import pytest
def test_home_page(test_client):
response = test_client.get('/')
assert response.status_code == 200
text_list = ['RCS Gugulethu AC', 'Home', 'Search Runner',
'Search Race', 'Predict Race Time', 'Login']
text_list_bytes = [str.encode(x) for x... | 0.259638 | 0.391813 |
import pickle as pkl
import numpy as np
import matplotlib.pyplot as plt
import random
from tqdm import tqdm
import argparse
from typing import List
from json import JSONEncoder, dumps
from wikipediaapi import Wikipedia
class Paragraph:
def __init__(self,
context: str):
self.context = con... | wiki-preparation/stats_analysis_results.py | import pickle as pkl
import numpy as np
import matplotlib.pyplot as plt
import random
from tqdm import tqdm
import argparse
from typing import List
from json import JSONEncoder, dumps
from wikipediaapi import Wikipedia
class Paragraph:
def __init__(self,
context: str):
self.context = con... | 0.473292 | 0.162347 |
#coding utf-8
'''print("请输入不小于10的整数")
n=input()
if n.isdigit()==True:
a=int(n)
print("%d"%(a/10))
else:
print("数据输入错误")'''
'''a=input("请你猜我的名字:")
if a=="xxx":
print("猜对了")
else:
print("猜错了")'''
'''a=input("请你猜我的名字:")
b="猜对了"
c="猜错了"
d=b if a=="xxx" else c
print(d) '''
'''print("猜... | test.py | #coding utf-8
'''print("请输入不小于10的整数")
n=input()
if n.isdigit()==True:
a=int(n)
print("%d"%(a/10))
else:
print("数据输入错误")'''
'''a=input("请你猜我的名字:")
if a=="xxx":
print("猜对了")
else:
print("猜错了")'''
'''a=input("请你猜我的名字:")
b="猜对了"
c="猜错了"
d=b if a=="xxx" else c
print(d) '''
'''print("猜... | 0.024458 | 0.096323 |
import paddle
import paddle.fluid as fluid
import time
import sys
from paddle_fl.mpc.data_utils.data_utils import get_datautils
sys.path.append('..')
import network
mpc_du = get_datautils('aby3')
def original_train(model_dir, model_filename):
"""
Original Training: train and save pre-trained paddle model
... | python/paddle_fl/mpc/examples/model_encryption/update/train_and_encrypt_model.py | import paddle
import paddle.fluid as fluid
import time
import sys
from paddle_fl.mpc.data_utils.data_utils import get_datautils
sys.path.append('..')
import network
mpc_du = get_datautils('aby3')
def original_train(model_dir, model_filename):
"""
Original Training: train and save pre-trained paddle model
... | 0.473901 | 0.173148 |
class informacoes:
nome =''
dia = 0
mes = 0
ano = 0
ddd = 0
tel = 0
rua =''
num = 0
cidade =''
estado =''
serie = 0
def enfeite(texto,estilos=''):
print('-'*100)
print(f'{estilos}{texto:^100}')
print(f'{"-"*30}{"_"*40}{"-"*30}')
def cadastro(integ):
print(' '*100)
print(f'Vagas dispo... | segundoModulo/classes4.py | class informacoes:
nome =''
dia = 0
mes = 0
ano = 0
ddd = 0
tel = 0
rua =''
num = 0
cidade =''
estado =''
serie = 0
def enfeite(texto,estilos=''):
print('-'*100)
print(f'{estilos}{texto:^100}')
print(f'{"-"*30}{"_"*40}{"-"*30}')
def cadastro(integ):
print(' '*100)
print(f'Vagas dispo... | 0.074085 | 0.220615 |
import json
from django.http import HttpResponse
from django.views.generic import View
from django.shortcuts import render
from braces.views import CsrfExemptMixin
from core.models import AccountBling, Product, Movement
from django.utils import timezone
from Bling import Api, ApiError, HookDataProduct, SyncStock
from d... | core/views.py | import json
from django.http import HttpResponse
from django.views.generic import View
from django.shortcuts import render
from braces.views import CsrfExemptMixin
from core.models import AccountBling, Product, Movement
from django.utils import timezone
from Bling import Api, ApiError, HookDataProduct, SyncStock
from d... | 0.331985 | 0.105671 |
from blockchainetl_common.executors.batch_work_executor import BatchWorkExecutor
from blockchainetl_common.jobs.base_job import BaseJob
from blockchainetl_common.utils import validate_range
from zilliqaetl.jobs.retriable_exceptions import RETRY_EXCEPTIONS
from zilliqaetl.mappers.event_log_mapper import map_event_logs... | cli/zilliqaetl/jobs/export_tx_blocks_job.py |
from blockchainetl_common.executors.batch_work_executor import BatchWorkExecutor
from blockchainetl_common.jobs.base_job import BaseJob
from blockchainetl_common.utils import validate_range
from zilliqaetl.jobs.retriable_exceptions import RETRY_EXCEPTIONS
from zilliqaetl.mappers.event_log_mapper import map_event_logs... | 0.643665 | 0.150247 |
from rpython.jit.metainterp.history import ConstInt, FLOAT
from rpython.jit.backend.ppc.locations import imm
def check_imm_box(arg, lower_bound=-2**15, upper_bound=2**15-1):
if isinstance(arg, ConstInt):
i = arg.getint()
return lower_bound <= i <= upper_bound
return False
def _check_imm_arg(i)... | rpython/jit/backend/ppc/helper/regalloc.py | from rpython.jit.metainterp.history import ConstInt, FLOAT
from rpython.jit.backend.ppc.locations import imm
def check_imm_box(arg, lower_bound=-2**15, upper_bound=2**15-1):
if isinstance(arg, ConstInt):
i = arg.getint()
return lower_bound <= i <= upper_bound
return False
def _check_imm_arg(i)... | 0.442637 | 0.276868 |
from pyramid.view import view_config
from ..Models import Base
from sqlalchemy import select, asc, func
from pyramid.security import NO_PERMISSION_REQUIRED
dictObj = {
'stations': 'Station',
'sensors': 'Sensor',
'individuals': 'Individual',
'monitoredSites': 'MonitoredSite',
'users': 'User',
'... | Back/ecoreleve_be_server/Views/autocomplete.py | from pyramid.view import view_config
from ..Models import Base
from sqlalchemy import select, asc, func
from pyramid.security import NO_PERMISSION_REQUIRED
dictObj = {
'stations': 'Station',
'sensors': 'Sensor',
'individuals': 'Individual',
'monitoredSites': 'MonitoredSite',
'users': 'User',
'... | 0.379493 | 0.171755 |
import argparse
import csv
import logging
import sys
def convert(input_csv, source_sep, dest_sep, output_file, label_col, label_order, quote_char='"'):
"""
Formats the input to the target by changing the separator
"""
label_map = {l: f"{i:03}_{l}" for i, l in enumerate(label_order)}
print(label_map)
... | src/utils/convert_to_csv.py | import argparse
import csv
import logging
import sys
def convert(input_csv, source_sep, dest_sep, output_file, label_col, label_order, quote_char='"'):
"""
Formats the input to the target by changing the separator
"""
label_map = {l: f"{i:03}_{l}" for i, l in enumerate(label_order)}
print(label_map)
... | 0.336222 | 0.199133 |
from tkinter import *
from tkinter import ttk
from tkinter import scrolledtext
from pandas.core.frame import DataFrame
from prettytable import PrettyTable
from parserT28.utils.decorators import singleton
@singleton
class DataWindow(object):
def __init__(self):
self._console = None
self._data = '... | bases_2021_1S/Grupo 03/parserT28/views/data_window.py | from tkinter import *
from tkinter import ttk
from tkinter import scrolledtext
from pandas.core.frame import DataFrame
from prettytable import PrettyTable
from parserT28.utils.decorators import singleton
@singleton
class DataWindow(object):
def __init__(self):
self._console = None
self._data = '... | 0.478529 | 0.122418 |
from .CardInfo import CardInfo
from woodcutter.src.Card import *
from woodcutter.src.Action import Action
class ADVISOR(CardInfo):
names = ["Advisor", "Advisors", "an Advisor"]
types = [Types.ACTION]
cost = [4, 0, 0]
def onPlay(self, state, log, cardIndex):
state = deepcopy(state)
sta... | woodcutter/src/CardActions/Guilds.py | from .CardInfo import CardInfo
from woodcutter.src.Card import *
from woodcutter.src.Action import Action
class ADVISOR(CardInfo):
names = ["Advisor", "Advisors", "an Advisor"]
types = [Types.ACTION]
cost = [4, 0, 0]
def onPlay(self, state, log, cardIndex):
state = deepcopy(state)
sta... | 0.357119 | 0.485722 |
from course_lib.Base.BaseRecommender import BaseRecommender
from typing import List
import numpy as np
class HybridPredictionRecommender(BaseRecommender):
models_object: List[BaseRecommender] = []
models_name: List[str] = []
models_aps: List[np.array] = []
def __init__(self, URM_train):
self.... | src/model/HybridRecommender/HybridPredictionRecommender.py | from course_lib.Base.BaseRecommender import BaseRecommender
from typing import List
import numpy as np
class HybridPredictionRecommender(BaseRecommender):
models_object: List[BaseRecommender] = []
models_name: List[str] = []
models_aps: List[np.array] = []
def __init__(self, URM_train):
self.... | 0.800302 | 0.533397 |
import unittest
import pandas as pd
from tqdm import tqdm
import oscml.data.dataset
import oscml.data.dataset_cep
import oscml.data.dataset_hopv15
import oscml.utils.util
from oscml.utils.util import smiles2mol
class TestData(unittest.TestCase):
def assert_PCE_values(self, df_100, df):
for i in range(l... | tests/test_data.py | import unittest
import pandas as pd
from tqdm import tqdm
import oscml.data.dataset
import oscml.data.dataset_cep
import oscml.data.dataset_hopv15
import oscml.utils.util
from oscml.utils.util import smiles2mol
class TestData(unittest.TestCase):
def assert_PCE_values(self, df_100, df):
for i in range(l... | 0.340485 | 0.457621 |
def SPV_Comment_dict(Set):
if Set == 1:
Set_dic = dict([
('Phi_Shift_476', 'Phase control NEH'),
('Phi_Shift_ps' , 'Phase shift FEH'),
('Cav_1' , 'Cav 1 '),
('Cav_2' , 'Cav 2 ')
])
else:
Set_dic = dict([
... | python/SPV_Comment_dict.py | def SPV_Comment_dict(Set):
if Set == 1:
Set_dic = dict([
('Phi_Shift_476', 'Phase control NEH'),
('Phi_Shift_ps' , 'Phase shift FEH'),
('Cav_1' , 'Cav 1 '),
('Cav_2' , 'Cav 2 ')
])
else:
Set_dic = dict([
... | 0.172974 | 0.267277 |
import logging, os
from logging.handlers import RotatingFileHandler
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from celery import Celery
from config import Config
# Monolith design
# Video... | project/__init__.py | import logging, os
from logging.handlers import RotatingFileHandler
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from celery import Celery
from config import Config
# Monolith design
# Video... | 0.22627 | 0.045121 |
import warnings
import numpy as np
from magicgui.widgets import Table
from napari.types import ImageData, LabelsData, LayerDataTuple
from napari import Viewer
from pandas import DataFrame
from qtpy.QtWidgets import QTableWidget, QTableWidgetItem, QWidget, QGridLayout, QPushButton, QFileDialog
from skimage.measure impo... | napari_feature_visualization/_regionprops.py | import warnings
import numpy as np
from magicgui.widgets import Table
from napari.types import ImageData, LabelsData, LayerDataTuple
from napari import Viewer
from pandas import DataFrame
from qtpy.QtWidgets import QTableWidget, QTableWidgetItem, QWidget, QGridLayout, QPushButton, QFileDialog
from skimage.measure impo... | 0.428951 | 0.511168 |
from Tkinter import *
import tkFont
import win32api
import win32print
import pyodbc
from fpdf import FPDF
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
arial18 = tkFont.Font(family='Arial', size=18, weight='bold') # big font so we can read it in the shop
... | Interface.py | from Tkinter import *
import tkFont
import win32api
import win32print
import pyodbc
from fpdf import FPDF
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
arial18 = tkFont.Font(family='Arial', size=18, weight='bold') # big font so we can read it in the shop
... | 0.161717 | 0.096748 |
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
from PIL import Image
import torch, argparse
import torchvision.utils as vutils
from moviepy.editor import VideoClip
import numpy as np
import lib, models
from lib.manipulate import *
parser = argparse.ArgumentParser(description='SGD/SWA training'... | interpolate.py | import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
from PIL import Image
import torch, argparse
import torchvision.utils as vutils
from moviepy.editor import VideoClip
import numpy as np
import lib, models
from lib.manipulate import *
parser = argparse.ArgumentParser(description='SGD/SWA training'... | 0.514888 | 0.411288 |
import logging
from collections import namedtuple
from operator import attrgetter
from pony.orm import db_session
from data import Article
from .index import Index
InvertedIndexEntry = namedtuple("InvertedIndexEntry", ["article", "count", "positions"])
class InvertedIndex(Index):
NAME = "inverted_index"
d... | index/invertedindex.py | import logging
from collections import namedtuple
from operator import attrgetter
from pony.orm import db_session
from data import Article
from .index import Index
InvertedIndexEntry = namedtuple("InvertedIndexEntry", ["article", "count", "positions"])
class InvertedIndex(Index):
NAME = "inverted_index"
d... | 0.416915 | 0.295065 |
import pyautogui
import configparser
import base64
import mimetypes
import time
def main():
config = configparser.ConfigParser()
config.read('config.ini')
files = eval(config.get("Main", "Files"))
for f in files:
global last_command
global default_delay
last... | DuckyTails.py | import pyautogui
import configparser
import base64
import mimetypes
import time
def main():
config = configparser.ConfigParser()
config.read('config.ini')
files = eval(config.get("Main", "Files"))
for f in files:
global last_command
global default_delay
last... | 0.055785 | 0.0686 |
import logging
import asyncio
import socket
import aiohttp
import async_timeout
from datetime import timedelta
from homeassistant.util.dt import now
TIMEOUT = 15
DATE_FORMAT = "%G-%m-%d"
_LOGGER: logging.Logger = logging.getLogger(__package__)
class DsnyApiClient:
def __init__(self, session: aiohttp.ClientSessi... | custom_components/dsny/api.py | import logging
import asyncio
import socket
import aiohttp
import async_timeout
from datetime import timedelta
from homeassistant.util.dt import now
TIMEOUT = 15
DATE_FORMAT = "%G-%m-%d"
_LOGGER: logging.Logger = logging.getLogger(__package__)
class DsnyApiClient:
def __init__(self, session: aiohttp.ClientSessi... | 0.545528 | 0.105027 |
import openpyxl
import os
class XlsxWriter():
def __init__(self, report, reportdir):
self.report = report
self.reportdir = reportdir
self.book = openpyxl.Workbook()
def write(self):
self.write_cover()
self.write_envinfo()
self.write_results()
report_pat... | script/report/writer/xlsx.py | import openpyxl
import os
class XlsxWriter():
def __init__(self, report, reportdir):
self.report = report
self.reportdir = reportdir
self.book = openpyxl.Workbook()
def write(self):
self.write_cover()
self.write_envinfo()
self.write_results()
report_pat... | 0.144843 | 0.243148 |
import inspect
from abc import ABCMeta, abstractmethod
from guniflask.annotation import AnnotationMetadata, AnnotationUtils
from guniflask.beans.definition import BeanDefinition
from guniflask.beans.definition_registry import BeanDefinitionRegistry
from guniflask.context.annotation import Component
from guniflask.cont... | guniflask/context/annotation_config_registry.py | import inspect
from abc import ABCMeta, abstractmethod
from guniflask.annotation import AnnotationMetadata, AnnotationUtils
from guniflask.beans.definition import BeanDefinition
from guniflask.beans.definition_registry import BeanDefinitionRegistry
from guniflask.context.annotation import Component
from guniflask.cont... | 0.563018 | 0.064831 |
from builtins import str
import os
import argparse
import logging
# Deal with matplotlib backend before importing seaborn
# See https://stackoverflow.com/a/50089385/579925
import matplotlib
if os.environ.get('DISPLAY','') == '':
print('No display found: using non-interactive Agg backend')
matplotlib.use('Agg')
im... | pegs/cli.py | from builtins import str
import os
import argparse
import logging
# Deal with matplotlib backend before importing seaborn
# See https://stackoverflow.com/a/50089385/579925
import matplotlib
if os.environ.get('DISPLAY','') == '':
print('No display found: using non-interactive Agg backend')
matplotlib.use('Agg')
im... | 0.559049 | 0.23118 |
from ..dirs import PEOPLE_DIR, SLEPOK_DIR
from .audio import preprocess_wav
from resemblyzer.voice_encoder import VoiceEncoder
from .cut_pauses import wav_by_segments
from .kaldi_tools import parse_kaldi_file, creat_output_file, write_file
import os
import numpy as np
import sys
def get_similarity(encoder, cont_embe... | src/diarization/diarization.py | from ..dirs import PEOPLE_DIR, SLEPOK_DIR
from .audio import preprocess_wav
from resemblyzer.voice_encoder import VoiceEncoder
from .cut_pauses import wav_by_segments
from .kaldi_tools import parse_kaldi_file, creat_output_file, write_file
import os
import numpy as np
import sys
def get_similarity(encoder, cont_embe... | 0.273671 | 0.134264 |
import sys, os
from pathlib import Path
import cv2
import numpy as np
import torch
from torchvision import datasets
from torch.autograd import Variable
from keras.applications.inception_resnet_v2 import preprocess_input
from keras.preprocessing.image import load_img, img_to_array
import tensorflow as tf
# detector
sy... | ml/server/estimator.py | import sys, os
from pathlib import Path
import cv2
import numpy as np
import torch
from torchvision import datasets
from torch.autograd import Variable
from keras.applications.inception_resnet_v2 import preprocess_input
from keras.preprocessing.image import load_img, img_to_array
import tensorflow as tf
# detector
sy... | 0.504394 | 0.20834 |