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 __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import os.path
import numpy as np
import tensorflow as tf
from config import *
from nets import *
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('dataset', 'KITTI',
... | src/demo_tk.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import os.path
import numpy as np
import tensorflow as tf
from config import *
from nets import *
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('dataset', 'KITTI',
... | 0.708515 | 0.127598 |
import lightgbm as lgb
import numpy as np
from sklearn.metrics import mean_squared_error
import copy
import itertools
class Constraint_GA2M:
"""
Our proposed model CGA2M+.
Attributes
----------
X_train : numpy.ndarray
y_train : numpy.ndarray
y_train_mean : numpy.ndarray
X_test : numpy... | src/CGA2M_plus/cga2m.py | import lightgbm as lgb
import numpy as np
from sklearn.metrics import mean_squared_error
import copy
import itertools
class Constraint_GA2M:
"""
Our proposed model CGA2M+.
Attributes
----------
X_train : numpy.ndarray
y_train : numpy.ndarray
y_train_mean : numpy.ndarray
X_test : numpy... | 0.840029 | 0.646739 |
import time
from natsort import natsorted
from cm_client.rest import ApiException
import cm_client
from ansible.module_utils.basic import AnsibleModule
ANSIBLE_METADATA = {
"metadata_version": "1.0",
"supported_by": "community",
"status": ["preview"],
"version": "1.1.0"
}
def build_module():
fie... | cloudera_parcel.py |
import time
from natsort import natsorted
from cm_client.rest import ApiException
import cm_client
from ansible.module_utils.basic import AnsibleModule
ANSIBLE_METADATA = {
"metadata_version": "1.0",
"supported_by": "community",
"status": ["preview"],
"version": "1.1.0"
}
def build_module():
fie... | 0.454714 | 0.124479 |
import torch
from torch_mlir_torchscript.e2e_test.framework import TestUtils
from torch_mlir_torchscript.e2e_test.registry import register_test_case
from torch_mlir_torchscript.annotations import annotate_args, export
# TODO: Support scalar !torch.int/!torch.float variants. Add support to
# ReduceOpVariants to imple... | frontends/pytorch/e2e_testing/torchscript/elementwise.py |
import torch
from torch_mlir_torchscript.e2e_test.framework import TestUtils
from torch_mlir_torchscript.e2e_test.registry import register_test_case
from torch_mlir_torchscript.annotations import annotate_args, export
# TODO: Support scalar !torch.int/!torch.float variants. Add support to
# ReduceOpVariants to imple... | 0.799011 | 0.616359 |
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.core.cache import cache
from django.utils.translation import ugettext_lazy as _
from cms.plugins.teaser.models import Teaser
from cms.plugins.text.settings import USE_TINYMCE
from django.forms.fields import CharField
from djan... | cms/plugins/teaser/cms_plugins.py | from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.core.cache import cache
from django.utils.translation import ugettext_lazy as _
from cms.plugins.teaser.models import Teaser
from cms.plugins.text.settings import USE_TINYMCE
from django.forms.fields import CharField
from djan... | 0.436142 | 0.059346 |
import xml.etree.ElementTree as ElementTree
import xml.dom.minidom
import json
import os
from ..utils import fileutils
from ..utils.error import Error
from ..base.generator_data_storage_base import get_class_name_from_data_name
from ..base.generator_data_storage_base import get_data_list_name, get_data_name
from ..util... | mlc_tools/base/data_parser.py | import xml.etree.ElementTree as ElementTree
import xml.dom.minidom
import json
import os
from ..utils import fileutils
from ..utils.error import Error
from ..base.generator_data_storage_base import get_class_name_from_data_name
from ..base.generator_data_storage_base import get_data_list_name, get_data_name
from ..util... | 0.2587 | 0.086825 |
import queue
# Third party imports
import pandas as pd
import numpy as np
# Local application imports
def fetch_pipe_elements(pipesystem, ignore_inlets=False, ignore_outlets=False):
"""Iterates through the PipeSystem and returns a list of all PipeElements
Arguments
------------------
pipesystem : P... | lyteflow/util.py | import queue
# Third party imports
import pandas as pd
import numpy as np
# Local application imports
def fetch_pipe_elements(pipesystem, ignore_inlets=False, ignore_outlets=False):
"""Iterates through the PipeSystem and returns a list of all PipeElements
Arguments
------------------
pipesystem : P... | 0.851475 | 0.509215 |
import numpy as np
import fourvector as fv
import metric as mt
def test_fourvector():
metric = mt.minkowski()
# Check operators
v1 = fv.fourvector([1,0,0,0], metric)
v2 = fv.fourvector([0,1,0,0], metric)
assert(np.allclose((v1+v2).vector, [1,1,0,0])), "Unexpected result"
assert(np.allclose((v1-v2).vector... | src/python/fourvector_tests.py | import numpy as np
import fourvector as fv
import metric as mt
def test_fourvector():
metric = mt.minkowski()
# Check operators
v1 = fv.fourvector([1,0,0,0], metric)
v2 = fv.fourvector([0,1,0,0], metric)
assert(np.allclose((v1+v2).vector, [1,1,0,0])), "Unexpected result"
assert(np.allclose((v1-v2).vector... | 0.807499 | 0.743261 |
import argparse
import logging
import os
import sys
import logzero
from logzero import logger
from idoit import __version__
from .common import run_nocmd
from .check import setup_argparse as setup_argparse_check
from .check import run as run_check
from .constants import setup_argparse as setup_argparse_constants
fro... | idoit/__main__.py |
import argparse
import logging
import os
import sys
import logzero
from logzero import logger
from idoit import __version__
from .common import run_nocmd
from .check import setup_argparse as setup_argparse_check
from .check import run as run_check
from .constants import setup_argparse as setup_argparse_constants
fro... | 0.457621 | 0.143038 |
import argparse
import os
import shlex
import sys
from . import VERSION_LIST, SFFTK_MIGRATIONS_VERSION
from .core import get_output_name, get_source_version, list_versions
from .migrate import do_migration
from .utils import _print
def parse_args(args, use_shlex=True):
"""Perform argument parsing as well as
... | sfftk_migrate/main.py | import argparse
import os
import shlex
import sys
from . import VERSION_LIST, SFFTK_MIGRATIONS_VERSION
from .core import get_output_name, get_source_version, list_versions
from .migrate import do_migration
from .utils import _print
def parse_args(args, use_shlex=True):
"""Perform argument parsing as well as
... | 0.302185 | 0.171165 |
import copy
import math
from typing import Tuple
import numpy as np
import torch
try:
import cv2
except ImportError:
_HAS_CV2 = False
else:
_HAS_CV2 = True
def uniform_temporal_subsample(
x: torch.Tensor, num_samples: int, temporal_dim: int = -3
) -> torch.Tensor:
"""
Uniformly subsamples ... | pytorchvideo/pytorchvideo/transforms/functional.py |
import copy
import math
from typing import Tuple
import numpy as np
import torch
try:
import cv2
except ImportError:
_HAS_CV2 = False
else:
_HAS_CV2 = True
def uniform_temporal_subsample(
x: torch.Tensor, num_samples: int, temporal_dim: int = -3
) -> torch.Tensor:
"""
Uniformly subsamples ... | 0.941969 | 0.722282 |
import json
import os
import sys
from collections import OrderedDict
from unittest import mock
import pytest
from saltfactories.factories.base import SaltCliFactory
from saltfactories.utils.processes import ProcessResult
@pytest.fixture
def config_dir(testdir):
_conf_dir = testdir.mkdir("conf")
yield _conf_... | tests/unit/factories/base/test_salt_cli_factory.py | import json
import os
import sys
from collections import OrderedDict
from unittest import mock
import pytest
from saltfactories.factories.base import SaltCliFactory
from saltfactories.utils.processes import ProcessResult
@pytest.fixture
def config_dir(testdir):
_conf_dir = testdir.mkdir("conf")
yield _conf_... | 0.291082 | 0.20199 |
from overrides import overrides
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from claf.decorator import register
from claf.model.base import ModelWithTokenEmbedder
from claf.model.sequence_classification.mixin import SequenceClassification
from claf.modules import functional a... | claf/model/sequence_classification/structured_self_attention.py | from overrides import overrides
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from claf.decorator import register
from claf.model.base import ModelWithTokenEmbedder
from claf.model.sequence_classification.mixin import SequenceClassification
from claf.modules import functional a... | 0.956268 | 0.492859 |
from django.test import TestCase
from mock import MagicMock, patch
from . import BillingAddressStep, ShippingStep
from ..checkout import Checkout, STORAGE_SESSION_KEY
from ..checkout.steps import BaseAddressStep
from ..userprofile.models import Address
NEW_ADDRESS = {
'first_name': 'Test',
'last_name': 'Test'... | saleor/checkout/tests.py | from django.test import TestCase
from mock import MagicMock, patch
from . import BillingAddressStep, ShippingStep
from ..checkout import Checkout, STORAGE_SESSION_KEY
from ..checkout.steps import BaseAddressStep
from ..userprofile.models import Address
NEW_ADDRESS = {
'first_name': 'Test',
'last_name': 'Test'... | 0.653238 | 0.348895 |
import json
class Renderer:
def render(self, entity):
if isinstance(entity, Report):
return self.render_report(entity)
elif isinstance(entity, Section):
return self.render_section(entity)
elif isinstance(entity, Text):
return self.render_text(entity)
... | report.py | import json
class Renderer:
def render(self, entity):
if isinstance(entity, Report):
return self.render_report(entity)
elif isinstance(entity, Section):
return self.render_section(entity)
elif isinstance(entity, Text):
return self.render_text(entity)
... | 0.45641 | 0.155591 |
from pyrogram import Client, filters
from pyrogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message
from .. import BOT_NAME, TRIGGERS as trg
from ..utils.data_parser import get_wo, get_wols
from ..utils.helper import check_user, control_user
from ..utils.db import get_collection
... | anibot/plugins/watch.py |
from pyrogram import Client, filters
from pyrogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message
from .. import BOT_NAME, TRIGGERS as trg
from ..utils.data_parser import get_wo, get_wols
from ..utils.helper import check_user, control_user
from ..utils.db import get_collection
... | 0.215351 | 0.080357 |
from os.path import isfile, dirname
from os import makedirs
import csv, functools
from time import perf_counter
import numpy as np
import torch
suffix = '_nntimes'
global_depth = None
global_sync = False
def _update_counter(module, name, value, depth):
if hasattr(module, name):
getattr(... | nntime/timing.py | from os.path import isfile, dirname
from os import makedirs
import csv, functools
from time import perf_counter
import numpy as np
import torch
suffix = '_nntimes'
global_depth = None
global_sync = False
def _update_counter(module, name, value, depth):
if hasattr(module, name):
getattr(... | 0.542621 | 0.194043 |
from unittest import TestCase
from rtreelib import RTreeGuttman, RTreeNode, RTreeEntry, Rect
from rtreelib.strategies.guttman import quadratic_split, adjust_tree_strategy
class TestGuttman(TestCase):
"""Tests for Guttman R-Tree implementation"""
def test_quadratic_split(self):
"""Ensures that a split... | tests/test_guttman.py | from unittest import TestCase
from rtreelib import RTreeGuttman, RTreeNode, RTreeEntry, Rect
from rtreelib.strategies.guttman import quadratic_split, adjust_tree_strategy
class TestGuttman(TestCase):
"""Tests for Guttman R-Tree implementation"""
def test_quadratic_split(self):
"""Ensures that a split... | 0.889223 | 0.778102 |
from first_CS import first_CS
from base_parameters import RMSD
from score import score_population
from score import change_Ligand
from Trader import select_bests
import numpy as np
import copy
def move(CS,bests):
for i in range(0,len(CS)):
f=np.random.randint(len(bests))
k=np.ran... | PSO.py | from first_CS import first_CS
from base_parameters import RMSD
from score import score_population
from score import change_Ligand
from Trader import select_bests
import numpy as np
import copy
def move(CS,bests):
for i in range(0,len(CS)):
f=np.random.randint(len(bests))
k=np.ran... | 0.100773 | 0.144994 |
import os
import json
import fnmatch
class DATSDataset(object):
def __init__(self, datasetpath):
"""
store the datsetopath and tries to find a DATS.json file
"""
if not os.path.isdir(datasetpath):
raise 'No dataset found at {}'.format(datasetpath)
self.datasetp... | app/search/models.py | import os
import json
import fnmatch
class DATSDataset(object):
def __init__(self, datasetpath):
"""
store the datsetopath and tries to find a DATS.json file
"""
if not os.path.isdir(datasetpath):
raise 'No dataset found at {}'.format(datasetpath)
self.datasetp... | 0.411939 | 0.197193 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from six.moves import xrange
from mtl.layers import dense_layer
def listify(x):
"""Convert one element into a list of that element. No-op on list inputs."""
if not isinstance... | mtl/util/common.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from six.moves import xrange
from mtl.layers import dense_layer
def listify(x):
"""Convert one element into a list of that element. No-op on list inputs."""
if not isinstance... | 0.838581 | 0.366618 |
from dataclasses import dataclass
from drhue.adapter.base import DrHueAdapter
@dataclass
class DrHueSensor(DrHueAdapter):
def __post_init__(self):
super().__post_init__()
self.motion_sensor_key, self.temp_sensor_key, self.light_sensor_key = self._get_sensor_keys()
def _get_sensor_keys(self):... | wip/drhue/adapter/sensor.py | from dataclasses import dataclass
from drhue.adapter.base import DrHueAdapter
@dataclass
class DrHueSensor(DrHueAdapter):
def __post_init__(self):
super().__post_init__()
self.motion_sensor_key, self.temp_sensor_key, self.light_sensor_key = self._get_sensor_keys()
def _get_sensor_keys(self):... | 0.758779 | 0.100481 |
import setuptools.command.build_py
from setuptools import find_packages, setup
# Set version_info[__version__], while avoiding importing numpy, in case numpy
# and vg are being installed concurrently.
# https://packaging.python.org/guides/single-sourcing-package-version/
version_info = {}
exec(open("meshlab_pickedpoin... | setup.py | import setuptools.command.build_py
from setuptools import find_packages, setup
# Set version_info[__version__], while avoiding importing numpy, in case numpy
# and vg are being installed concurrently.
# https://packaging.python.org/guides/single-sourcing-package-version/
version_info = {}
exec(open("meshlab_pickedpoin... | 0.460289 | 0.171859 |
import h5py
import numpy
class HDF5Storage():
"""HDF5 file for storing gridded model.
"""
def __init__(self, filename):
"""Constructor.
Args:
filename (str):
Name for HDF5 file
"""
self.filename = filename
def save_domain(self, domain):
... | geomodelgrids/create/io/hdf5.py | import h5py
import numpy
class HDF5Storage():
"""HDF5 file for storing gridded model.
"""
def __init__(self, filename):
"""Constructor.
Args:
filename (str):
Name for HDF5 file
"""
self.filename = filename
def save_domain(self, domain):
... | 0.764364 | 0.285123 |
import pytest
from nbformat.v4.nbbase import new_markdown_cell
from jupytext.cell_reader import (
RMarkdownCellReader,
LightScriptCellReader,
uncomment,
paragraph_is_fully_commented,
)
from jupytext.cell_to_text import RMarkdownCellExporter
@pytest.mark.parametrize(
"lines",
[
"# text"... | tests/test_cells.py | """
lines = text.splitlines()
cell, pos = RMarkdownCellReader().read(lines)
assert cell.cell_type == "code"
assert cell.source == "1+2+3"
assert cell.metadata == {"language": "python"}
assert lines[pos:] == []
def test_text_to_code_cell_empty_code():
text = """```{python}
"""
lines =... | 0.706089 | 0.870212 |
import numpy as np
import scipy.integrate as spi
import matplotlib.pyplot as plt
import scipy.optimize as spo
from scipy.optimize import fsolve
class friction_factor:
"""
This class computes pipe flow information based on the non-Newtonian Dodge-Metzner paper.
There is a Jupyter notebook demonstrating us... | rheoflow/friction_factor_property.py | import numpy as np
import scipy.integrate as spi
import matplotlib.pyplot as plt
import scipy.optimize as spo
from scipy.optimize import fsolve
class friction_factor:
"""
This class computes pipe flow information based on the non-Newtonian Dodge-Metzner paper.
There is a Jupyter notebook demonstrating us... | 0.759225 | 0.282586 |
from socket import *
from threading import Thread
import sys
def accept_incoming_connections():
"""Sets up handling for incoming clients."""
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
fc = open("connections_log", "a... | server.py | from socket import *
from threading import Thread
import sys
def accept_incoming_connections():
"""Sets up handling for incoming clients."""
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
fc = open("connections_log", "a... | 0.249173 | 0.050847 |
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
import constraint_analysis_tools as cat
import matplotlib.font_manager as font_manager
font_file = 'C:/Windows/Fonts/pala.ttf'
font_manager.fontManager.addfont(font_file)
sns.set_theme(style='whitegrid', font='Palatino Linotype', context='paper'... | 2 - Conceptual Design/3 - Initial Sizing/constraint_analysis.py | import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
import constraint_analysis_tools as cat
import matplotlib.font_manager as font_manager
font_file = 'C:/Windows/Fonts/pala.ttf'
font_manager.fontManager.addfont(font_file)
sns.set_theme(style='whitegrid', font='Palatino Linotype', context='paper'... | 0.455199 | 0.414543 |
__all__ = ['mean_from_cluster', 'fig2img', 'c_imshow', 'Flatten', 'conv3x3', 'get_proto_accuracy', 'get_accuracy']
# Cell
# export
import io
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
from PIL import Image
def mean_from_cluster(z, labels):
predicted_labels = labels.u... | unsupervised_meta_learning/nn_utils.py |
__all__ = ['mean_from_cluster', 'fig2img', 'c_imshow', 'Flatten', 'conv3x3', 'get_proto_accuracy', 'get_accuracy']
# Cell
# export
import io
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
from PIL import Image
def mean_from_cluster(z, labels):
predicted_labels = labels.u... | 0.959412 | 0.709145 |
from unittest import TestCase
from unittest.mock import Mock
from airena.builder import ServiceBuilder
from airena.typing import IObjectService, IDisplayService
from airena.vector import Vector2
from airena import components
class ObjectServiceTests(TestCase):
def setUp(self):
self.builder = ServiceBuil... | tests/unit/test_object.py | from unittest import TestCase
from unittest.mock import Mock
from airena.builder import ServiceBuilder
from airena.typing import IObjectService, IDisplayService
from airena.vector import Vector2
from airena import components
class ObjectServiceTests(TestCase):
def setUp(self):
self.builder = ServiceBuil... | 0.797241 | 0.569972 |
from imagepy import IPy
import numpy as np
from imagepy.core.engine import Simple, Filter
class Statistic(Simple):
title = 'Pixel Statistic 3D'
note = ['8-bit', '16-bit', 'int', 'float', 'stack3d']
para = {'nozero':False, 'max':True, 'min':True,'mean':False,'var':False,'std':False,'slice':False}
v... | imagepy/menus/Kit3D/Analysis 3D/pixelstatistic_plgs.py | from imagepy import IPy
import numpy as np
from imagepy.core.engine import Simple, Filter
class Statistic(Simple):
title = 'Pixel Statistic 3D'
note = ['8-bit', '16-bit', 'int', 'float', 'stack3d']
para = {'nozero':False, 'max':True, 'min':True,'mean':False,'var':False,'std':False,'slice':False}
v... | 0.250454 | 0.297741 |
import requests
import json
from .helper import Helper
class Costs(Helper):
def __init__(self, base_url, org_pk, teams_pk, access_token, _csrf_token, headers, pagination):
super().__init__(base_url, org_pk, teams_pk, access_token, _csrf_token, headers, pagination)
def copy_costs_fee_allocations_from... | resources/costs.py | import requests
import json
from .helper import Helper
class Costs(Helper):
def __init__(self, base_url, org_pk, teams_pk, access_token, _csrf_token, headers, pagination):
super().__init__(base_url, org_pk, teams_pk, access_token, _csrf_token, headers, pagination)
def copy_costs_fee_allocations_from... | 0.307774 | 0.187133 |
import FWCore.ParameterSet.Config as cms
from RecoVertex.BeamSpotProducer.BeamSpot_cfi import *
from L1Trigger.TrackFindingTracklet.Tracklet_cfi import *
from SimTracker.TrackTriggerAssociation.TrackTriggerAssociator_cff import *
from L1Trigger.TrackTrigger.ProducerHPH_cff import *
# prompt hybrid emulation
TTTrac... | L1Trigger/TrackFindingTracklet/python/L1HybridEmulationTracks_cff.py | import FWCore.ParameterSet.Config as cms
from RecoVertex.BeamSpotProducer.BeamSpot_cfi import *
from L1Trigger.TrackFindingTracklet.Tracklet_cfi import *
from SimTracker.TrackTriggerAssociation.TrackTriggerAssociator_cff import *
from L1Trigger.TrackTrigger.ProducerHPH_cff import *
# prompt hybrid emulation
TTTrac... | 0.360377 | 0.304688 |
import amulet
from charmhelpers.contrib.openstack.amulet.deployment import (
OpenStackAmuletDeployment
)
from charmhelpers.contrib.openstack.amulet.utils import (
OpenStackAmuletUtils,
DEBUG,
# ERROR
)
# Use DEBUG to turn on debug logging
u = OpenStackAmuletUtils(DEBUG)
class NeutronAPIBasicDeploy... | tests/basic_deployment.py |
import amulet
from charmhelpers.contrib.openstack.amulet.deployment import (
OpenStackAmuletDeployment
)
from charmhelpers.contrib.openstack.amulet.utils import (
OpenStackAmuletUtils,
DEBUG,
# ERROR
)
# Use DEBUG to turn on debug logging
u = OpenStackAmuletUtils(DEBUG)
class NeutronAPIBasicDeploy... | 0.650911 | 0.246851 |
import json
import logging
import os
from dataclasses import (
dataclass,
field
)
from typing import Optional
import pandas as pd
import torch
from nlp import Dataset
from transformers import (
MT5Tokenizer,
HfArgumentParser
)
from source.utils import dict_to_json
logger = logging.getLogger(__name__)... | source/databuilder.py | import json
import logging
import os
from dataclasses import (
dataclass,
field
)
from typing import Optional
import pandas as pd
import torch
from nlp import Dataset
from transformers import (
MT5Tokenizer,
HfArgumentParser
)
from source.utils import dict_to_json
logger = logging.getLogger(__name__)... | 0.881634 | 0.197715 |
from typing import Optional, Union, Type, List, Dict
from discord.ext import commands
import discord
from functools import wraps
from .cogs.classes import MusicRawDataForJson
from .music_player import MusicPlayer
from .cogs.music import MusicData
from .util import check_dj
def split_list(list_: list... | cogs/music/views.py |
from typing import Optional, Union, Type, List, Dict
from discord.ext import commands
import discord
from functools import wraps
from .cogs.classes import MusicRawDataForJson
from .music_player import MusicPlayer
from .cogs.music import MusicData
from .util import check_dj
def split_list(list_: list... | 0.802942 | 0.166235 |
import os
import subprocess
import sys
timeouts = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 12500, 15000, 17500, 20000]
numprocs = [4,16,32]
numcpu = 4
par_reg = 0.01
lrate = 0.0008
drate = 0.0001
exp_name = sys.argv[0][:sys.argv[0].rfind('.py')]
dim = 100
for numproc in numprocs:
timeout_s... | Scripts/stampede/synth/stampede_synth_nomad.py | import os
import subprocess
import sys
timeouts = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 12500, 15000, 17500, 20000]
numprocs = [4,16,32]
numcpu = 4
par_reg = 0.01
lrate = 0.0008
drate = 0.0001
exp_name = sys.argv[0][:sys.argv[0].rfind('.py')]
dim = 100
for numproc in numprocs:
timeout_s... | 0.08312 | 0.08882 |
from staticconf import config, proxy, readers
from staticconf.proxy import UndefToken
def register_value_proxy(namespace, value_proxy, help_text):
"""Register a value proxy with the namespace, and add the help_text."""
namespace.register_proxy(value_proxy)
config.config_help.add(
value_proxy.confi... | staticconf/getters.py | from staticconf import config, proxy, readers
from staticconf.proxy import UndefToken
def register_value_proxy(namespace, value_proxy, help_text):
"""Register a value proxy with the namespace, and add the help_text."""
namespace.register_proxy(value_proxy)
config.config_help.add(
value_proxy.confi... | 0.772187 | 0.247748 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
from nebp_flux import extract_mcnp
from cf252 import cf252_source
from group_structures import energy_groups, cosine_groups, radial_groups
import sys
sys.path.insert(0, '../')
import paths
from spectrum import Spectrum, Spectrum2D
def... | flux/plot_flux.py | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
from nebp_flux import extract_mcnp
from cf252 import cf252_source
from group_structures import energy_groups, cosine_groups, radial_groups
import sys
sys.path.insert(0, '../')
import paths
from spectrum import Spectrum, Spectrum2D
def... | 0.574514 | 0.671396 |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
long_description = """
USA Spending Python API
=======================
Python API for the numerous APIs available through [USA
Spending](http://usaspending.gov/data?carryfilters=on).
Usage
-----
>>> from usa_spendin... | setup.py | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
long_description = """
USA Spending Python API
=======================
Python API for the numerous APIs available through [USA
Spending](http://usaspending.gov/data?carryfilters=on).
Usage
-----
>>> from usa_spendin... | 0.652463 | 0.483587 |
from dash_bootstrap_components.themes import YETI
try:
#data analysis modules
import pandas as pd
import numpy as np
#dash modules
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies imp... | data dashboards/financial/app.py | from dash_bootstrap_components.themes import YETI
try:
#data analysis modules
import pandas as pd
import numpy as np
#dash modules
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies imp... | 0.406391 | 0.223356 |
import pytest
# Import Pyomo libraries
import pyomo.environ as pyo
from pyomo.environ import units as pyunits
# Import IDAES core
from idaes.core import FlowsheetBlock
from idaes.core.util.model_statistics import degrees_of_freedom
# Import Unit Model Modules
from idaes.generic_models.properties import iapws95
from i... | idaes/power_generation/unit_models/tests/test_heat_exchanger2D.py | import pytest
# Import Pyomo libraries
import pyomo.environ as pyo
from pyomo.environ import units as pyunits
# Import IDAES core
from idaes.core import FlowsheetBlock
from idaes.core.util.model_statistics import degrees_of_freedom
# Import Unit Model Modules
from idaes.generic_models.properties import iapws95
from i... | 0.636918 | 0.524151 |
def check_input_resources(resource_pool, resource_name):
import os
if resource_name not in resource_pool.keys():
err = "\n\nResource pool: %s\n\n[!] The resource '%s' is missing " \
"from the resource pool, and it is needed in one of the steps "\
"of the pipeline. Plea... | qap/workflow_utils.py | def check_input_resources(resource_pool, resource_name):
import os
if resource_name not in resource_pool.keys():
err = "\n\nResource pool: %s\n\n[!] The resource '%s' is missing " \
"from the resource pool, and it is needed in one of the steps "\
"of the pipeline. Plea... | 0.284576 | 0.137532 |
import os
from pathlib import Path
import socket
import pytest
from archive import Archive
from archive.exception import ArchiveWarning
from conftest import *
# Setup a directory with some test data to be put into an archive.
# Make sure that we have all kind of different things in there.
testdata = [
DataDir(Pat... | tests/test_03_create_filetype.py | import os
from pathlib import Path
import socket
import pytest
from archive import Archive
from archive.exception import ArchiveWarning
from conftest import *
# Setup a directory with some test data to be put into an archive.
# Make sure that we have all kind of different things in there.
testdata = [
DataDir(Pat... | 0.333069 | 0.282437 |
import numpy as np
import os
import h5py
import sys
import scipy.signal
import argparse
def minor_format(x, i=None):
return x
def main():
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
dataname='/ACST_Spectrogram'
currentname='/fit_w_current2_L'
h5fi... | KARA/f06214/f06214_spectrogram-compare.py |
import numpy as np
import os
import h5py
import sys
import scipy.signal
import argparse
def minor_format(x, i=None):
return x
def main():
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
dataname='/ACST_Spectrogram'
currentname='/fit_w_current2_L'
h5fi... | 0.315947 | 0.321673 |
import depthai as dai
import sys
import time
blType = dai.DeviceBootloader.Type.AUTO
if len(sys.argv) > 1:
if sys.argv[1] == 'usb':
blType = dai.DeviceBootloader.Type.USB
elif sys.argv[1] == 'network':
blType = dai.DeviceBootloader.Type.NETWORK
else:
print("Specify either 'usb' or ... | examples/bootloader/flash_bootloader.py |
import depthai as dai
import sys
import time
blType = dai.DeviceBootloader.Type.AUTO
if len(sys.argv) > 1:
if sys.argv[1] == 'usb':
blType = dai.DeviceBootloader.Type.USB
elif sys.argv[1] == 'network':
blType = dai.DeviceBootloader.Type.NETWORK
else:
print("Specify either 'usb' or ... | 0.21984 | 0.126488 |
import socket
import struct
from threading import Thread
from time import sleep
from bases.fl.messages import MessageTypes, ClientToServerAckMessage
from utils.save_load import dumps, loads
__all__ = ["ServerSocket", "ClientSocket"]
class Socket(socket.socket):
def recv_msg(self):
msg_len = struct.unpac... | bases/fl/sockets.py | import socket
import struct
from threading import Thread
from time import sleep
from bases.fl.messages import MessageTypes, ClientToServerAckMessage
from utils.save_load import dumps, loads
__all__ = ["ServerSocket", "ClientSocket"]
class Socket(socket.socket):
def recv_msg(self):
msg_len = struct.unpac... | 0.305076 | 0.065905 |
from os import listdir, environ
from subprocess import Popen
from typing import Tuple, List
from pathlib import Path
from glob import glob
BASE_DIR = Path("~/.cache/silverkube").expanduser()
SRC_DIR = BASE_DIR / "src"
SOURCES_DIR = BASE_DIR / "SOURCES"
BIN_DIR = BASE_DIR / "bin"
environ["GOPATH"] = str(BASE_DIR)
US... | build.py | from os import listdir, environ
from subprocess import Popen
from typing import Tuple, List
from pathlib import Path
from glob import glob
BASE_DIR = Path("~/.cache/silverkube").expanduser()
SRC_DIR = BASE_DIR / "src"
SOURCES_DIR = BASE_DIR / "SOURCES"
BIN_DIR = BASE_DIR / "bin"
environ["GOPATH"] = str(BASE_DIR)
US... | 0.315209 | 0.130175 |
from flask import Flask, render_template, request, redirect, session, url_for, Response
from bson.json_util import dumps
import datetime
import pymongo
from pymongo import MongoClient
from bson.objectid import ObjectId
import hashlib
menu = {}
f = open('menu.txt')
for i in f.readlines():
a = i.split(':')
menu[... | cafe-order-system.py | from flask import Flask, render_template, request, redirect, session, url_for, Response
from bson.json_util import dumps
import datetime
import pymongo
from pymongo import MongoClient
from bson.objectid import ObjectId
import hashlib
menu = {}
f = open('menu.txt')
for i in f.readlines():
a = i.split(':')
menu[... | 0.306942 | 0.112065 |
json = {
"full": {
"title": "L1Trigger collections (in RECO and AOD)",
"data": [
]
},
"aod": {
"title": "L1Trigger collections (in AOD only)",
"data": [
{
"instance": "l1GtRecord",
"container": "*",
"desc": "No documentation"
},
{
"instan... | Documentation/DataFormats/python/L1Trigger_dataformats.py | json = {
"full": {
"title": "L1Trigger collections (in RECO and AOD)",
"data": [
]
},
"aod": {
"title": "L1Trigger collections (in AOD only)",
"data": [
{
"instance": "l1GtRecord",
"container": "*",
"desc": "No documentation"
},
{
"instan... | 0.231527 | 0.261051 |
import json
from abc import abstractmethod, ABCMeta, abstractproperty
from contextlib import contextmanager
try:
from urllib.request import urlopen, Request
from urllib.parse import urlencode
from urllib.error import HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
fro... | kan/structures.py | import json
from abc import abstractmethod, ABCMeta, abstractproperty
from contextlib import contextmanager
try:
from urllib.request import urlopen, Request
from urllib.parse import urlencode
from urllib.error import HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
fro... | 0.675551 | 0.15059 |
import cherrypy
import os.path
import sys
import argparse
import socket
from Tkinter import *
import tkFileDialog
import server
from cherrypy.lib import static
from os import listdir
import threading
# Checks to make sure the filepath is correct and SiLaS can access it
# TODO: Add all path/permission ... | SiLaS/core/SiLaS.py | import cherrypy
import os.path
import sys
import argparse
import socket
from Tkinter import *
import tkFileDialog
import server
from cherrypy.lib import static
from os import listdir
import threading
# Checks to make sure the filepath is correct and SiLaS can access it
# TODO: Add all path/permission ... | 0.088156 | 0.084078 |
import unittest
from importasol.entorno import EntornoSOL
from importasol.db.contasol import APU, AutoAcumulador, MAE
from datetime import date
def crea_apu(**kwargs):
apu = APU()
for k, v in kwargs.iteritems():
setattr(apu, k, v)
return apu
def entorno_con_acumulador():
e = EntornoSOL()
... | tests/acumulador.py | import unittest
from importasol.entorno import EntornoSOL
from importasol.db.contasol import APU, AutoAcumulador, MAE
from datetime import date
def crea_apu(**kwargs):
apu = APU()
for k, v in kwargs.iteritems():
setattr(apu, k, v)
return apu
def entorno_con_acumulador():
e = EntornoSOL()
... | 0.468791 | 0.380529 |
from __future__ import annotations
from typing import Optional, TYPE_CHECKING, Union
# noinspection PyPackageRequirements
from pyspark.sql.types import StructType, DataType
from spark_auto_mapper_fhir.fhir_types.list import FhirList
from spark_auto_mapper_fhir.complex_types.meta import Meta
from spark_auto_mapper_fhir... | spark_auto_mapper_fhir/resources/bundle.py | from __future__ import annotations
from typing import Optional, TYPE_CHECKING, Union
# noinspection PyPackageRequirements
from pyspark.sql.types import StructType, DataType
from spark_auto_mapper_fhir.fhir_types.list import FhirList
from spark_auto_mapper_fhir.complex_types.meta import Meta
from spark_auto_mapper_fhir... | 0.903954 | 0.253618 |
import abc
import pytest
import reframe.core.launchers as launchers
from reframe.core.backends import getlauncher
from reframe.core.schedulers import Job, JobScheduler
@pytest.fixture(params=[
'alps', 'launcherwrapper', 'local', 'mpiexec',
'mpirun', 'srun', 'srunalloc', 'ssh', 'upcrun', 'upcxx-run'
])
def l... | unittests/test_launchers.py |
import abc
import pytest
import reframe.core.launchers as launchers
from reframe.core.backends import getlauncher
from reframe.core.schedulers import Job, JobScheduler
@pytest.fixture(params=[
'alps', 'launcherwrapper', 'local', 'mpiexec',
'mpirun', 'srun', 'srunalloc', 'ssh', 'upcrun', 'upcxx-run'
])
def l... | 0.509032 | 0.164987 |
from __future__ import annotations
import collections.abc
from abc import ABCMeta
from typing import TYPE_CHECKING, Optional, Union, Type, List, Iterator, Iterable, Any
from pyrtable._baseandtable import _BaseAndTableProtocol, BaseAndTable
from pyrtable.fields import BaseField
if TYPE_CHECKING:
from pyrtable.re... | src/pyrtable/fields/recordlink.py | from __future__ import annotations
import collections.abc
from abc import ABCMeta
from typing import TYPE_CHECKING, Optional, Union, Type, List, Iterator, Iterable, Any
from pyrtable._baseandtable import _BaseAndTableProtocol, BaseAndTable
from pyrtable.fields import BaseField
if TYPE_CHECKING:
from pyrtable.re... | 0.786254 | 0.142143 |
from unittest import mock
from dimensigon import defaults
from dimensigon.domain.entities import Vault
from dimensigon.domain.entities.user import ROOT, User, JOIN
from dimensigon.utils.helpers import get_now
from dimensigon.web import db
from tests.base import TestDimensigonBase
class TestVault(TestDimensigonBase):... | tests/unit/domain/entities/test_vault.py | from unittest import mock
from dimensigon import defaults
from dimensigon.domain.entities import Vault
from dimensigon.domain.entities.user import ROOT, User, JOIN
from dimensigon.utils.helpers import get_now
from dimensigon.web import db
from tests.base import TestDimensigonBase
class TestVault(TestDimensigonBase):... | 0.708213 | 0.393851 |
from model_manager import ModelManager
import tensorflow as tf
from utils import to_numpy, save_samples
import numpy as np
import pickle
import os
from time import time
class Stage2Trainer(ModelManager):
def __init__(self, stg2_data_dir, devices_to_use, model_dir, data_dir, results_dir, model_config, schedule_conf... | code/train_stg2.py | from model_manager import ModelManager
import tensorflow as tf
from utils import to_numpy, save_samples
import numpy as np
import pickle
import os
from time import time
class Stage2Trainer(ModelManager):
def __init__(self, stg2_data_dir, devices_to_use, model_dir, data_dir, results_dir, model_config, schedule_conf... | 0.566618 | 0.228372 |
u"""
Copyright 2021 Telefónica Investigación y Desarrollo, S.A.U.
This file is part of Toolium.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unles... | toolium/utils/dataset.py | u"""
Copyright 2021 Telefónica Investigación y Desarrollo, S.A.U.
This file is part of Toolium.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unles... | 0.62601 | 0.42316 |
import sys, math
def parse_vec3(line):
return [float(line[1]), float(line[2]), float(line[3])]
def parse_vec2(line):
return [float(line[1]), float(line[2])]
def norm(vec):
l = math.sqrt(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2])
if l != 0.0:
return [vec[0] / l, vec[1] / l, vec[2] / l]
return ... | model_converter.py | import sys, math
def parse_vec3(line):
return [float(line[1]), float(line[2]), float(line[3])]
def parse_vec2(line):
return [float(line[1]), float(line[2])]
def norm(vec):
l = math.sqrt(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2])
if l != 0.0:
return [vec[0] / l, vec[1] / l, vec[2] / l]
return ... | 0.146484 | 0.490175 |
import json
from flask import Blueprint
from flask import request
from flask_atomic.query.buffer import QueryBuffer
from ..orm.helpers import getschema
from ..orm.helpers import serialize
from flask_atomic.http.responses import HTTPSuccess
from flask_atomic.http.responses import HTTPCreated
from flask_atomic.http.re... | _dump/builder/routes.py | import json
from flask import Blueprint
from flask import request
from flask_atomic.query.buffer import QueryBuffer
from ..orm.helpers import getschema
from ..orm.helpers import serialize
from flask_atomic.http.responses import HTTPSuccess
from flask_atomic.http.responses import HTTPCreated
from flask_atomic.http.re... | 0.604399 | 0.091666 |
import numpy as np
import os
import logging
import torch
from tqdm.auto import tqdm
from torch.nn.parallel import DistributedDataParallel as DDP
import torch.multiprocessing as mp
from LanguageModels.SpeedyModel import SpeedyModelForRec
from LanguageModels.configuration_tnlrv3 import TuringNLRv3Config
from .utils im... | speedy/test_auc.py |
import numpy as np
import os
import logging
import torch
from tqdm.auto import tqdm
from torch.nn.parallel import DistributedDataParallel as DDP
import torch.multiprocessing as mp
from LanguageModels.SpeedyModel import SpeedyModelForRec
from LanguageModels.configuration_tnlrv3 import TuringNLRv3Config
from .utils im... | 0.497315 | 0.235636 |
import sys
import csv
import re
#Opens database and reads it into memory
with open(sys.argv[1], newline='') as f:
reader = csv.reader(f)
suspectlist = list(reader)
#Opens sequences and reads it into memory
with open(sys.argv[2], 'r') as f:
dna = f.readlines()
dnalist = []
#below lines are taking dna's a... | pset6/dna/dna.py | import sys
import csv
import re
#Opens database and reads it into memory
with open(sys.argv[1], newline='') as f:
reader = csv.reader(f)
suspectlist = list(reader)
#Opens sequences and reads it into memory
with open(sys.argv[2], 'r') as f:
dna = f.readlines()
dnalist = []
#below lines are taking dna's a... | 0.053812 | 0.370112 |
import json
from urllib.parse import urlencode
from http.client import HTTPResponse
from hubspot3.base import BaseClient
from hubspot3.error import HubspotNotFound, HubspotServerError
from typing import Dict
FORMS_API_VERSION = 2
class FormSubmissionClient(BaseClient):
"""allows acccess to submit forms via the ... | hubspot3/forms.py | import json
from urllib.parse import urlencode
from http.client import HTTPResponse
from hubspot3.base import BaseClient
from hubspot3.error import HubspotNotFound, HubspotServerError
from typing import Dict
FORMS_API_VERSION = 2
class FormSubmissionClient(BaseClient):
"""allows acccess to submit forms via the ... | 0.77949 | 0.108095 |
from data import CoverabilityInstance, Transition, Interval
from mister.ast import Constraint
from mister.data import ReachabilityInstance
def build_problem_instance(program_node):
'''
Process node of the form Program(variables, rules, initial, target, invariants)
'''
variables, n, var_ids = get_varia... | src/mister/builder.py | from data import CoverabilityInstance, Transition, Interval
from mister.ast import Constraint
from mister.data import ReachabilityInstance
def build_problem_instance(program_node):
'''
Process node of the form Program(variables, rules, initial, target, invariants)
'''
variables, n, var_ids = get_varia... | 0.439747 | 0.44065 |
from contextlib import closing
from pathlib import Path
from sqlalchemy.orm import Session
from config.constants import (ARTIFACTS_PATH, ACCURACY_CONFIGURATION_FILE_NAME,
JOB_SCRIPT_NAME, JOBS_SCRIPTS_FOLDER_NAME, ACCURACY_ARTIFACTS_FOLDER,
DATASET_ANNOTATIO... | wb/main/jobs/accuracy_analysis/annotate_datset/create_annotate_dataset_bundle_job.py | from contextlib import closing
from pathlib import Path
from sqlalchemy.orm import Session
from config.constants import (ARTIFACTS_PATH, ACCURACY_CONFIGURATION_FILE_NAME,
JOB_SCRIPT_NAME, JOBS_SCRIPTS_FOLDER_NAME, ACCURACY_ARTIFACTS_FOLDER,
DATASET_ANNOTATIO... | 0.457621 | 0.102709 |
import re
import datetime
from datetime import timezone
MONTHS = {
'jan': 1,
'feb': 2,
'mar': 3,
'apr': 4,
'may': 5,
'jun': 6,
'jul': 7,
'aug': 8,
'sep': 9,
'oct': 10,
'nov': 11,
'dec': 12
}
def parse_time(line, now=None):
# Regex to read Unix, NetWare and NetPresen... | ftpparser/parse_time.py | import re
import datetime
from datetime import timezone
MONTHS = {
'jan': 1,
'feb': 2,
'mar': 3,
'apr': 4,
'may': 5,
'jun': 6,
'jul': 7,
'aug': 8,
'sep': 9,
'oct': 10,
'nov': 11,
'dec': 12
}
def parse_time(line, now=None):
# Regex to read Unix, NetWare and NetPresen... | 0.318273 | 0.356139 |
import numpy as np
from scipy.linalg import blas
from .fourier_transform import FourierTransform, multiplex_for_tensor_fields, _get_float_and_complex_dtype
from ..field import Field
from ..config import Configuration
import numexpr as ne
class MatrixFourierTransform(FourierTransform):
'''A Matrix Fourier Transform (M... | hcipy/fourier/matrix_fourier_transform.py | import numpy as np
from scipy.linalg import blas
from .fourier_transform import FourierTransform, multiplex_for_tensor_fields, _get_float_and_complex_dtype
from ..field import Field
from ..config import Configuration
import numexpr as ne
class MatrixFourierTransform(FourierTransform):
'''A Matrix Fourier Transform (M... | 0.783575 | 0.627495 |
import asyncio
import os
import signal
import sys
import pytest
from sys_toolkit.tests.mock import MockCalledMethod
from cli_toolkit.script import Script
from cli_toolkit.task import Task, CommandLineTask
# pylint: disable=too-few-public-methods
class MockSigInt(MockCalledMethod):
"""
Mock SIGINT handler
... | tests/test_script_tasks.py | import asyncio
import os
import signal
import sys
import pytest
from sys_toolkit.tests.mock import MockCalledMethod
from cli_toolkit.script import Script
from cli_toolkit.task import Task, CommandLineTask
# pylint: disable=too-few-public-methods
class MockSigInt(MockCalledMethod):
"""
Mock SIGINT handler
... | 0.316264 | 0.278514 |
import h5py
import mpi_init
import subfind_data
import cosmology
import tree_build
import numpy as np
from scipy.interpolate import interp1d
def compute_accretion_rates(mpi, path, datasets, data, snap=99, mcut=1.0e12):
"""
Compute the accretion rate based on different mass estimates
"""
if not mpi.Ra... | TRACING_EXAMPLE.py | import h5py
import mpi_init
import subfind_data
import cosmology
import tree_build
import numpy as np
from scipy.interpolate import interp1d
def compute_accretion_rates(mpi, path, datasets, data, snap=99, mcut=1.0e12):
"""
Compute the accretion rate based on different mass estimates
"""
if not mpi.Ra... | 0.686895 | 0.344967 |
import os
import shutil
import tarfile
from capreolus import ConfigOption, constants
from capreolus.utils.common import download_file
from capreolus.utils.loginit import get_logger
from capreolus.utils.trec import anserini_index_to_trec_docs
from . import Collection
logger = get_logger(__name__)
PACKAGE_PATH = const... | capreolus/collection/robust04.py | import os
import shutil
import tarfile
from capreolus import ConfigOption, constants
from capreolus.utils.common import download_file
from capreolus.utils.loginit import get_logger
from capreolus.utils.trec import anserini_index_to_trec_docs
from . import Collection
logger = get_logger(__name__)
PACKAGE_PATH = const... | 0.507324 | 0.238356 |
import argparse
import cv2
import os
import re
import shutil
fg_video_path = '/content/AnimeGAN/video/input_video.mp4'
EXTRACT_FREQUENCY = 1
def extract(video_path, image_path, index=EXTRACT_FREQUENCY):
try:
shutil.rmtree(image_path)
except OSError:
pass
os.mkdir(image_path)
video = cv... | content/video.py | import argparse
import cv2
import os
import re
import shutil
fg_video_path = '/content/AnimeGAN/video/input_video.mp4'
EXTRACT_FREQUENCY = 1
def extract(video_path, image_path, index=EXTRACT_FREQUENCY):
try:
shutil.rmtree(image_path)
except OSError:
pass
os.mkdir(image_path)
video = cv... | 0.150185 | 0.125039 |
import logging
import requests
from urllib.parse import urljoin
from typing import List
from inspect import isclass
from enum import Enum
__all__ = [
"Abilities",
"Ability",
"Command",
"Device",
"Error",
"Hub",
"Location",
"MowerCommands",
"OutletCommands",
"Properties",
"Pr... | gardena/gardena.py | import logging
import requests
from urllib.parse import urljoin
from typing import List
from inspect import isclass
from enum import Enum
__all__ = [
"Abilities",
"Ability",
"Command",
"Device",
"Error",
"Hub",
"Location",
"MowerCommands",
"OutletCommands",
"Properties",
"Pr... | 0.703957 | 0.115411 |
from __future__ import print_function
import numpy as np
from scipy.integrate import simps
from scipy import fftpack
import warnings
import collections
class Schrod:
def __init__(self, x, V, n_basis=20):
"""
Parameters
----------
x : array_like, float
Length-N array of... | schrod.py | from __future__ import print_function
import numpy as np
from scipy.integrate import simps
from scipy import fftpack
import warnings
import collections
class Schrod:
def __init__(self, x, V, n_basis=20):
"""
Parameters
----------
x : array_like, float
Length-N array of... | 0.866782 | 0.591458 |
# necessary imports
import sys
import json
import numpy as np
import itertools
import pandas as pd
from toolbox.utils import load_obj, CombinationsManager
configFilename = "config.json"
argCount = len(sys.argv)
if (argCount > 1):
configFilename = sys.argv[1]
with open(configFilename, "r") as fd:
config = jso... | read_outputs_oinfo.py |
# necessary imports
import sys
import json
import numpy as np
import itertools
import pandas as pd
from toolbox.utils import load_obj, CombinationsManager
configFilename = "config.json"
argCount = len(sys.argv)
if (argCount > 1):
configFilename = sys.argv[1]
with open(configFilename, "r") as fd:
config = jso... | 0.067685 | 0.11887 |
#------------------------------------------------------------------------------
# Imports:
#------------------------------------------------------------------------------
import sys
import wx
import wx.html
import wx.lib.wxpTag
from enthought.pyface.ui.wx.about_dialog import AboutDialog \
as EnthoughtAboutDialo... | puddle/workbench/wx_about_dialog.py | #------------------------------------------------------------------------------
# Imports:
#------------------------------------------------------------------------------
import sys
import wx
import wx.html
import wx.lib.wxpTag
from enthought.pyface.ui.wx.about_dialog import AboutDialog \
as EnthoughtAboutDialo... | 0.382833 | 0.09343 |
from collections import defaultdict
from datetime import datetime
from os.path import join
import asyncio
import logging
import uuid
from .client import Client, DisconnectError
from .map import Map
from .message import Message
from .message_type import MessageType
from .player_collection import PlayerCollection
from .... | server/server.py | from collections import defaultdict
from datetime import datetime
from os.path import join
import asyncio
import logging
import uuid
from .client import Client, DisconnectError
from .map import Map
from .message import Message
from .message_type import MessageType
from .player_collection import PlayerCollection
from .... | 0.482917 | 0.058426 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from nni.compression.torch import LotteryTicketPruner
class fc1(nn.Module):
def __init__(self, num_classes=10):
super(fc1, self).__... | examples/model_compress/lottery_torch_mnist_fc.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from nni.compression.torch import LotteryTicketPruner
class fc1(nn.Module):
def __init__(self, num_classes=10):
super(fc1, self).__... | 0.953611 | 0.650911 |
from PySimpleGUI import PySimpleGUI as sg
from docx import Document
from docx.shared import Inches
from datetime import datetime
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
import os
def doc(cliente, img=0):
now = datetime.today()
today = f'{now.day}{now.month}{now.year}--{now.hou... | program.py | from PySimpleGUI import PySimpleGUI as sg
from docx import Document
from docx.shared import Inches
from datetime import datetime
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
import os
def doc(cliente, img=0):
now = datetime.today()
today = f'{now.day}{now.month}{now.year}--{now.hou... | 0.242116 | 0.223758 |
import os
from core.model import Model
from core.operators import *
def make_simple_model() -> Model:
"""Create a simple model with a simple graph."""
model = Model()
graph = model.graph
node_names = [
'conv1_kernel',
'conv1_bn_beta',
'conv1_bn_gamma',
'conv1_bn_mean'... | dlk/python/dlk/scripts/simple_model.py | import os
from core.model import Model
from core.operators import *
def make_simple_model() -> Model:
"""Create a simple model with a simple graph."""
model = Model()
graph = model.graph
node_names = [
'conv1_kernel',
'conv1_bn_beta',
'conv1_bn_gamma',
'conv1_bn_mean'... | 0.627495 | 0.514034 |
import asyncio
import sys
import argparse
import json
import importlib
import pkgutil
from dataclasses import dataclass
from typing import Dict
from pathlib import Path
import mudfuzz.mud_fuzzer as MF
import mudfuzz.ui as UI
from mudfuzz.util import snake_to_camel_case
@dataclass
class MudFuzzConfig:
mud_host: ... | mudfuzz.py |
import asyncio
import sys
import argparse
import json
import importlib
import pkgutil
from dataclasses import dataclass
from typing import Dict
from pathlib import Path
import mudfuzz.mud_fuzzer as MF
import mudfuzz.ui as UI
from mudfuzz.util import snake_to_camel_case
@dataclass
class MudFuzzConfig:
mud_host: ... | 0.344223 | 0.084947 |
import time
from xminds.compat import logger
from ..baserecoapi import JobFailedException
class AmazonTrainApi():
def __init__(self, api_clients):
self.clients = api_clients
def aws_train(self, arn_set, algorithm, event_type, name):
t0 = time.time()
arn_set.solution_arn = self._aw... | recoapis/amazonrecoapi/train.py | import time
from xminds.compat import logger
from ..baserecoapi import JobFailedException
class AmazonTrainApi():
def __init__(self, api_clients):
self.clients = api_clients
def aws_train(self, arn_set, algorithm, event_type, name):
t0 = time.time()
arn_set.solution_arn = self._aw... | 0.428353 | 0.134634 |
from __future__ import division
from __future__ import print_function
import pickle
import numpy as np
from PIL import Image
import csv
import data_dirs
DATADIR = data_dirs.synth_signs
NUM_LABELS = 43
IMAGE_SHAPE = [40, 40, 3]
def get_data(name):
"""Utility for convenient data loading."""
if name in ['tra... | semisup/tools/synth_signs.py | from __future__ import division
from __future__ import print_function
import pickle
import numpy as np
from PIL import Image
import csv
import data_dirs
DATADIR = data_dirs.synth_signs
NUM_LABELS = 43
IMAGE_SHAPE = [40, 40, 3]
def get_data(name):
"""Utility for convenient data loading."""
if name in ['tra... | 0.677901 | 0.269955 |
from __future__ import absolute_import, division, print_function
import time
import uuid
from vivarium.actor.control import ActorControl, AgentCommand
DEFAULT_BOOT = 'vivarium.environment.boot'
class ShepherdControl(ActorControl):
"""Send messages to agents in the system to control execution."""
def __init... | vivarium/environment/control.py | from __future__ import absolute_import, division, print_function
import time
import uuid
from vivarium.actor.control import ActorControl, AgentCommand
DEFAULT_BOOT = 'vivarium.environment.boot'
class ShepherdControl(ActorControl):
"""Send messages to agents in the system to control execution."""
def __init... | 0.638159 | 0.131507 |
# In[1]:
import time
import numpy as np
import pandas as pd
# In[2]:
import tensorflow.python.keras as keras
from tensorflow.python.keras.layers import Layer
import tensorflow as tf
import dan_models
import dan_utils
# In[3]:
def main(class_i):
physical_devices = tf.config.list_physical_devices('GPU')
... | learning_DAN/base_ST-DTNN.py |
# In[1]:
import time
import numpy as np
import pandas as pd
# In[2]:
import tensorflow.python.keras as keras
from tensorflow.python.keras.layers import Layer
import tensorflow as tf
import dan_models
import dan_utils
# In[3]:
def main(class_i):
physical_devices = tf.config.list_physical_devices('GPU')
... | 0.345878 | 0.333137 |
import unittest
from flask_testing import TestCase as FlaskTestCase
from .basetest import BasetTest, BaseTest2, flask_profiler
class EndpointMeasurementTest(BasetTest, FlaskTestCase):
def tearDown(self):
pass
def test_01_return_value(self):
name = "john"
response = self.client.get(... | tests/test_measure_endpoint.py | import unittest
from flask_testing import TestCase as FlaskTestCase
from .basetest import BasetTest, BaseTest2, flask_profiler
class EndpointMeasurementTest(BasetTest, FlaskTestCase):
def tearDown(self):
pass
def test_01_return_value(self):
name = "john"
response = self.client.get(... | 0.439988 | 0.34172 |
import os
import time
import gzip
import shutil
# external packages
from PyQt5.QtCore import Qt, pyqtSignal
import requests
# local import
from gui.utilities import toolsQtWidget
from base.tpool import Worker
from gui.widgets.downloadPopup_ui import Ui_DownloadPopup
class DownloadPopup(toolsQtWidget.MWidget):
"... | mw4/gui/extWindows/downloadPopupW.py | import os
import time
import gzip
import shutil
# external packages
from PyQt5.QtCore import Qt, pyqtSignal
import requests
# local import
from gui.utilities import toolsQtWidget
from base.tpool import Worker
from gui.widgets.downloadPopup_ui import Ui_DownloadPopup
class DownloadPopup(toolsQtWidget.MWidget):
"... | 0.363308 | 0.083553 |
from django.db import models
from django.utils import timezone
from django.utils.http import urlquote
from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.contrib.auth.models import BaseUserMa... | models.py | from django.db import models
from django.utils import timezone
from django.utils.http import urlquote
from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.contrib.auth.models import BaseUserMa... | 0.526343 | 0.078113 |
import urllib2
from oauth import oauth
from django.core.exceptions import PermissionDenied
class OAuthHTTPError(urllib2.HTTPError, PermissionDenied):
def __init__(self, e):
self.exception = e
def __getattr__(self, key):
return getattr(self.__dict__['exception'], key)
def __setattr__(... | molly/auth/oauth/clients.py | import urllib2
from oauth import oauth
from django.core.exceptions import PermissionDenied
class OAuthHTTPError(urllib2.HTTPError, PermissionDenied):
def __init__(self, e):
self.exception = e
def __getattr__(self, key):
return getattr(self.__dict__['exception'], key)
def __setattr__(... | 0.408395 | 0.048092 |
import threading
import logging
from .named_expr import eval_expr, L
class Variable:
""" Pipeline variable """
def __init__(self, default=None, init_on_each_run=False, lock=True, pipeline=None):
self.default = default
if init_on_each_run is not None and not isinstance(init_on_each_run, bool):... | dataset/variables.py | import threading
import logging
from .named_expr import eval_expr, L
class Variable:
""" Pipeline variable """
def __init__(self, default=None, init_on_each_run=False, lock=True, pipeline=None):
self.default = default
if init_on_each_run is not None and not isinstance(init_on_each_run, bool):... | 0.57523 | 0.108614 |
from __future__ import print_function
import numpy as np
import tensorflow as tf
from collections import namedtuple
import json
import pickle
HyperParams = namedtuple(
"HyperParams",
[
"max_seq_len",
"seq_width",
"h_size",
"batch_size",
"grad_clip",
"num_mixture"... | navrep/models/tcn.py | from __future__ import print_function
import numpy as np
import tensorflow as tf
from collections import namedtuple
import json
import pickle
HyperParams = namedtuple(
"HyperParams",
[
"max_seq_len",
"seq_width",
"h_size",
"batch_size",
"grad_clip",
"num_mixture"... | 0.658308 | 0.227909 |
import asyncio
import unittest
from unittest import mock
from aiohttp.multidict import MultiDict, CaseInsensitiveMultiDict
from aiohttp.web import Request, StreamResponse, Response
from aiohttp.protocol import RawRequestMessage, HttpVersion11
class TestStreamResponse(unittest.TestCase):
def setUp(self):
... | tests/test_web_response.py | import asyncio
import unittest
from unittest import mock
from aiohttp.multidict import MultiDict, CaseInsensitiveMultiDict
from aiohttp.web import Request, StreamResponse, Response
from aiohttp.protocol import RawRequestMessage, HttpVersion11
class TestStreamResponse(unittest.TestCase):
def setUp(self):
... | 0.53777 | 0.212008 |
import sys
import argparse
import os
from core import translate
USAGE = '''todo
'''
def write_in_chunks(f,pos,data):
f.seek(pos)
f.write(data)
def read_in_chunks(f, chunk_size=1024):
"""Lazy function (generator) to read a file piece by piece.
Default chunk size: 1k."""
while True:
da... | assets/scripts/translation/main.py | import sys
import argparse
import os
from core import translate
USAGE = '''todo
'''
def write_in_chunks(f,pos,data):
f.seek(pos)
f.write(data)
def read_in_chunks(f, chunk_size=1024):
"""Lazy function (generator) to read a file piece by piece.
Default chunk size: 1k."""
while True:
da... | 0.051678 | 0.10904 |
from __future__ import absolute_import
from sentry.api.permissions import has_perm
from sentry.constants import MEMBER_USER, MEMBER_ADMIN
from sentry.testutils import TestCase
class TeamPermissionTest(TestCase):
def test_basic_user(self):
user = self.create_user(is_superuser=False, email='<EMAIL>')
... | tests/sentry/api/test_permissions.py |
from __future__ import absolute_import
from sentry.api.permissions import has_perm
from sentry.constants import MEMBER_USER, MEMBER_ADMIN
from sentry.testutils import TestCase
class TeamPermissionTest(TestCase):
def test_basic_user(self):
user = self.create_user(is_superuser=False, email='<EMAIL>')
... | 0.567218 | 0.191309 |
from typing import Any
from typing import NamedTuple
from typing import Optional
import pytest
from http_overeasy.response import Response
from urllib3.response import HTTPResponse
RESP_HEADERS = {
"Date": "Mon, 29, Jan 2022 12:00:00 GMT",
"Server": "EggCarton v1 (endless)",
"Content-Length": "0",
"C... | tests/response_test.py | from typing import Any
from typing import NamedTuple
from typing import Optional
import pytest
from http_overeasy.response import Response
from urllib3.response import HTTPResponse
RESP_HEADERS = {
"Date": "Mon, 29, Jan 2022 12:00:00 GMT",
"Server": "EggCarton v1 (endless)",
"Content-Length": "0",
"C... | 0.806738 | 0.219181 |
from django.contrib.auth.models import User
from django.db import models
from django_extensions.db.fields import AutoSlugField
from apps.government.models import Government
from apps.core.models import BaseData
from apps.contacts.models import Contact
from datetime import datetime
from django.utils import timezone
cl... | foiamachine/apps/agency/models.py | from django.contrib.auth.models import User
from django.db import models
from django_extensions.db.fields import AutoSlugField
from apps.government.models import Government
from apps.core.models import BaseData
from apps.contacts.models import Contact
from datetime import datetime
from django.utils import timezone
cl... | 0.503906 | 0.14013 |
import datetime as dt
import logging
import os
import sys
import time
from logging.handlers import RotatingFileHandler
import requests
import telegram
import telegram.ext as te
from dotenv import load_dotenv
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove
from image_handler import geo_data, qr_data
from... | tg_bot_akson/main.py | import datetime as dt
import logging
import os
import sys
import time
from logging.handlers import RotatingFileHandler
import requests
import telegram
import telegram.ext as te
from dotenv import load_dotenv
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove
from image_handler import geo_data, qr_data
from... | 0.243822 | 0.07343 |
from polygraphy import constants, mod, util
from polygraphy.common import TensorMetadata
from polygraphy.logger import G_LOGGER
from polygraphy.tools.args import util as args_util
from polygraphy.tools.args.base import BaseArgs
from polygraphy.tools.script import Script, make_invocable
onnx_backend = mod.lazy_import("... | tools/Polygraphy/polygraphy/tools/args/onnx/loader.py | from polygraphy import constants, mod, util
from polygraphy.common import TensorMetadata
from polygraphy.logger import G_LOGGER
from polygraphy.tools.args import util as args_util
from polygraphy.tools.args.base import BaseArgs
from polygraphy.tools.script import Script, make_invocable
onnx_backend = mod.lazy_import("... | 0.761272 | 0.135004 |
from pathlib import Path
import numpy as np
DATA_ROOT = Path.cwd() / 'data' / 'kjm_ecog' / 'download' / 'faces_basic'
AREA_LABELS = [
'Temporal pole',
'Parahippocampal gyrus', # parahippocampal part of the medial occipito-temporal gyrus
'Inferior temporal gyrus',
'Middle temporal gyrus',
... | data/kjm_ecog/studies/faces_basic.py | from pathlib import Path
import numpy as np
DATA_ROOT = Path.cwd() / 'data' / 'kjm_ecog' / 'download' / 'faces_basic'
AREA_LABELS = [
'Temporal pole',
'Parahippocampal gyrus', # parahippocampal part of the medial occipito-temporal gyrus
'Inferior temporal gyrus',
'Middle temporal gyrus',
... | 0.661814 | 0.450601 |
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from .arcface_torch.backbones.iresnet import iresnet100
from .Deep3DFaceRecon_pytorch.models.networks import ReconNetWrapper
class ResBlock(nn.Module):
def __init__(self, in_channel, out_channel, down_sample=False, up_sample=False)... | model/hififace.py | import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from .arcface_torch.backbones.iresnet import iresnet100
from .Deep3DFaceRecon_pytorch.models.networks import ReconNetWrapper
class ResBlock(nn.Module):
def __init__(self, in_channel, out_channel, down_sample=False, up_sample=False)... | 0.870652 | 0.258177 |