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 django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.views.generic import DeleteView, DetailView, UpdateView
from .forms import AddNewProduc... | goodbuyDatabase/views.py | from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.views.generic import DeleteView, DetailView, UpdateView
from .forms import AddNewProduc... | 0.411466 | 0.082291 |
import os
import six
import logging
from django.conf import settings
from bakery.views import BuildableMixin
from django.contrib.syndication.views import Feed
logger = logging.getLogger(__name__)
class BuildableFeed(Feed, BuildableMixin):
"""
Extends the base Django Feed class to be buildable.
"""
bui... | bakery/feeds.py | import os
import six
import logging
from django.conf import settings
from bakery.views import BuildableMixin
from django.contrib.syndication.views import Feed
logger = logging.getLogger(__name__)
class BuildableFeed(Feed, BuildableMixin):
"""
Extends the base Django Feed class to be buildable.
"""
bui... | 0.601242 | 0.114839 |
import logging
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.cache import caches
from django.db import connections
from django.db.migrations.executor import MigrationExecutor
from . import HealthcheckFailure
# don't bother with typing on Python <3.5
try:
from typing import O... | django_alive/checks.py | import logging
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.cache import caches
from django.db import connections
from django.db.migrations.executor import MigrationExecutor
from . import HealthcheckFailure
# don't bother with typing on Python <3.5
try:
from typing import O... | 0.791861 | 0.21101 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
DEFAULT_SERVICE = 'easyweb'
DEFAULT_URL = 'https://easyweb.... | institutions/TD.py | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
DEFAULT_SERVICE = 'easyweb'
DEFAULT_URL = 'https://easyweb.... | 0.191479 | 0.089694 |
# wujian@2018
# xpavlu10@2020
"""
Compute SI-SDR as the evaluation metric
"""
import argparse
from tqdm import tqdm
from collections import defaultdict
from libs.metric import si_snr, permute_si_snr, permute_si_snr_mix_of_mix
from libs.audio import WaveReader, Reader
from glob import glob
import numpy as np
impo... | nnet/compute_si_snr.py |
# wujian@2018
# xpavlu10@2020
"""
Compute SI-SDR as the evaluation metric
"""
import argparse
from tqdm import tqdm
from collections import defaultdict
from libs.metric import si_snr, permute_si_snr, permute_si_snr_mix_of_mix
from libs.audio import WaveReader, Reader
from glob import glob
import numpy as np
impo... | 0.617743 | 0.276881 |
import os
import re
import yaml
import base64
def read_base64(path):
return base64.b64encode(open(path, 'rb').read()).decode('utf-8')
class KubeConfig:
def __init__(self, workdir, apiserver):
ca_path = os.path.join(workdir, 'ca.pem')
self.workdir = workdir
self.apiserver = apiserver... | hardway/kubeconfig.py | import os
import re
import yaml
import base64
def read_base64(path):
return base64.b64encode(open(path, 'rb').read()).decode('utf-8')
class KubeConfig:
def __init__(self, workdir, apiserver):
ca_path = os.path.join(workdir, 'ca.pem')
self.workdir = workdir
self.apiserver = apiserver... | 0.397237 | 0.102439 |
import os
import random
import string
import time
from kubernetes import client as k8s_config
from kubernetes.client.api import core_v1_api
from kubernetes.client import api_client
from kubernetes.client.rest import ApiException
from rally.common import cfg
from rally.common import utils as common_utils
from rally i... | rally_openstack/task/scenarios/magnum/utils.py |
import os
import random
import string
import time
from kubernetes import client as k8s_config
from kubernetes.client.api import core_v1_api
from kubernetes.client import api_client
from kubernetes.client.rest import ApiException
from rally.common import cfg
from rally.common import utils as common_utils
from rally i... | 0.702122 | 0.227062 |
import numpy as np
import matplotlib.pylab as plt
import matplotlib.patches as patches
import os
import warnings
from scipy.interpolate import interp1d
import time
warnings.filterwarnings("ignore", category=FutureWarning)
def get_image_intensity(image):
intensity = 0
for row in image:
for pixel in row:... | heuslertools/mbe/rheed_oszillation.py | import numpy as np
import matplotlib.pylab as plt
import matplotlib.patches as patches
import os
import warnings
from scipy.interpolate import interp1d
import time
warnings.filterwarnings("ignore", category=FutureWarning)
def get_image_intensity(image):
intensity = 0
for row in image:
for pixel in row:... | 0.294925 | 0.373733 |
from core import perf_benchmark
import page_sets
from telemetry import benchmark
from telemetry.page import cache_temperature
from telemetry.web_perf import timeline_based_measurement
def AugmentOptionsForLoadingMetrics(tbm_options):
cat_filter = tbm_options.config.chrome_trace_config.category_filter
# "blink.c... | tools/perf/benchmarks/page_cycler_v2.py | from core import perf_benchmark
import page_sets
from telemetry import benchmark
from telemetry.page import cache_temperature
from telemetry.web_perf import timeline_based_measurement
def AugmentOptionsForLoadingMetrics(tbm_options):
cat_filter = tbm_options.config.chrome_trace_config.category_filter
# "blink.c... | 0.61173 | 0.153074 |
from m5.SimObject import SimObject
# This class represents the systemc kernel. There should be exactly one in the
# simulation. It receives gem5 SimObject lifecycle callbacks (init, regStats,
# etc.) and manages the lifecycle of the systemc simulation accordingly.
# It also acts as a collecting point for systemc rela... | src/systemc/core/SystemC.py |
from m5.SimObject import SimObject
# This class represents the systemc kernel. There should be exactly one in the
# simulation. It receives gem5 SimObject lifecycle callbacks (init, regStats,
# etc.) and manages the lifecycle of the systemc simulation accordingly.
# It also acts as a collecting point for systemc rela... | 0.469277 | 0.281912 |
from copy import deepcopy
class DataModelMixin:
"""
Base data model structure
"""
__deleted__ = False
def __init__(self, **kwargs):
self._data = deepcopy(kwargs)
self._changes = dict()
self._cache = dict()
def __repr__(self):
return f"<{self.__class__.__name__... | pyawx/models/_mixins.py | from copy import deepcopy
class DataModelMixin:
"""
Base data model structure
"""
__deleted__ = False
def __init__(self, **kwargs):
self._data = deepcopy(kwargs)
self._changes = dict()
self._cache = dict()
def __repr__(self):
return f"<{self.__class__.__name__... | 0.610918 | 0.352397 |
import gzip
import json
import base64
import logging
from datetime import datetime
import re
from typing import Any
import boto3
# Set up logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ec2_resource = boto3.resource('ec2', region_name='us-west-2')
table = boto3.resource('dynamodb', region_... | ec2_monitor/lambda_function.py | import gzip
import json
import base64
import logging
from datetime import datetime
import re
from typing import Any
import boto3
# Set up logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ec2_resource = boto3.resource('ec2', region_name='us-west-2')
table = boto3.resource('dynamodb', region_... | 0.36625 | 0.077622 |
import webapp2
from google.appengine.ext.webapp import util
from model import get_youtify_user_model_by_id_or_nick
from model import get_youtify_user_struct
from model import get_playlist_overview_structs
from model import get_followers_for_youtify_user_model
from model import get_followings_for_youtify_user_model
from... | users.py | import webapp2
from google.appengine.ext.webapp import util
from model import get_youtify_user_model_by_id_or_nick
from model import get_youtify_user_struct
from model import get_playlist_overview_structs
from model import get_followers_for_youtify_user_model
from model import get_followings_for_youtify_user_model
from... | 0.255065 | 0.07989 |
import mock
from zvmsdk import api
from zvmsdk import exception
from zvmsdk.tests.unit import base
class SDKAPITestCase(base.SDKTestCase):
"""Testcases for compute APIs."""
def setUp(self):
super(SDKAPITestCase, self).setUp()
self.api = api.SDKAPI()
self._vmops = mock.MagicMock()
... | zvmsdk/tests/unit/test_api.py | import mock
from zvmsdk import api
from zvmsdk import exception
from zvmsdk.tests.unit import base
class SDKAPITestCase(base.SDKTestCase):
"""Testcases for compute APIs."""
def setUp(self):
super(SDKAPITestCase, self).setUp()
self.api = api.SDKAPI()
self._vmops = mock.MagicMock()
... | 0.521471 | 0.151153 |
import pandas as pd
class System():
# A class to defin the systems which will be used on Bruntwood
def __init__(self,System_Ref,Name,Eff_Type,Cost,Capacity, Lifespan,Description,**Efficency):
self.System_Ref=System_Ref
self.Name=Name
self.Eff_Type=Eff_Type
self.Effice... | Systems/Systems.py | import pandas as pd
class System():
# A class to defin the systems which will be used on Bruntwood
def __init__(self,System_Ref,Name,Eff_Type,Cost,Capacity, Lifespan,Description,**Efficency):
self.System_Ref=System_Ref
self.Name=Name
self.Eff_Type=Eff_Type
self.Effice... | 0.235724 | 0.196441 |
import os, csv, math
from pathlib import Path
'''Hardcoded settings'''
directory_in_str = '/home/moar82/Documents/iot_miniaturization/results/sunspider/tunning_hv_server_173'
directory_for_org_measurements = '/home/moar82/Documents/iot_miniaturization/results/sunspider/default_duktape_measurements'
nb_of_objectives =4... | iot/utilities/getRawValsFromFUN.py | import os, csv, math
from pathlib import Path
'''Hardcoded settings'''
directory_in_str = '/home/moar82/Documents/iot_miniaturization/results/sunspider/tunning_hv_server_173'
directory_for_org_measurements = '/home/moar82/Documents/iot_miniaturization/results/sunspider/default_duktape_measurements'
nb_of_objectives =4... | 0.122195 | 0.14137 |
standalone = True
import time
import unittestX as unittest
class TestCase(unittest.TestCase):
def test1(self):
cmd = '''./testapp1.py \
--monitor.geometer.m1="(0,0,1),(0,0,0)" \
--monitor.geometer.m2="(0,0,0),(0,90,0)" \
--journal.debug.monitor \
'''
execute(cmd)
return
def tes... | packages/mcni/tests/mcni/pyre_components/MultiMonitors/MultiMonitors_TestCase.py |
standalone = True
import time
import unittestX as unittest
class TestCase(unittest.TestCase):
def test1(self):
cmd = '''./testapp1.py \
--monitor.geometer.m1="(0,0,1),(0,0,0)" \
--monitor.geometer.m2="(0,0,0),(0,90,0)" \
--journal.debug.monitor \
'''
execute(cmd)
return
def tes... | 0.40698 | 0.437042 |
import copy
import json
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import JsonResponse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from datatables_ajax.datatables import DjangoDat... | uni_ticket/views/datatables.py | import copy
import json
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import JsonResponse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from datatables_ajax.datatables import DjangoDat... | 0.53048 | 0.065965 |
from datetime import date, timedelta
from http import HTTPStatus
import pytest
from analyzer_service.api.schema import BIRTH_DATE_FORMAT
from analyzer_service.utils.pg import MAX_INTEGER
from analyzer_service.utils.testing import (
compare_citizen_groups, generate_citizen, generate_citizens, get_citizens,
imp... | tests/api/test_imports.py | from datetime import date, timedelta
from http import HTTPStatus
import pytest
from analyzer_service.api.schema import BIRTH_DATE_FORMAT
from analyzer_service.utils.pg import MAX_INTEGER
from analyzer_service.utils.testing import (
compare_citizen_groups, generate_citizen, generate_citizens, get_citizens,
imp... | 0.333395 | 0.238384 |
from __future__ import absolute_import
from dateutil.parser import parse
import pytest
from rest_framework.test import (
APIRequestFactory,
# RequestsClient, Not supported in older rest_framework versions
force_authenticate,
)
from opaque_keys.edx.keys import CourseKey
from figures.compat import Co... | tests/views/test_course_enrollment_view.py | from __future__ import absolute_import
from dateutil.parser import parse
import pytest
from rest_framework.test import (
APIRequestFactory,
# RequestsClient, Not supported in older rest_framework versions
force_authenticate,
)
from opaque_keys.edx.keys import CourseKey
from figures.compat import Co... | 0.464173 | 0.237601 |
from bsp_epidemic_suppression_model.model_utilities.epidemic_data import (
make_scenario_parameters_for_asymptomatic_symptomatic_model,
)
from bsp_epidemic_suppression_model.model_utilities.scenario import Scenario
from bsp_epidemic_suppression_model.math_utilities.functions_utils import (
DeltaMeasure,
Rea... | examples/reproduction_number_time_evolution_span_parameters.py | from bsp_epidemic_suppression_model.model_utilities.epidemic_data import (
make_scenario_parameters_for_asymptomatic_symptomatic_model,
)
from bsp_epidemic_suppression_model.model_utilities.scenario import Scenario
from bsp_epidemic_suppression_model.math_utilities.functions_utils import (
DeltaMeasure,
Rea... | 0.584864 | 0.375248 |
from html import unescape
from urllib.parse import unquote
import datasets
_CITATION = """\
@inproceedings{mitchell2015,
added-at = {2015-01-27T15:35:24.000+0100},
author = {<NAME>. and <NAME> <NAME> <NAME>. and <NAME>. and <NAME>. and <NAME>. and <NAME>. and <NAME>. and <NAME>. and <NAME>. and Samadi, M. and Se... | datasets/nell/nell.py | from html import unescape
from urllib.parse import unquote
import datasets
_CITATION = """\
@inproceedings{mitchell2015,
added-at = {2015-01-27T15:35:24.000+0100},
author = {<NAME>. and <NAME> <NAME> <NAME>. and <NAME>. and <NAME>. and <NAME>. and <NAME>. and <NAME>. and <NAME>. and <NAME>. and Samadi, M. and Se... | 0.675122 | 0.554109 |
import os
import sys
from datetime import timedelta
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, BASE_DIR) # 方便import app... | clashroyalecampsite_sever/settings.py | import os
import sys
from datetime import timedelta
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, BASE_DIR) # 方便import app... | 0.209389 | 0.07221 |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import compas_rhino
from compas.geometry import length_vector_sqrd
from compas.utilities import Colormap
from compas_rhino.artists import MeshArtist
__all__ = ['CablenetArtist']
class CablenetArtist(MeshA... | src/compas_fofin/rhino/cablenetartist.py | from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import compas_rhino
from compas.geometry import length_vector_sqrd
from compas.utilities import Colormap
from compas_rhino.artists import MeshArtist
__all__ = ['CablenetArtist']
class CablenetArtist(MeshA... | 0.917465 | 0.311322 |
import numpy as np
import os, dill
from scipy.sparse import coo_matrix
from gcn.lib.utils.lib_utils import py_struct, swap_keyVal, normalize_dic
def build_bipartitie_graph(kegg_genes_fn):
fp = open(kegg_genes_fn, 'r')
heads = fp.next()[1:-1].split('\t')
hsa_to_genes = [[],[],[]]
hsa_idx = 0
gene_idx = 0
Hsa = {}... | gcn/bin/prioritize/bipartite_diffusion.py | import numpy as np
import os, dill
from scipy.sparse import coo_matrix
from gcn.lib.utils.lib_utils import py_struct, swap_keyVal, normalize_dic
def build_bipartitie_graph(kegg_genes_fn):
fp = open(kegg_genes_fn, 'r')
heads = fp.next()[1:-1].split('\t')
hsa_to_genes = [[],[],[]]
hsa_idx = 0
gene_idx = 0
Hsa = {}... | 0.151906 | 0.433022 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")
driver = webdriver.Chrome(chrome_options=chrome_options)
# driver = webdriver.Chrome('chromedriver.exe', chrome_options=self.browserProfile)
d... | Insta-3/example.py | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")
driver = webdriver.Chrome(chrome_options=chrome_options)
# driver = webdriver.Chrome('chromedriver.exe', chrome_options=self.browserProfile)
d... | 0.131507 | 0.051966 |
import argparse
import json
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import dataset
from models import UNet
import trainer
import utils
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-c",
"--config",
type=str,
... | train.py | import argparse
import json
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import dataset
from models import UNet
import trainer
import utils
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-c",
"--config",
type=str,
... | 0.569374 | 0.181644 |
# no functions
# classes
class ClipPlane(object):
""" ClipPlane() """
def Delete(self):
""" Delete(self: ClipPlane) -> bool """
pass
def Insert(self):
""" Insert(self: ClipPlane) -> bool """
pass
def Modify(self):
""" Modify(self: ClipPlane)... | release/stubs.min/Tekla/Structures/Model/UI.py |
# no functions
# classes
class ClipPlane(object):
""" ClipPlane() """
def Delete(self):
""" Delete(self: ClipPlane) -> bool """
pass
def Insert(self):
""" Insert(self: ClipPlane) -> bool """
pass
def Modify(self):
""" Modify(self: ClipPlane)... | 0.677154 | 0.54468 |
from bin import cloud, utils
class Show:
def run(self, line: str):
self.show(line.lower())
def show(self, arg: str):
if arg == '':
utils.colour_print(
'Use (colour_cmd)help show (colour_clear)to see available '
'subcommands for (colour_cmd)show(col... | commands/show.py | from bin import cloud, utils
class Show:
def run(self, line: str):
self.show(line.lower())
def show(self, arg: str):
if arg == '':
utils.colour_print(
'Use (colour_cmd)help show (colour_clear)to see available '
'subcommands for (colour_cmd)show(col... | 0.229018 | 0.281912 |
"""Unit testing for models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import tensorflow.compat.v1 as tf
from tensorflow.compat.v1.python.framework import ops as _ops
from tensorflow.compat.v1.python.keras impo... | tensorflow_privacy/privacy/bolt_on/models_test.py | """Unit testing for models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import tensorflow.compat.v1 as tf
from tensorflow.compat.v1.python.framework import ops as _ops
from tensorflow.compat.v1.python.keras impo... | 0.965811 | 0.370966 |
import OGL
from macros import *
from math import cos, sin, radians, degrees
from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
import shoot
import config
from formula import *
class SmithAndWesson(OGL.Cube):
def __init__(self):
self.standby_pos = config.SmithAndWesson["Standby Pos"]#[.3,-.25,-1... | objects/player.py | import OGL
from macros import *
from math import cos, sin, radians, degrees
from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
import shoot
import config
from formula import *
class SmithAndWesson(OGL.Cube):
def __init__(self):
self.standby_pos = config.SmithAndWesson["Standby Pos"]#[.3,-.25,-1... | 0.321886 | 0.144813 |
import collections
import json
from urllib.parse import urlparse
import xbmc
import xbmcaddon
_main_addon = None
def get_main_addon():
global _main_addon
if not _main_addon:
_main_addon = xbmcaddon.Addon()
return _main_addon
def localize(messageid):
if isinstance(messageid, str):
retur... | python/lib/pykodi.py | import collections
import json
from urllib.parse import urlparse
import xbmc
import xbmcaddon
_main_addon = None
def get_main_addon():
global _main_addon
if not _main_addon:
_main_addon = xbmcaddon.Addon()
return _main_addon
def localize(messageid):
if isinstance(messageid, str):
retur... | 0.301362 | 0.048451 |
import uos
import sys
import machine
from machine import reset
import _thread
try:
import usocket as socket
except:
import socket
led = -1
def web_page():
global led
if led.value() == 1:
gpio_state="ON"
else:
gpio_state="OFF"
html = """<html><head> <title>ESP Web Server</title> <meta name="view... | Projects/ESP32Micropython/20-12-21/main.py | import uos
import sys
import machine
from machine import reset
import _thread
try:
import usocket as socket
except:
import socket
led = -1
def web_page():
global led
if led.value() == 1:
gpio_state="ON"
else:
gpio_state="OFF"
html = """<html><head> <title>ESP Web Server</title> <meta name="view... | 0.229276 | 0.054024 |
import numpy as np
from lab2.utils import get_random_number_generator
class BallWindow:
"""Create a ball with a center and a radius
"""
def __init__(self, center, radius):
"""Initialize the center and the radius of the ball
Args:
center (array): a point with two coordinates.... | src/lab2/ball_window.py | import numpy as np
from lab2.utils import get_random_number_generator
class BallWindow:
"""Create a ball with a center and a radius
"""
def __init__(self, center, radius):
"""Initialize the center and the radius of the ball
Args:
center (array): a point with two coordinates.... | 0.936249 | 0.788502 |
import pprint
import re # noqa: F401
import six
from openapi_client.configuration import Configuration
class ProcessInstanceQueryDtoSorting(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attr... | openapi-python-client/openapi_client/models/process_instance_query_dto_sorting.py | import pprint
import re # noqa: F401
import six
from openapi_client.configuration import Configuration
class ProcessInstanceQueryDtoSorting(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attr... | 0.839405 | 0.192444 |
r"""Compute action detection performance for the AVA dataset.
Please send any questions about this code to the Google Group ava-dataset-users:
https://groups.google.com/forum/#!forum/ava-dataset-users
Example usage:
python -O get_ava_performance.py \
-l ava/ava_action_list_v2.1_for_activitynet_2018.pbtxt.txt \
-g... | evaluation/get_ava_performance_custom.py | r"""Compute action detection performance for the AVA dataset.
Please send any questions about this code to the Google Group ava-dataset-users:
https://groups.google.com/forum/#!forum/ava-dataset-users
Example usage:
python -O get_ava_performance.py \
-l ava/ava_action_list_v2.1_for_activitynet_2018.pbtxt.txt \
-g... | 0.791861 | 0.47725 |
from __future__ import annotations
import orjson
from sauronlab.core.core_imports import *
def _o(x: Optional[int]) -> int:
return 0 if x is None else x
# we can't use dataclass order=True because None is allowed
@abcd.total_ordering
@dataclass(frozen=True, order=False)
class Treatment:
"""
A drug (ba... | sauronlab/model/treatments.py | from __future__ import annotations
import orjson
from sauronlab.core.core_imports import *
def _o(x: Optional[int]) -> int:
return 0 if x is None else x
# we can't use dataclass order=True because None is allowed
@abcd.total_ordering
@dataclass(frozen=True, order=False)
class Treatment:
"""
A drug (ba... | 0.787032 | 0.244391 |
import typing
from datetime import datetime
from enum import Enum
from typing import List
import aiohttp
from pytrafikverket.trafikverket import (
FieldFilter,
FieldSort,
FilterOperation,
NodeHelper,
SortOrder,
Trafikverket,
)
class RouteInfo(object):
"""Contains information about a Ferr... | pytrafikverket/trafikverket_ferry.py |
import typing
from datetime import datetime
from enum import Enum
from typing import List
import aiohttp
from pytrafikverket.trafikverket import (
FieldFilter,
FieldSort,
FilterOperation,
NodeHelper,
SortOrder,
Trafikverket,
)
class RouteInfo(object):
"""Contains information about a Ferr... | 0.859457 | 0.158467 |
from datetime import datetime
from .Location import Location
class REPLine:
def __init__(self, linenumber, line):
self.lineNum = linenumber
self.line = line
self.timestamp = None
self.vessel = None
self.symbology = None
self.latitude = None
self.longitude =... | Formats/REPFile.py | from datetime import datetime
from .Location import Location
class REPLine:
def __init__(self, linenumber, line):
self.lineNum = linenumber
self.line = line
self.timestamp = None
self.vessel = None
self.symbology = None
self.latitude = None
self.longitude =... | 0.263789 | 0.289315 |
import numpy as np
import fitdist as fitdist
print(fitdist.__version__)
# %% Import class
from fitdist import fitdist
dir(fitdist)
#%%
X = np.random.normal(0, 2, 5000)
y = [-8,-6,0,1,2,3,4,5,6]
model = fitdist()
model.fit_transform(X)
model.plot()
# Make prediction
model.predict(y)
model.plot()
# %% Fit and t... | fitdist/examples.py |
import numpy as np
import fitdist as fitdist
print(fitdist.__version__)
# %% Import class
from fitdist import fitdist
dir(fitdist)
#%%
X = np.random.normal(0, 2, 5000)
y = [-8,-6,0,1,2,3,4,5,6]
model = fitdist()
model.fit_transform(X)
model.plot()
# Make prediction
model.predict(y)
model.plot()
# %% Fit and t... | 0.528533 | 0.370539 |
import itertools
import collections
import pytest
import repobee_plug as plug
from _repobee.plugin import register_plugins
from _repobee.ext import pairwise
import constants
class TestGenerateReviewAllocations:
"""Tests the default implementation of generate_review_allocations."""
def test_register(self... | tests/unit_tests/repobee/plugin_tests/test_pairwise.py | import itertools
import collections
import pytest
import repobee_plug as plug
from _repobee.plugin import register_plugins
from _repobee.ext import pairwise
import constants
class TestGenerateReviewAllocations:
"""Tests the default implementation of generate_review_allocations."""
def test_register(self... | 0.746509 | 0.375191 |
from __future__ import print_function
import networkx as nx
from . import graph
from . import resolve
def inspect_graph(import_graph):
keys = set(x[0] for x in import_graph.graph.edges)
for key in sorted(keys):
k = import_graph.format(key)
for _, value in sorted(import_graph.graph.edges([key... | importlab/output.py | from __future__ import print_function
import networkx as nx
from . import graph
from . import resolve
def inspect_graph(import_graph):
keys = set(x[0] for x in import_graph.graph.edges)
for key in sorted(keys):
k = import_graph.format(key)
for _, value in sorted(import_graph.graph.edges([key... | 0.52756 | 0.111531 |
from matplotlib import pyplot as plt # Pyplot for nice graphs
from matplotlib.gridspec import GridSpec
from progress.bar import Bar
import numpy as np # NumPy
from Functions import ImportSystem, DefineDevice
from Functions import EnergyRecursion, Transmission, PeriodicHamiltonian
import sys
np... | Listings/3KpointTransmission.py | from matplotlib import pyplot as plt # Pyplot for nice graphs
from matplotlib.gridspec import GridSpec
from progress.bar import Bar
import numpy as np # NumPy
from Functions import ImportSystem, DefineDevice
from Functions import EnergyRecursion, Transmission, PeriodicHamiltonian
import sys
np... | 0.46393 | 0.698315 |
from attrdict import AttrDict
import torch
from torch import nn
import torch.nn.functional as F
from eqv_transformer.classfier import Classifier
from eqv_transformer.eqv_attention_se2_finite import EqvTransformer
from forge import flags
# flags.DEFINE_integer('input_dim', 2, 'Dimensionality of the input.')
flags.DEF... | configs/constellation/se2_finite_transformer.py | from attrdict import AttrDict
import torch
from torch import nn
import torch.nn.functional as F
from eqv_transformer.classfier import Classifier
from eqv_transformer.eqv_attention_se2_finite import EqvTransformer
from forge import flags
# flags.DEFINE_integer('input_dim', 2, 'Dimensionality of the input.')
flags.DEF... | 0.846387 | 0.183228 |
from .BaseQuery import BaseQuery
from .utils import by_epic, date_difference
class LeadtimeQuery(BaseQuery):
template = ('Between {begin_date} and {end_date}, '
'the average lead time was {value} days.')
query_bases = {
'leadtime': ('PROJECT = {project} '
'AND TYPE... | mosaic/queries/LeadtimeQuery.py | from .BaseQuery import BaseQuery
from .utils import by_epic, date_difference
class LeadtimeQuery(BaseQuery):
template = ('Between {begin_date} and {end_date}, '
'the average lead time was {value} days.')
query_bases = {
'leadtime': ('PROJECT = {project} '
'AND TYPE... | 0.516839 | 0.161949 |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class AvailableHardware(Base):
"""The AvailableHardware class encapsulates a required availableHardware node in the ixnetwork hierarchy.
An instance of the class can be obtained by accessing the AvailableHardware property ... | RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/availablehardware/availablehardware.py |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class AvailableHardware(Base):
"""The AvailableHardware class encapsulates a required availableHardware node in the ixnetwork hierarchy.
An instance of the class can be obtained by accessing the AvailableHardware property ... | 0.767341 | 0.19544 |
from python_libs import sh
import argparse
import os
from os import path
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("dir")
parser.add_argument("dataset_config")
parser.add_argument("--delete_original", action="store_true")
parser.add_argument("--max_prefix_size", type=int)
parse... | get_datasets.py |
from python_libs import sh
import argparse
import os
from os import path
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("dir")
parser.add_argument("dataset_config")
parser.add_argument("--delete_original", action="store_true")
parser.add_argument("--max_prefix_size", type=int)
parse... | 0.278061 | 0.107625 |
from typing import List, Optional, TYPE_CHECKING
import weakref
from electrumsv.constants import PaymentFlag
from electrumsv.paymentrequest import PaymentRequest
from electrumsv.wallet_database.sqlite_support import CompletionCallbackType, SynchronousWriter
from electrumsv.wallet_database.tables import InvoiceAccountR... | electrumsv/services/invoices.py | from typing import List, Optional, TYPE_CHECKING
import weakref
from electrumsv.constants import PaymentFlag
from electrumsv.paymentrequest import PaymentRequest
from electrumsv.wallet_database.sqlite_support import CompletionCallbackType, SynchronousWriter
from electrumsv.wallet_database.tables import InvoiceAccountR... | 0.869008 | 0.208421 |
import argparse
import os
import ray
from ray import tune
from ray.tune.utils.release_test_util import timed_tune_run
def main(bucket):
secrets_file = os.path.join(
os.path.dirname(__file__), "..", "aws_secrets.txt")
if os.path.isfile(secrets_file):
print(f"Loading AWS secrets from file {sec... | release/tune_tests/scalability_tests/workloads/test_durable_trainable.py | import argparse
import os
import ray
from ray import tune
from ray.tune.utils.release_test_util import timed_tune_run
def main(bucket):
secrets_file = os.path.join(
os.path.dirname(__file__), "..", "aws_secrets.txt")
if os.path.isfile(secrets_file):
print(f"Loading AWS secrets from file {sec... | 0.32896 | 0.087837 |
import sys
sys.path.append('.')
import datetime as dt, time, re, calendar, sys
from utils import get_strdate_format
from wull import wull, iswull, WULL
from datetime import datetime
if sys.version_info.major >=3 and sys.version_info.minor>=8:
clocktime = time.perf_counter
process_time = time.process_time
... | richdb/ztime.py | import sys
sys.path.append('.')
import datetime as dt, time, re, calendar, sys
from utils import get_strdate_format
from wull import wull, iswull, WULL
from datetime import datetime
if sys.version_info.major >=3 and sys.version_info.minor>=8:
clocktime = time.perf_counter
process_time = time.process_time
... | 0.479747 | 0.208058 |
from ... pyaz_utils import _call_az
from . import task
def create(location, name, resource_group, service_name, source_platform, target_platform, tags=None):
'''
Create a migration project which can contain multiple tasks.
Required Parameters:
- location -- Location. Values from: `az account list-loc... | pyaz/dms/project/__init__.py | from ... pyaz_utils import _call_az
from . import task
def create(location, name, resource_group, service_name, source_platform, target_platform, tags=None):
'''
Create a migration project which can contain multiple tasks.
Required Parameters:
- location -- Location. Values from: `az account list-loc... | 0.845592 | 0.205456 |
import argparse
import numpy as np
import networkx as nx
import node2vec2
from gensim.models import Word2Vec
def parse_args():
'''
Parses the node2vec arguments.
'''
parser = argparse.ArgumentParser(description="Run node2vec.")
parser.add_argument('--input', nargs='?', default='graph/karate.edgel... | src/main.py | import argparse
import numpy as np
import networkx as nx
import node2vec2
from gensim.models import Word2Vec
def parse_args():
'''
Parses the node2vec arguments.
'''
parser = argparse.ArgumentParser(description="Run node2vec.")
parser.add_argument('--input', nargs='?', default='graph/karate.edgel... | 0.65379 | 0.188623 |
import json
import socket
import thread
from threading import Thread
import logging
from liota.disc_listeners.discovery_listener import DiscoveryListener
log = logging.getLogger(__name__)
class SocketListener(DiscoveryListener):
"""
SocketListener does inter-process communication (IPC), and
blocks on a so... | liota/disc_listeners/socket_svr.py | import json
import socket
import thread
from threading import Thread
import logging
from liota.disc_listeners.discovery_listener import DiscoveryListener
log = logging.getLogger(__name__)
class SocketListener(DiscoveryListener):
"""
SocketListener does inter-process communication (IPC), and
blocks on a so... | 0.275422 | 0.046899 |
#! /usr/bin/env python3
from __future__ import print_function
import numpy as np
import faiss
import time
import os
import argparse
parser = argparse.ArgumentParser()
def aa(*args, **kwargs):
group.add_argument(*args, **kwargs)
group = parser.add_argument_group('dataset options')
aa('--dim', type=int, default... | internal/core/src/index/thirdparty/faiss/benchs/bench_for_interrupt.py |
#! /usr/bin/env python3
from __future__ import print_function
import numpy as np
import faiss
import time
import os
import argparse
parser = argparse.ArgumentParser()
def aa(*args, **kwargs):
group.add_argument(*args, **kwargs)
group = parser.add_argument_group('dataset options')
aa('--dim', type=int, default... | 0.308398 | 0.129678 |
import sys
import inspect
import base64
if (sys.version_info > (3, 0)):
import io
else:
import cStringIO as io
from viewerstate import *
from visitstate import RPCType as RPC
class ViewerMethods:
def __init__(self,_state):
self.state = _state
def sync(self):
gmap = sys.modules["__main_... | src/resources/clients/python_client/viewermethods.py | import sys
import inspect
import base64
if (sys.version_info > (3, 0)):
import io
else:
import cStringIO as io
from viewerstate import *
from visitstate import RPCType as RPC
class ViewerMethods:
def __init__(self,_state):
self.state = _state
def sync(self):
gmap = sys.modules["__main_... | 0.285073 | 0.14774 |
"""Criteo Classification Sample Preprocessing Runner."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import datetime
import os
import random
import subprocess
import sys
import criteo
import path_constants
import apache_beam as beam
imp... | criteo_tft/preprocess.py | """Criteo Classification Sample Preprocessing Runner."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import datetime
import os
import random
import subprocess
import sys
import criteo
import path_constants
import apache_beam as beam
imp... | 0.593727 | 0.190103 |
import os
from transformers import (BertConfig, BertForMaskedLM, BertTokenizer,
AlbertConfig, AlbertForMaskedLM, AlbertTokenizer)
import torch
from torch.utils.data import ConcatDataset, TensorDataset
import numpy as np
import random
import pickle
import logging
import re
import glob
import sh... | src/models/mlm_finetune/utils.py | import os
from transformers import (BertConfig, BertForMaskedLM, BertTokenizer,
AlbertConfig, AlbertForMaskedLM, AlbertTokenizer)
import torch
from torch.utils.data import ConcatDataset, TensorDataset
import numpy as np
import random
import pickle
import logging
import re
import glob
import sh... | 0.511229 | 0.326728 |
from typing import TYPE_CHECKING, Any, Dict, List, Optional
import asyncpg
from app import commands, errors
from app.cogs.premium.premium_funcs import can_increase, limit_for
from app.i18n import t_
if TYPE_CHECKING:
from app.database.database import Database
class PosRoles:
def __init__(self, db: "Databas... | app/database/database_functions/posroles.py | from typing import TYPE_CHECKING, Any, Dict, List, Optional
import asyncpg
from app import commands, errors
from app.cogs.premium.premium_funcs import can_increase, limit_for
from app.i18n import t_
if TYPE_CHECKING:
from app.database.database import Database
class PosRoles:
def __init__(self, db: "Databas... | 0.645008 | 0.111 |
import os
import yaml
class Project(object):
def __init__(self, data, source=None, dir=None, annotation=None):
self.data = data
self.source = source
self.dir = dir
self.annotation = annotation
self.command_line_flags = []
self.command_line_profiles = []
def att... | guild/project.py | import os
import yaml
class Project(object):
def __init__(self, data, source=None, dir=None, annotation=None):
self.data = data
self.source = source
self.dir = dir
self.annotation = annotation
self.command_line_flags = []
self.command_line_profiles = []
def att... | 0.327883 | 0.133641 |
from __future__ import absolute_import
import numpy as np
from datetime import datetime
import csv
import os
from dateutil import parser
class GridInfo:
"""
This class provides common info about the grid
"""
def __init__(self, input_file='Grid_Info_data_artificial_inertia.csv', **kwargs):
# ... | src/grid_info_artificial_inertia.py |
from __future__ import absolute_import
import numpy as np
from datetime import datetime
import csv
import os
from dateutil import parser
class GridInfo:
"""
This class provides common info about the grid
"""
def __init__(self, input_file='Grid_Info_data_artificial_inertia.csv', **kwargs):
# ... | 0.695131 | 0.198122 |
import datetime as dt
import warnings
import numpy as np
import pandas as pd
from lhorizon import LHorizon
from lhorizon.constants import LUNAR_RADIUS
from lhorizon.lhorizon_utils import make_raveled_meshgrid
from lhorizon.solutions import make_ray_sphere_lambdas
from lhorizon.target import Targeter
from lhorizon.ker... | lhorizon/tests/test_targeter_online.py | import datetime as dt
import warnings
import numpy as np
import pandas as pd
from lhorizon import LHorizon
from lhorizon.constants import LUNAR_RADIUS
from lhorizon.lhorizon_utils import make_raveled_meshgrid
from lhorizon.solutions import make_ray_sphere_lambdas
from lhorizon.target import Targeter
from lhorizon.ker... | 0.608594 | 0.348008 |
rp_solver_list_1d = []
rp_solver_list_2d = []
rp_solver_list_3d = []
# Import 1d Riemann solvers
from advection_1D_py import advection_1D
from vc_advection_1D_py import vc_advection_1D
from acoustics_1D_py import acoustics_1D
from burgers_1D_py import burgers_1D
from shallow_1D_py import shallow_roe_1D, shallow_hll_1D... | docker/src/clawpack-5.3.1/riemann/src/__init__.py | rp_solver_list_1d = []
rp_solver_list_2d = []
rp_solver_list_3d = []
# Import 1d Riemann solvers
from advection_1D_py import advection_1D
from vc_advection_1D_py import vc_advection_1D
from acoustics_1D_py import acoustics_1D
from burgers_1D_py import burgers_1D
from shallow_1D_py import shallow_roe_1D, shallow_hll_1D... | 0.321993 | 0.317598 |
from exceptions import *
from dakota_file import DakotaFile
import numpy as np
import xarray as xr
import unittest
import main
import os
import test_dakota_file
# These are essentially integration tests.
class fake_args:
def __init__(self):
self.driver = None
self.concurrency = 1
se... | user_interface/test/test_main.py | from exceptions import *
from dakota_file import DakotaFile
import numpy as np
import xarray as xr
import unittest
import main
import os
import test_dakota_file
# These are essentially integration tests.
class fake_args:
def __init__(self):
self.driver = None
self.concurrency = 1
se... | 0.594787 | 0.356475 |
import sys
import maya.cmds as cmds
from mGui.core import Control
import maya.mel as mel
class UserCancelledProgress(RuntimeError):
pass
class ProgressBar(Control):
"""
mGui style wrapper for ProgressBar
Use start() and end() to avoid the cumbersome (cmds.progressBar('xxx', e=True, beginProgress = ... | mGui/core/progress.py | import sys
import maya.cmds as cmds
from mGui.core import Control
import maya.mel as mel
class UserCancelledProgress(RuntimeError):
pass
class ProgressBar(Control):
"""
mGui style wrapper for ProgressBar
Use start() and end() to avoid the cumbersome (cmds.progressBar('xxx', e=True, beginProgress = ... | 0.340595 | 0.211498 |
import pygame
import time
from .game import Game
from .sound import Sound
from .window import Window
from .db.database import DB
from .constants import Paths, Win, Buttons, Table
class Menu():
def __init__(self):
# Initialize pygame
pygame.init()
self.sound = Sound(
menu_soundt... | src/menu.py | import pygame
import time
from .game import Game
from .sound import Sound
from .window import Window
from .db.database import DB
from .constants import Paths, Win, Buttons, Table
class Menu():
def __init__(self):
# Initialize pygame
pygame.init()
self.sound = Sound(
menu_soundt... | 0.457864 | 0.142143 |
from iexfinance.iexdata.base import (
TOPS,
Last,
DEEP,
Book,
IntradayReader,
RecentReader,
RecordsReader,
DailySummaryReader,
MonthlySummaryReader,
)
def get_tops(symbols=None, **kwargs):
"""
TOPS data for a symbol or list of symbols.
TOPS provides IEX's aggregated be... | iexfinance/iexdata/__init__.py | from iexfinance.iexdata.base import (
TOPS,
Last,
DEEP,
Book,
IntradayReader,
RecentReader,
RecordsReader,
DailySummaryReader,
MonthlySummaryReader,
)
def get_tops(symbols=None, **kwargs):
"""
TOPS data for a symbol or list of symbols.
TOPS provides IEX's aggregated be... | 0.887984 | 0.572962 |
import functools
class Player:
def __init__(self, position):
self.position = position
self.score = 0
def move(self, steps: int):
self.position += steps
while self.position > 10:
self.position -= 10
self.score += self.position
class Die:
def __init__(s... | aoc/year2021/day21/day21.py | import functools
class Player:
def __init__(self, position):
self.position = position
self.score = 0
def move(self, steps: int):
self.position += steps
while self.position > 10:
self.position -= 10
self.score += self.position
class Die:
def __init__(s... | 0.470737 | 0.268507 |
from contextlib import contextmanager
import logging
import time
from typing import Callable
from threading import current_thread, Event
from brightside.command_processor import CommandProcessor, Request
from brightside.channels import Channel
from brightside.exceptions import ChannelFailureException, ConfigurationExc... | brightside/message_pump.py | from contextlib import contextmanager
import logging
import time
from typing import Callable
from threading import current_thread, Event
from brightside.command_processor import CommandProcessor, Request
from brightside.channels import Channel
from brightside.exceptions import ChannelFailureException, ConfigurationExc... | 0.668447 | 0.070528 |
from __future__ import absolute_import
import pytest
import yaml
from collections import namedtuple
from datacube.drivers import new_datasource, reader_drivers, writer_drivers
from datacube.drivers import index_drivers, index_driver_by_name
from datacube.drivers.indexes import IndexDriverCache
from datacube.storage.s... | tests/test_driver.py | from __future__ import absolute_import
import pytest
import yaml
from collections import namedtuple
from datacube.drivers import new_datasource, reader_drivers, writer_drivers
from datacube.drivers import index_drivers, index_driver_by_name
from datacube.drivers.indexes import IndexDriverCache
from datacube.storage.s... | 0.550607 | 0.425784 |
from __future__ import absolute_import
import tests
import vcr as base_vcr
from tests.weibos import weibo2
from weibo_exporter import WeiboExporter, WeiboStatusTable
from datetime import datetime
import os
import tempfile
import shutil
vcr = base_vcr.VCR(
cassette_library_dir='tests/fixtures',
record_mode='on... | tests/test_weibo_exporter.py |
from __future__ import absolute_import
import tests
import vcr as base_vcr
from tests.weibos import weibo2
from weibo_exporter import WeiboExporter, WeiboStatusTable
from datetime import datetime
import os
import tempfile
import shutil
vcr = base_vcr.VCR(
cassette_library_dir='tests/fixtures',
record_mode='on... | 0.452052 | 0.291371 |
from tests.util import pick_ray
from pyrosetta import Pose
from pyrosetta.rosetta.core.import_pose import pose_from_pdbstring
name = "LYS"
contents = """
ATOM 1 N ALA A 1 0.000 0.000 0.000 1.00 0.00 N
ATOM 2 CA ALA A 1 1.458 0.000 0.000 1.00 0.00 C
ATOM ... | tests/data/residues/LYS.py | from tests.util import pick_ray
from pyrosetta import Pose
from pyrosetta.rosetta.core.import_pose import pose_from_pdbstring
name = "LYS"
contents = """
ATOM 1 N ALA A 1 0.000 0.000 0.000 1.00 0.00 N
ATOM 2 CA ALA A 1 1.458 0.000 0.000 1.00 0.00 C
ATOM ... | 0.482185 | 0.317311 |
import json
import re
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.forms.fields import *
from django.forms.forms import Form
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.utils.translation import uge... | corehq/apps/sms/forms.py | import json
import re
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.forms.fields import *
from django.forms.forms import Form
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.utils.translation import uge... | 0.467575 | 0.093927 |
from marshmallow import Schema, fields
from pyramid.security import Allow, Everyone
from sqlalchemy import (
Boolean,
Column,
DateTime,
Integer,
Binary,
String,
Text,
Unicode,
ForeignKey
)
from sqlalchemy.ext.declarative import ( AbstractConcreteBase, declarative_base, declared_at... | titledb/models.py | from marshmallow import Schema, fields
from pyramid.security import Allow, Everyone
from sqlalchemy import (
Boolean,
Column,
DateTime,
Integer,
Binary,
String,
Text,
Unicode,
ForeignKey
)
from sqlalchemy.ext.declarative import ( AbstractConcreteBase, declarative_base, declared_at... | 0.44071 | 0.148757 |
import sys
import os
import math
from sklearn import datasets
import matplotlib.pyplot as plt
import numpy as np
# Import helper functions
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, dir_path + "/../utils")
from data_manipulation import train_test_split, categorical_to_binary, normalize, ... | supervised_learning/perceptron.py | import sys
import os
import math
from sklearn import datasets
import matplotlib.pyplot as plt
import numpy as np
# Import helper functions
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, dir_path + "/../utils")
from data_manipulation import train_test_split, categorical_to_binary, normalize, ... | 0.688783 | 0.563378 |
from __future__ import print_function
import csv
import os
import cdms2
import cdutil
import numpy
import scipy.io
from e3sm_diags.driver import utils
from e3sm_diags.logger import custom_logger
from e3sm_diags.plot.cartopy.streamflow_plot import (
plot_annual_map,
plot_annual_scatter,
plot_seasonality_m... | e3sm_diags/driver/streamflow_driver.py | from __future__ import print_function
import csv
import os
import cdms2
import cdutil
import numpy
import scipy.io
from e3sm_diags.driver import utils
from e3sm_diags.logger import custom_logger
from e3sm_diags.plot.cartopy.streamflow_plot import (
plot_annual_map,
plot_annual_scatter,
plot_seasonality_m... | 0.715821 | 0.476214 |
from cryptlex.lexfloatclient.lexfloatstatus_codes import LexFloatStatusCodes
class LexFloatClientException(Exception):
def __init__(self, code):
super(LexFloatClientException, self).__init__(
LexFloatClientException.get_error_message(code))
self.message = LexFloatClientException.get_er... | cryptlex/lexfloatclient/lexfloatclient_exception.py | from cryptlex.lexfloatclient.lexfloatstatus_codes import LexFloatStatusCodes
class LexFloatClientException(Exception):
def __init__(self, code):
super(LexFloatClientException, self).__init__(
LexFloatClientException.get_error_message(code))
self.message = LexFloatClientException.get_er... | 0.735071 | 0.197039 |
import unittest
import os
from osgeo import gdal
import numpy as np
from qgis.core import (QgsVectorLayer,
QgsRasterLayer,
QgsProcessingParameterField,
QgsProcessingFeedback,
QgsProcessingContext)
from los_tools.tools.tool_re... | los_tools/test/tools/test_tool_replace_raster_values.py | import unittest
import os
from osgeo import gdal
import numpy as np
from qgis.core import (QgsVectorLayer,
QgsRasterLayer,
QgsProcessingParameterField,
QgsProcessingFeedback,
QgsProcessingContext)
from los_tools.tools.tool_re... | 0.672547 | 0.406391 |
"""Conll training algorithm"""
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
import numpy as np
import torch
import torch.nn as nn
import torch.utils.data
class Model(nn.Module):
def __init__(self, vocab_size, embedding_dim, H1, H2... | neuralcoref/train/model.py | """Conll training algorithm"""
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
import numpy as np
import torch
import torch.nn as nn
import torch.utils.data
class Model(nn.Module):
def __init__(self, vocab_size, embedding_dim, H1, H2... | 0.907125 | 0.361503 |
import re
import unittest
from unittest.mock import patch
import bucky3.prometheus as prometheus
def prometheus_verify(prometheus_module, expected_values):
line_pattern = re.compile('^([^\{\s]+)({(\S+)})*\s+(\S+)(\s+(\S+))*$')
label_pattern = re.compile('^([^=]+)=\"(.+)\"$')
page = prometheus_module.get_p... | tests/test_prometheus.py | import re
import unittest
from unittest.mock import patch
import bucky3.prometheus as prometheus
def prometheus_verify(prometheus_module, expected_values):
line_pattern = re.compile('^([^\{\s]+)({(\S+)})*\s+(\S+)(\s+(\S+))*$')
label_pattern = re.compile('^([^=]+)=\"(.+)\"$')
page = prometheus_module.get_p... | 0.498291 | 0.602646 |
import pytest
import numpy as np
from GPdoemd.models import Model
"""
SET UP MODEL ONCE
"""
def f (x, p, grad=False):
if not grad:
return x * p
return x * p, np.array([[x[0],0],[0,x[1]]])
E = 2
d = {
'name': 'testmodel',
'call': f,
'dim_x': E,
'dim_p': E,
'num_outputs... | tests/test_models/test_model.py | import pytest
import numpy as np
from GPdoemd.models import Model
"""
SET UP MODEL ONCE
"""
def f (x, p, grad=False):
if not grad:
return x * p
return x * p, np.array([[x[0],0],[0,x[1]]])
E = 2
d = {
'name': 'testmodel',
'call': f,
'dim_x': E,
'dim_p': E,
'num_outputs... | 0.378229 | 0.694678 |
import os
#os.chdir('your project folder')
import pandas as pd
import csv as csv
import glob
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
from datetime import date
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.plotly as py
i... | Code/Final_serf.py | import os
#os.chdir('your project folder')
import pandas as pd
import csv as csv
import glob
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
from datetime import date
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.plotly as py
i... | 0.252108 | 0.152001 |
from stix_shifter_modules.carbonblack.entry_point import EntryPoint
import json
import logging
import unittest
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
entry_point = EntryPoint()
data_source = {
"type": "identity",
"id": "identity--3532c56d-ea72-48be-a2ad-1a53f4c9c6d3",
"name"... | stix_shifter_modules/carbonblack/tests/stix_translation/test_carbonblack_json_to_stix.py | from stix_shifter_modules.carbonblack.entry_point import EntryPoint
import json
import logging
import unittest
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
entry_point = EntryPoint()
data_source = {
"type": "identity",
"id": "identity--3532c56d-ea72-48be-a2ad-1a53f4c9c6d3",
"name"... | 0.291586 | 0.237311 |
import re
import os
import cv2
import pdb
import glob
import pandas
import argparse
import numpy as np
from tqdm import tqdm
from functools import partial
from multiprocessing import Pool
# Check Pytorch installation
import torch, torchvision
print('torch version:', torch.__version__, torch.cuda.is_avail... | preprocess/dataset_preprocess_keypoint.py | import re
import os
import cv2
import pdb
import glob
import pandas
import argparse
import numpy as np
from tqdm import tqdm
from functools import partial
from multiprocessing import Pool
# Check Pytorch installation
import torch, torchvision
print('torch version:', torch.__version__, torch.cuda.is_avail... | 0.468304 | 0.129871 |
import os
import sys
from unittest import TestCase
import requests
class WebTestCase(TestCase):
def __init__(self, methodName):
"""测试网页搜索
本测试用于测试BaiduSpider.`search_web`
"""
super().__init__(methodName)
def setUp(self):
# 导入包
sys.path.append(os.path.abspath('.... | baiduspider/tests/test_web.py | import os
import sys
from unittest import TestCase
import requests
class WebTestCase(TestCase):
def __init__(self, methodName):
"""测试网页搜索
本测试用于测试BaiduSpider.`search_web`
"""
super().__init__(methodName)
def setUp(self):
# 导入包
sys.path.append(os.path.abspath('.... | 0.253306 | 0.250523 |
from cached_property import cached_property
from onegov.core.utils import normalize_for_url
from onegov.election_day import _
from onegov.election_day.layouts.detail import DetailLayout
from onegov.election_day.utils import pdf_filename
from onegov.election_day.utils import svg_filename
class VoteLayout(DetailLayout)... | src/onegov/election_day/layouts/vote.py | from cached_property import cached_property
from onegov.core.utils import normalize_for_url
from onegov.election_day import _
from onegov.election_day.layouts.detail import DetailLayout
from onegov.election_day.utils import pdf_filename
from onegov.election_day.utils import svg_filename
class VoteLayout(DetailLayout)... | 0.838217 | 0.134349 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth'
}
class FixedBatchNorm(nn.BatchNorm2d):
def forward(self, input):
return F.batch_norm(input, self.runnin... | net/resnet50.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth'
}
class FixedBatchNorm(nn.BatchNorm2d):
def forward(self, input):
return F.batch_norm(input, self.runnin... | 0.927626 | 0.569314 |
import socket
import struct
import time
import logging
import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
LOGIN_TEMPLATE = b'\xa0\x00\x00\x60%b\x00\x00\x00%b%b%b%b\x04\x01\x00\x00\x00\x00\xa1\xaa%b&&%b\x00Random:%b\r\n\r\n'
GET_SERIAL = b'\xa4\x00\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00\x00\x00\x0... | utils/dahua.py | import socket
import struct
import time
import logging
import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
LOGIN_TEMPLATE = b'\xa0\x00\x00\x60%b\x00\x00\x00%b%b%b%b\x04\x01\x00\x00\x00\x00\xa1\xaa%b&&%b\x00Random:%b\r\n\r\n'
GET_SERIAL = b'\xa4\x00\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00\x00\x00\x0... | 0.103737 | 0.346624 |
from __future__ import absolute_import, print_function
import logging
import six
from django.http import HttpResponse
from django.utils import timezone
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View
from sentry.mod... | src/sentry/web/frontend/oauth_token.py | from __future__ import absolute_import, print_function
import logging
import six
from django.http import HttpResponse
from django.utils import timezone
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View
from sentry.mod... | 0.437343 | 0.043346 |
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
class Toplevel1:
def __init__(self):
'''This class configures and populates the toplevel window.
top is th... | telaCalculadora.py |
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
class Toplevel1:
def __init__(self):
'''This class configures and populates the toplevel window.
top is th... | 0.338296 | 0.122733 |
""" VoicePlay track handling module """
import re
from voiceplay.database import voiceplaydb
class TrackNormalizer(object):
"""
Normalize tracks, check their status, etc
"""
keywords = ['karaoke', 'djfm toronto ids', 'djfm ids', 'djfm ottawa', '@paulburyradio']
@classmethod
def track_ok(cls,... | voiceplay/utils/track.py | """ VoicePlay track handling module """
import re
from voiceplay.database import voiceplaydb
class TrackNormalizer(object):
"""
Normalize tracks, check their status, etc
"""
keywords = ['karaoke', 'djfm toronto ids', 'djfm ids', 'djfm ottawa', '@paulburyradio']
@classmethod
def track_ok(cls,... | 0.504883 | 0.226527 |
def parse_source_value(value):
if type(value) is str:
value: str
if value.replace('.', '', 1).replace('-', '', 1).isdecimal():
return float(value) if '.' in value else int(value)
return 0
else:
return value
def parse_int_vector(string):
return [parse_source_valu... | blender_bindings/source1/bsp/entities/bms_entity_classes.py | def parse_source_value(value):
if type(value) is str:
value: str
if value.replace('.', '', 1).replace('-', '', 1).isdecimal():
return float(value) if '.' in value else int(value)
return 0
else:
return value
def parse_int_vector(string):
return [parse_source_valu... | 0.637482 | 0.27941 |
import sqlite3
from tkinter import *
from tkinter import ttk
from PIL import ImageTk,Image
from tkinter import messagebox
import sqlite3
def bookRegister():
bid = bookInfo1.get()
title = bookInfo2.get()
author = bookInfo3.get()
status =selected.get()
if bid =="" or title ==""... | AddBook.py | import sqlite3
from tkinter import *
from tkinter import ttk
from PIL import ImageTk,Image
from tkinter import messagebox
import sqlite3
def bookRegister():
bid = bookInfo1.get()
title = bookInfo2.get()
author = bookInfo3.get()
status =selected.get()
if bid =="" or title ==""... | 0.216425 | 0.081191 |
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
result_mat = []
s_mat = []
arr_res = []
s_len = len(nums)
# sort the nums
nums.sort()
# cre... | 18.4-sum.py | class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
result_mat = []
s_mat = []
arr_res = []
s_len = len(nums)
# sort the nums
nums.sort()
# cre... | 0.297368 | 0.518485 |
import lvsfunc as lvf
import vapoursynth as vs
from lvsfunc.types import Range
from typing import Tuple, Union, List, Sequence, Optional, Dict, Any
from vsutil import depth as vdepth, get_depth, disallow_variable_format
@disallow_variable_format
def replace_squaremask(
clipa: vs.VideoNode, clipb: vs.VideoNode, ma... | stgfunc/utils.py | import lvsfunc as lvf
import vapoursynth as vs
from lvsfunc.types import Range
from typing import Tuple, Union, List, Sequence, Optional, Dict, Any
from vsutil import depth as vdepth, get_depth, disallow_variable_format
@disallow_variable_format
def replace_squaremask(
clipa: vs.VideoNode, clipb: vs.VideoNode, ma... | 0.88642 | 0.677434 |
import torch
import numpy as np
from logger.terminal_utils import ExperimentArgParse, logout
import models.standard_models as std_models
import pdb
class SizeEstimator(object):
def __init__(self, args, input_size=(1, 1, 32, 32), bits=32):
'''
Estimates the size of PyTorch models in memory
... | models/pytorch_modelsize.py | import torch
import numpy as np
from logger.terminal_utils import ExperimentArgParse, logout
import models.standard_models as std_models
import pdb
class SizeEstimator(object):
def __init__(self, args, input_size=(1, 1, 32, 32), bits=32):
'''
Estimates the size of PyTorch models in memory
... | 0.611382 | 0.338323 |
from impact.tests.api_test_case import APITestCase
from impact.tests.utils import assert_data_is_consistent_with_instance
from impact.tests.factories import CriterionFactory
from impact.v1.views import CriterionDetailView
from impact.v1.views.utils import valid_keys_note
from django.urls import reverse
class TestCrit... | web/impact/impact/tests/test_criterion_detail_view.py | from impact.tests.api_test_case import APITestCase
from impact.tests.utils import assert_data_is_consistent_with_instance
from impact.tests.factories import CriterionFactory
from impact.v1.views import CriterionDetailView
from impact.v1.views.utils import valid_keys_note
from django.urls import reverse
class TestCrit... | 0.677794 | 0.277383 |
import sys
import time
import pickle
import requests
from github import Github, GithubException
from common import get_credentials
step_size = 100
search_phrase = '"from astropy" import OR "import astropy"'
username, password = get_credentials()
gh = Github(username, password)
total_repo = gh.search_code(search_ph... | astropy_usage.py | import sys
import time
import pickle
import requests
from github import Github, GithubException
from common import get_credentials
step_size = 100
search_phrase = '"from astropy" import OR "import astropy"'
username, password = get_credentials()
gh = Github(username, password)
total_repo = gh.search_code(search_ph... | 0.154376 | 0.078501 |
import sys
from PySide2.QtCore import QAbstractListModel, Qt, QModelIndex
from PySide2.QtGui import QColor, QPixmap, QIcon
from PySide2.QtWidgets import QApplication, QListView, QComboBox, QTreeView, QTableView
class PalletListModel(QAbstractListModel):
"""
It'll receive a list of colors and a parent
""... | model_view_interactions/custom_model.py | import sys
from PySide2.QtCore import QAbstractListModel, Qt, QModelIndex
from PySide2.QtGui import QColor, QPixmap, QIcon
from PySide2.QtWidgets import QApplication, QListView, QComboBox, QTreeView, QTableView
class PalletListModel(QAbstractListModel):
"""
It'll receive a list of colors and a parent
""... | 0.499023 | 0.364438 |
from typing import Optional, List
from ...modelclass import modelclass
@modelclass
class SipMapping:
"Contains data for a mapping to a symbol for each SIP that has a given condition."
CTA: Optional[str] = None
OPRA: Optional[str] = None
UTP: Optional[str] = None
@staticmethod
def from_dict(d)... | polygon/rest/models/conditions.py | from typing import Optional, List
from ...modelclass import modelclass
@modelclass
class SipMapping:
"Contains data for a mapping to a symbol for each SIP that has a given condition."
CTA: Optional[str] = None
OPRA: Optional[str] = None
UTP: Optional[str] = None
@staticmethod
def from_dict(d)... | 0.923786 | 0.442215 |
import time
from absl import logging
import six
from google.appengine.api import apiproxy_stub_map
from google.appengine.api import memcache
from google.appengine.api.memcache import memcache_stub
from google.appengine.runtime import apiproxy_errors
from absl.testing import absltest
if six.PY3:
long = int
class... | tests/google/appengine/api/memcache/memcache_unavailable_unittest.py | import time
from absl import logging
import six
from google.appengine.api import apiproxy_stub_map
from google.appengine.api import memcache
from google.appengine.api.memcache import memcache_stub
from google.appengine.runtime import apiproxy_errors
from absl.testing import absltest
if six.PY3:
long = int
class... | 0.707203 | 0.265595 |