code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import time
import os
import shutil
import zipfile
import platform
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
testdir = os.path.dirname(os.path.abspath(__file__))
nwdist = os.path.join(os.path.dirname(os.environ['CHROMEDRIVER']), 'nwdist')
appdir = os.path.join(testdir, 'ap... | test/remoting/package/test.py | import time
import os
import shutil
import zipfile
import platform
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
testdir = os.path.dirname(os.path.abspath(__file__))
nwdist = os.path.join(os.path.dirname(os.environ['CHROMEDRIVER']), 'nwdist')
appdir = os.path.join(testdir, 'ap... | 0.084444 | 0.09277 |
import argparse
import os
import shutil
import tempfile
import tensorflow.keras as keras
import numpy as np
import h5py
import joblib
from tensorflow.python.lib.io import file_io
import trainer.export_to_tensorflow as export_to_tensorflow
import trainer.predictor as predictor
def train_model(train_file='./data/', jo... | trainer/train.py | import argparse
import os
import shutil
import tempfile
import tensorflow.keras as keras
import numpy as np
import h5py
import joblib
from tensorflow.python.lib.io import file_io
import trainer.export_to_tensorflow as export_to_tensorflow
import trainer.predictor as predictor
def train_model(train_file='./data/', jo... | 0.58059 | 0.213152 |
import paho.mqtt.client as paho
from paho.mqtt import client as mqtt_client
from utils import email_handler, rfid, buzzer
from datetime import datetime
client = paho.Client("client-007")
broker = 'localhost'
port = 1883
topics = [("Dashboard/RFID/Tag",0),("Dashboard/Light/Photo",1)]
# Generate client ID with pub pref... | Dashboard/utils/mqtt_server.py | import paho.mqtt.client as paho
from paho.mqtt import client as mqtt_client
from utils import email_handler, rfid, buzzer
from datetime import datetime
client = paho.Client("client-007")
broker = 'localhost'
port = 1883
topics = [("Dashboard/RFID/Tag",0),("Dashboard/Light/Photo",1)]
# Generate client ID with pub pref... | 0.155463 | 0.056679 |
from . lsp_metals_text_command import LspMetalsTextCommand
from . utils import handle_error
from LSP.plugin.core.protocol import Request, Location
from LSP.plugin.core.sessions import Session
from LSP.plugin.core.typing import Any, List, Union, Dict
from LSP.plugin.locationpicker import LocationPicker
import weakref
i... | commands/lsp_metals_find_in_dependency.py | from . lsp_metals_text_command import LspMetalsTextCommand
from . utils import handle_error
from LSP.plugin.core.protocol import Request, Location
from LSP.plugin.core.sessions import Session
from LSP.plugin.core.typing import Any, List, Union, Dict
from LSP.plugin.locationpicker import LocationPicker
import weakref
i... | 0.473657 | 0.126003 |
from HAPT import split_HAPT
from compression import decode_weights
from keras.models import load_model
from keras.optimizers import Adam
from numpy.random import seed
import pickle
import tensorflow
if __name__ == '__main__':
# x = [30, 15, 18, 21, 24, 27]
x = [27]
y = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, ... | HAPT/decode_and_evaluate_HAPT.py | from HAPT import split_HAPT
from compression import decode_weights
from keras.models import load_model
from keras.optimizers import Adam
from numpy.random import seed
import pickle
import tensorflow
if __name__ == '__main__':
# x = [30, 15, 18, 21, 24, 27]
x = [27]
y = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, ... | 0.41561 | 0.317625 |
from pinn.io.base import list_loader
def _ase_spec(atoms):
"""Guess dataset format from an ASE atoms"""
ds_spec = {
'elems': {'dtype': 'int32', 'shape': [None]},
'coord': {'dtype': 'float', 'shape': [None, 3]}}
if atoms.pbc.any():
ds_spec['cell'] = {'dtype': 'float', 'shape': [3... | pinn/io/ase.py |
from pinn.io.base import list_loader
def _ase_spec(atoms):
"""Guess dataset format from an ASE atoms"""
ds_spec = {
'elems': {'dtype': 'int32', 'shape': [None]},
'coord': {'dtype': 'float', 'shape': [None, 3]}}
if atoms.pbc.any():
ds_spec['cell'] = {'dtype': 'float', 'shape': [3... | 0.729231 | 0.368264 |
import gurobipy as gp
import pandas as pd
# Read in lengths
df_read = pd.read_excel('Rod_cutting_input.xlsx')
columns = df_read.columns
df_read = df_read.drop(columns=columns[0])
df_read = df_read.rename(columns={columns[1]:'count', columns[2]:'length'})
m = gp.Model("Beam to Rods")
# Given Info
cos... | Mini Project/MiniProject_WarmStart.py | import gurobipy as gp
import pandas as pd
# Read in lengths
df_read = pd.read_excel('Rod_cutting_input.xlsx')
columns = df_read.columns
df_read = df_read.drop(columns=columns[0])
df_read = df_read.rename(columns={columns[1]:'count', columns[2]:'length'})
m = gp.Model("Beam to Rods")
# Given Info
cos... | 0.253953 | 0.204144 |
import cv2
import numpy as np
import pandas as pd
import torch
import math
import pandas as pd
import numpy as np
import feat.au_detectors.JAANet.JAANet_model as network
import torch.nn as nn
from PIL import Image
from torchvision import transforms
from feat.utils import get_resource_path, convert68to49
import os
cla... | feat/au_detectors/JAANet/JAA_test.py | import cv2
import numpy as np
import pandas as pd
import torch
import math
import pandas as pd
import numpy as np
import feat.au_detectors.JAANet.JAANet_model as network
import torch.nn as nn
from PIL import Image
from torchvision import transforms
from feat.utils import get_resource_path, convert68to49
import os
cla... | 0.665193 | 0.172276 |
import unittest
import os
import filecmp
import scripts.scriptutils
from scripts.test.helpers import copy_to_tmp
template_path = os.path.join(os.path.pardir, os.path.pardir, os.path.pardir, 'package template.xlsx')
class TestExportCSV(unittest.TestCase):
def test_csv_export(self):
# copy file into temp ... | scripts/test/test_export.py | import unittest
import os
import filecmp
import scripts.scriptutils
from scripts.test.helpers import copy_to_tmp
template_path = os.path.join(os.path.pardir, os.path.pardir, os.path.pardir, 'package template.xlsx')
class TestExportCSV(unittest.TestCase):
def test_csv_export(self):
# copy file into temp ... | 0.345989 | 0.466056 |
from typing import (
Any,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from copy import deepcopy
from typing_extensions import Self
from graph.retworkx.digraph import _RetworkXDiGraph
from retworkx import NoEdgeBetweenNodes # type: ignore
from gra... | graph/retworkx/str_digraph.py | from typing import (
Any,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from copy import deepcopy
from typing_extensions import Self
from graph.retworkx.digraph import _RetworkXDiGraph
from retworkx import NoEdgeBetweenNodes # type: ignore
from gra... | 0.903685 | 0.425546 |
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sklearn.metrics import mean_absolute_error as MAE
from datetime import datetime
from fbprophet import Prophet
from matplotlib.dates import (
MonthLocator,
num2date,
AutoDateLocator,
... | src/utils.py | import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sklearn.metrics import mean_absolute_error as MAE
from datetime import datetime
from fbprophet import Prophet
from matplotlib.dates import (
MonthLocator,
num2date,
AutoDateLocator,
... | 0.79542 | 0.649773 |
import numpy as np
import matplotlib.pyplot as plt
import scipy
from scipy.fftpack import fftshift, ifftshift, fft2, ifft2
from mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size
from scipy.signal import correlate2d as correlate
from scipy.signal import general_gaussian
from astropy.io import fits
from scipy... | zernike.py | import numpy as np
import matplotlib.pyplot as plt
import scipy
from scipy.fftpack import fftshift, ifftshift, fft2, ifft2
from mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size
from scipy.signal import correlate2d as correlate
from scipy.signal import general_gaussian
from astropy.io import fits
from scipy... | 0.241937 | 0.483222 |
import argparse
import copy
from pathlib import Path
from typing import Any, Dict, List, Tuple
import graphviz
import yaml
from . import auto_gen_header
from .wic_types import (GraphData, GraphReps, Json, Namespaces, NodeData,
RoseTree, Tool, Tools, Yaml, YamlForest, YamlTree)
def read_lines... | src/wic/utils.py | import argparse
import copy
from pathlib import Path
from typing import Any, Dict, List, Tuple
import graphviz
import yaml
from . import auto_gen_header
from .wic_types import (GraphData, GraphReps, Json, Namespaces, NodeData,
RoseTree, Tool, Tools, Yaml, YamlForest, YamlTree)
def read_lines... | 0.794425 | 0.353735 |
from collections import OrderedDict
from poe_driver_pd69200_def import *
from poe_common import *
from poe_common import print_stderr
from smbus2 import SMBus, i2c_msg
import os
import sys
import time
import fcntl
import poe_driver_pd69200 as PoeDrv
def get_poe_platform():
return PoePlatform_delta_tn48m_poe()
cl... | dentos-poe-agent/opt/poeagent/platforms/delta/tn48m-poe-r0/poe_platform.py | from collections import OrderedDict
from poe_driver_pd69200_def import *
from poe_common import *
from poe_common import print_stderr
from smbus2 import SMBus, i2c_msg
import os
import sys
import time
import fcntl
import poe_driver_pd69200 as PoeDrv
def get_poe_platform():
return PoePlatform_delta_tn48m_poe()
cl... | 0.29747 | 0.161883 |
import unittest
from nltk import sent_tokenize
from tests.utils import get_abspath_from_tests_root
from web_backend.wrapper.twenty_news_groups_dataset_models_wrapper import TwentyNewsGroupsDatasetModelsWrapper
class TestModelsWrapper(unittest.TestCase):
_TEXT_DOESNT_CONVERGE_FILE_PATH = get_abspath_from_tests_r... | tests/test_wrapper.py | import unittest
from nltk import sent_tokenize
from tests.utils import get_abspath_from_tests_root
from web_backend.wrapper.twenty_news_groups_dataset_models_wrapper import TwentyNewsGroupsDatasetModelsWrapper
class TestModelsWrapper(unittest.TestCase):
_TEXT_DOESNT_CONVERGE_FILE_PATH = get_abspath_from_tests_r... | 0.715722 | 0.489442 |
import socket
import sys
import os
import subprocess
def launch(port_file, opts, debug):
# create and bind server socket
server = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
server.bind(("localhost",0))
server.listen(1)
# buffer for output file
output = ""
# fork and launch a CLI ... | bin/launch-cli.py | import socket
import sys
import os
import subprocess
def launch(port_file, opts, debug):
# create and bind server socket
server = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
server.bind(("localhost",0))
server.listen(1)
# buffer for output file
output = ""
# fork and launch a CLI ... | 0.095666 | 0.084455 |
import re
from unittest.mock import patch
from aiohttp.test_utils import loop_context
from click.testing import CliRunner
from darq import Darq
from darq.cli import cli
from darq.cron import cron
from . import redis_settings
darq = Darq(redis_settings=redis_settings, burst=True)
@darq.task
async def foobar(ctx):
... | tests/test_cli.py | import re
from unittest.mock import patch
from aiohttp.test_utils import loop_context
from click.testing import CliRunner
from darq import Darq
from darq.cli import cli
from darq.cron import cron
from . import redis_settings
darq = Darq(redis_settings=redis_settings, burst=True)
@darq.task
async def foobar(ctx):
... | 0.503174 | 0.422862 |
from typing import Any
import json
class OrderService:
def get_dimensions(self, **kwargs) -> Any:
"""7.1.1. Request for the trading venue and order options for a particular instrument.
Kwargs: Filter Parameter
instrument_id: Instrument id (UUID), unique identification of an instrument... | comdirect_api/service/order_service.py | from typing import Any
import json
class OrderService:
def get_dimensions(self, **kwargs) -> Any:
"""7.1.1. Request for the trading venue and order options for a particular instrument.
Kwargs: Filter Parameter
instrument_id: Instrument id (UUID), unique identification of an instrument... | 0.856722 | 0.311623 |
import requests
import random
import time
from json import encoder
def get_user_input(hparams=None):
"""Get the user's input, assess it and return it to the bot."""
utterance = input()
# End the chat
if utterance == 'end()':
return utterance, utterance
# Authorization not present
if not ... | assessment/input_assessment.py | import requests
import random
import time
from json import encoder
def get_user_input(hparams=None):
"""Get the user's input, assess it and return it to the bot."""
utterance = input()
# End the chat
if utterance == 'end()':
return utterance, utterance
# Authorization not present
if not ... | 0.696062 | 0.22777 |
import click
import sys
from .shakespeare import Shakespeare
from .errors import ShakespeareError
from ._repl import start_console, debug_play
from functools import wraps, partial
def pretty_print_shakespeare_errors(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
func(*args, **kwar... | shakespearelang/cli.py |
import click
import sys
from .shakespeare import Shakespeare
from .errors import ShakespeareError
from ._repl import start_console, debug_play
from functools import wraps, partial
def pretty_print_shakespeare_errors(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
func(*args, **kwar... | 0.457864 | 0.203846 |
import torch
import triton
import pytest
import subprocess
import triton.language as tl
import numpy as np
def get_p2p_matrix():
try:
stdout = subprocess.check_output(["nvidia-smi", "topo", "-p2p", "n"]).decode("ascii")
except subprocess.CalledProcessError:
return pytest.skip("No m... | python/test/unit/runtime/test_comm.py | import torch
import triton
import pytest
import subprocess
import triton.language as tl
import numpy as np
def get_p2p_matrix():
try:
stdout = subprocess.check_output(["nvidia-smi", "topo", "-p2p", "n"]).decode("ascii")
except subprocess.CalledProcessError:
return pytest.skip("No m... | 0.364438 | 0.315037 |
import pandas as pd
import numpy as np
import os
import shutil
import scipy
import tensorflow as tf
from sklearn.preprocessing import StandardScaler, OneHotEncoder, QuantileTransformer
from sklearn.compose import ColumnTransformer
from math import ceil
from tensorflow.keras.models import Model
from tensor... | tabGAN/tabGAN2.py | import pandas as pd
import numpy as np
import os
import shutil
import scipy
import tensorflow as tf
from sklearn.preprocessing import StandardScaler, OneHotEncoder, QuantileTransformer
from sklearn.compose import ColumnTransformer
from math import ceil
from tensorflow.keras.models import Model
from tensor... | 0.737253 | 0.166675 |
import math
import numpy as np
import Box2D
from Box2D.b2 import (
edgeShape,
circleShape,
fixtureDef,
polygonShape,
revoluteJointDef,
contactListener
)
from .color import Color
class Terrain:
GRASS = 0
STUMP = 1
STAIRS = 2
PIT = 3
@staticmethod
def rand(np_random=None, include_grass=Fal... | general_bipedal_walker/simulation.py | import math
import numpy as np
import Box2D
from Box2D.b2 import (
edgeShape,
circleShape,
fixtureDef,
polygonShape,
revoluteJointDef,
contactListener
)
from .color import Color
class Terrain:
GRASS = 0
STUMP = 1
STAIRS = 2
PIT = 3
@staticmethod
def rand(np_random=None, include_grass=Fal... | 0.642769 | 0.262475 |
r'''Layers for ranking model.
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import tensorflow as tf
class DotInteract(tf.layers.Layer):
r'''DLRM: Deep Learning Recommendation Model for Personalization and
Recommendation Systems.
... | examples/ranking/layers.py |
r'''Layers for ranking model.
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import tensorflow as tf
class DotInteract(tf.layers.Layer):
r'''DLRM: Deep Learning Recommendation Model for Personalization and
Recommendation Systems.
... | 0.912143 | 0.477006 |
from antlr4 import *
from sxlLexer import sxlLexer
from sxlParser import sxlParser
from sxlVisitor import sxlVisitor
class RegisterAddressVisitor(sxlVisitor):
"""
Parse a sxl file and return an array of all found register addresses
"""
def __init__(self):
self.addr = {}
self.validate =... | python/RegisterAddressVisitor.py | from antlr4 import *
from sxlLexer import sxlLexer
from sxlParser import sxlParser
from sxlVisitor import sxlVisitor
class RegisterAddressVisitor(sxlVisitor):
"""
Parse a sxl file and return an array of all found register addresses
"""
def __init__(self):
self.addr = {}
self.validate =... | 0.579043 | 0.13288 |
import pytest
from unittest.mock import patch, MagicMock
from click.testing import CliRunner
from paths_cli.cli import *
from paths_cli.plugin_management import OPSPlugin
from .null_command import NullCommandContext
class TestOpenPathSamplingCLI(object):
def setup(self):
def make_mock(name, helpless=Fals... | paths_cli/tests/test_cli.py | import pytest
from unittest.mock import patch, MagicMock
from click.testing import CliRunner
from paths_cli.cli import *
from paths_cli.plugin_management import OPSPlugin
from .null_command import NullCommandContext
class TestOpenPathSamplingCLI(object):
def setup(self):
def make_mock(name, helpless=Fals... | 0.677047 | 0.348091 |
import datetime
import random
import sys
import unittest
import genetic
def obtener_aptitud(genes):
pesoTotal = 0
volumenTotal = 0
valorTotal = 0
for ac in genes:
cuenta = ac.Cantidad
pesoTotal += ac.Artículo.Peso * cuenta
volumenTotal += ac.Artículo.Volumen * cuenta
... | es/ch09/mochila.py |
import datetime
import random
import sys
import unittest
import genetic
def obtener_aptitud(genes):
pesoTotal = 0
volumenTotal = 0
valorTotal = 0
for ac in genes:
cuenta = ac.Cantidad
pesoTotal += ac.Artículo.Peso * cuenta
volumenTotal += ac.Artículo.Volumen * cuenta
... | 0.223801 | 0.47317 |
from argparse import ArgumentParser
from os import path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
def main():
parser = ArgumentParser()
parser.add_argument(
"--inputfilepath",
help="path to the input file (path)",
required=True,
... | analyses/scripts/plots/create_performance_plot.py | from argparse import ArgumentParser
from os import path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
def main():
parser = ArgumentParser()
parser.add_argument(
"--inputfilepath",
help="path to the input file (path)",
required=True,
... | 0.560012 | 0.395076 |
import numpy as np
import math
import scipy.io.wavfile
from scipy.fftpack import dct
EPSILON = 1e-20
def convert_to_mfcc(audio_file, frames=None, frame_size=0.025, frame_overlap=0.01, n_coeff=26, n_ceps=12):
"""
Converts given audio file to mfcc
:param audio_file: location of audio file
:param frames... | analysis/processing.py | import numpy as np
import math
import scipy.io.wavfile
from scipy.fftpack import dct
EPSILON = 1e-20
def convert_to_mfcc(audio_file, frames=None, frame_size=0.025, frame_overlap=0.01, n_coeff=26, n_ceps=12):
"""
Converts given audio file to mfcc
:param audio_file: location of audio file
:param frames... | 0.755637 | 0.651812 |
from website.models import Currency
from requests.auth import _basic_auth_str
from . import login
def test_wallet_page(test_client):
cu = login(test_client, '<EMAIL>', '<PASSWORD>')
response = test_client.get('/wallet')
assert response.status_code == 200
assert b"Currency Exchange" in response.data
... | tests/functional/test_wallet.py | from website.models import Currency
from requests.auth import _basic_auth_str
from . import login
def test_wallet_page(test_client):
cu = login(test_client, '<EMAIL>', '<PASSWORD>')
response = test_client.get('/wallet')
assert response.status_code == 200
assert b"Currency Exchange" in response.data
... | 0.509276 | 0.461684 |
import datetime
import msgpack
from op_monitor_lib.common_class_py3 import Common_Class
import json
import time
class Rpi_Mosquitto_Client_Monitor(Common_Class):
def __init__(self, subsystem_name,common_obj ):
Common_Class.__init__(self,subsystem_name,common_obj )
self.handlers... | op_monitoring/op_monitor_lib/servers/monitor_rpi_mosquitto_clients_py3.py | import datetime
import msgpack
from op_monitor_lib.common_class_py3 import Common_Class
import json
import time
class Rpi_Mosquitto_Client_Monitor(Common_Class):
def __init__(self, subsystem_name,common_obj ):
Common_Class.__init__(self,subsystem_name,common_obj )
self.handlers... | 0.058279 | 0.082143 |
import json
from typing import Optional
from accounts.models import (
AccountModel,
ActionModel,
BusinessModel,
UserModel,
WorkspaceModel,
)
from api.serializers import BaseSerializer, ListItemsWithURLSerializer
from api.serializers.mixins import ActionMixinSerializer
from common.utils import Model... | server/api/serializers/accounts.py | import json
from typing import Optional
from accounts.models import (
AccountModel,
ActionModel,
BusinessModel,
UserModel,
WorkspaceModel,
)
from api.serializers import BaseSerializer, ListItemsWithURLSerializer
from api.serializers.mixins import ActionMixinSerializer
from common.utils import Model... | 0.798815 | 0.123392 |
import glob
import os
import json
import re
from dateutil.parser import parse
import jinja2
# pylint: disable=redefined-builtin, no-name-in-module
from toolz.curried import map, pipe, get, curry, filter, compose, juxt
from toolz.curried import valmap, itemmap, groupby, memoize, keymap, update_in
import yaml
def fco... | _data/simulations.py |
import glob
import os
import json
import re
from dateutil.parser import parse
import jinja2
# pylint: disable=redefined-builtin, no-name-in-module
from toolz.curried import map, pipe, get, curry, filter, compose, juxt
from toolz.curried import valmap, itemmap, groupby, memoize, keymap, update_in
import yaml
def fco... | 0.774498 | 0.366193 |
from __future__ import division, absolute_import
import cv2
from numpy import (
dstack,
degrees,
pi,
array,
ones_like,
arctan2,
hypot,
mgrid,
vstack,
uint8,
int32,
iinfo,
)
def draw_flow(img, flow, step=16, dtype=uint8):
"""
draws flow vectors on image
this ... | morecvutils/cv2draw.py | from __future__ import division, absolute_import
import cv2
from numpy import (
dstack,
degrees,
pi,
array,
ones_like,
arctan2,
hypot,
mgrid,
vstack,
uint8,
int32,
iinfo,
)
def draw_flow(img, flow, step=16, dtype=uint8):
"""
draws flow vectors on image
this ... | 0.845911 | 0.476275 |
# встроенные модули
from datetime import datetime
from unittest.mock import patch
# сторонние модули
import pytest
# модули проекта
from trivial_tools.storage.caching_machine import CachingMachine
@pytest.fixture()
def machine_persistent():
"""
Машина без срока хранения
"""
return CachingMachine()
... | trivial_tools/tests/storage/test_caching_machine.py | # встроенные модули
from datetime import datetime
from unittest.mock import patch
# сторонние модули
import pytest
# модули проекта
from trivial_tools.storage.caching_machine import CachingMachine
@pytest.fixture()
def machine_persistent():
"""
Машина без срока хранения
"""
return CachingMachine()
... | 0.415492 | 0.893402 |
"""Manage roles for vms created."""
import os
import sys
import argparse
from azure.mgmt.authorization import AuthorizationManagementClient
from azure.common.credentials import ServicePrincipalCredentials
def connect():
"""Set up Azure Login Credentials from Environmental Variables."""
credentials =... | quickstarts/docs/api/python/source/azure/azure_manage_rbac.py | """Manage roles for vms created."""
import os
import sys
import argparse
from azure.mgmt.authorization import AuthorizationManagementClient
from azure.common.credentials import ServicePrincipalCredentials
def connect():
"""Set up Azure Login Credentials from Environmental Variables."""
credentials =... | 0.411111 | 0.060752 |
from mocha import (Mocha,
_,
config,
url_for,
abort,
request,
utils,
flash_success,
flash_error,
flash_data,
get_flash_data,
... | mocha/contrib/views/contact_us.py | from mocha import (Mocha,
_,
config,
url_for,
abort,
request,
utils,
flash_success,
flash_error,
flash_data,
get_flash_data,
... | 0.458834 | 0.104752 |
from sqlalchemy import Column, DateTime
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import object_mapper
from sqlalchemy.types import CHAR
from designate.openstack.common import timeutils
from designate import exceptions
class Base(object):
__abstract__ = True
__table_initialized__ = False
... | designate/sqlalchemy/models.py | from sqlalchemy import Column, DateTime
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import object_mapper
from sqlalchemy.types import CHAR
from designate.openstack.common import timeutils
from designate import exceptions
class Base(object):
__abstract__ = True
__table_initialized__ = False
... | 0.648689 | 0.188343 |
import os
base_dir = "/usr/local/projects/xprize/quaternary"
val_vcf = os.path.join(base_dir, "NA12878_validate/inputs/NA12878-sanger-validate-allowone.vcf")
prep_dir = os.path.join(base_dir, "NA12878_fosmid/work/prep")
full_vcf = os.path.join(prep_dir, "NA12878-allfos-nomnp-fullcombine-wrefs-cleaned-annotated.vcf")
m... | src/python/pull_tps_fps.py | import os
base_dir = "/usr/local/projects/xprize/quaternary"
val_vcf = os.path.join(base_dir, "NA12878_validate/inputs/NA12878-sanger-validate-allowone.vcf")
prep_dir = os.path.join(base_dir, "NA12878_fosmid/work/prep")
full_vcf = os.path.join(prep_dir, "NA12878-allfos-nomnp-fullcombine-wrefs-cleaned-annotated.vcf")
m... | 0.188212 | 0.112747 |
__author__ = """<NAME>"""
__email__ = "<EMAIL>"
import numpy as np
label_names = [
[0, "unlabeled"],
[1, "outlier"],
[10, "car"],
[11, "bicycle"],
[13, "bus"],
[15, "motorcycle"],
[16, "on-rails"],
[18, "truck"],
[20, "other-vehicle"],
[30, "person"],
[31, "bicyclist"],
... | data/mapping.py |
__author__ = """<NAME>"""
__email__ = "<EMAIL>"
import numpy as np
label_names = [
[0, "unlabeled"],
[1, "outlier"],
[10, "car"],
[11, "bicycle"],
[13, "bus"],
[15, "motorcycle"],
[16, "on-rails"],
[18, "truck"],
[20, "other-vehicle"],
[30, "person"],
[31, "bicyclist"],
... | 0.5564 | 0.309402 |
from datetime import datetime, time, timedelta
import logging
import voluptuous as vol
from homeassistant.components.calendar import PLATFORM_SCHEMA, CalendarEventDevice
from homeassistant.const import (
CONF_ID,
CONF_NAME,
CONF_TOKEN,
STATE_UNKNOWN,
STATE_UNAVAILABLE,
)
import homeassistant.help... | custom_components/entities_calendar/calendar.py | from datetime import datetime, time, timedelta
import logging
import voluptuous as vol
from homeassistant.components.calendar import PLATFORM_SCHEMA, CalendarEventDevice
from homeassistant.const import (
CONF_ID,
CONF_NAME,
CONF_TOKEN,
STATE_UNKNOWN,
STATE_UNAVAILABLE,
)
import homeassistant.help... | 0.629319 | 0.118105 |
import psycopg2
import os
# Andmebaasi seaded
from auxiliary.database_settings import *
# Kui see väärtus on tõene, lisanduvad andmetabelis mitteesinevad nimed selle lõppu,
# vastasel juhul luuakse värske andmetabel puhtalt andmebaasis oleva teabe põhjal.
APPEND_TO_EXISTING = True
def update_course_tables(keep_exi... | auxiliary/crons/ut_event_type_updater_en.py |
import psycopg2
import os
# Andmebaasi seaded
from auxiliary.database_settings import *
# Kui see väärtus on tõene, lisanduvad andmetabelis mitteesinevad nimed selle lõppu,
# vastasel juhul luuakse värske andmetabel puhtalt andmebaasis oleva teabe põhjal.
APPEND_TO_EXISTING = True
def update_course_tables(keep_exi... | 0.184841 | 0.120853 |
from .constants import DAYS
from .reminders_io import open_json
from .utils import create_reminder, create_reminders
import datetime
import os
import argparse
import sys
class PyReminders(object):
def __init__(self):
parser = argparse.ArgumentParser(
description="Create Apple Reminders through ... | pyreminder/pr.py | from .constants import DAYS
from .reminders_io import open_json
from .utils import create_reminder, create_reminders
import datetime
import os
import argparse
import sys
class PyReminders(object):
def __init__(self):
parser = argparse.ArgumentParser(
description="Create Apple Reminders through ... | 0.262275 | 0.073663 |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import os
import tempfile
import unittest
from chainerrl import repl... | tests/test_replay_buffer.py | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import os
import tempfile
import unittest
from chainerrl import repl... | 0.645343 | 0.294716 |
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import matplotlib.pyplot as plt
import seaborn as sns
# ========== PYQT5 STYLES ============
class TabBar(QTabBar):
def tabSizeHint(self, index):
return QSize(180, 40)
def paintEvent(self, event):
painter = Q... | src/styles.py | from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import matplotlib.pyplot as plt
import seaborn as sns
# ========== PYQT5 STYLES ============
class TabBar(QTabBar):
def tabSizeHint(self, index):
return QSize(180, 40)
def paintEvent(self, event):
painter = Q... | 0.537041 | 0.141163 |
from __future__ import unicode_literals
from datetime import datetime
from rbpkg.repository.package_bundle import PackageBundle
from rbpkg.repository.package_channel import PackageChannel
from rbpkg.repository.package_release import PackageRelease
from rbpkg.repository.tests.testcases import PackagesTestCase
class ... | rbpkg/repository/tests/test_package_bundle.py | from __future__ import unicode_literals
from datetime import datetime
from rbpkg.repository.package_bundle import PackageBundle
from rbpkg.repository.package_channel import PackageChannel
from rbpkg.repository.package_release import PackageRelease
from rbpkg.repository.tests.testcases import PackagesTestCase
class ... | 0.792143 | 0.259427 |
import jax.numpy as jnp
from matplotlib import pyplot as plt
from numpy.linalg import inv
# Local imports
from jsl.experimental.seql.environments.base import make_evenly_spaced_x_sampler
from jsl.experimental.seql.environments.sequential_data_env import SequentialDataEnvironment
from jsl.experimental.seql.utils impor... | jsl/experimental/seql/experiments/linreg_kf_demo.py | import jax.numpy as jnp
from matplotlib import pyplot as plt
from numpy.linalg import inv
# Local imports
from jsl.experimental.seql.environments.base import make_evenly_spaced_x_sampler
from jsl.experimental.seql.environments.sequential_data_env import SequentialDataEnvironment
from jsl.experimental.seql.utils impor... | 0.788665 | 0.567098 |
# -----------------------------------------------------------------------------
import argparse
import json
import os
import re
import sys
# -----------------------------------------------------------------------------
class Namespace():
pass
template = Namespace()
doc = Namespace()
info = Namespace()
# ---------... | build-scripts/gen-layout.py | # -----------------------------------------------------------------------------
import argparse
import json
import os
import re
import sys
# -----------------------------------------------------------------------------
class Namespace():
pass
template = Namespace()
doc = Namespace()
info = Namespace()
# ---------... | 0.304352 | 0.162048 |
import logging
from unittest import mock, TestCase
from destinations.ms_teams import notification_text, send_notification
from models.notification import Notification
from models.metric_notification_data import MetricNotificationData
from ..data_model import DATA_MODEL
@mock.patch("pymsteams.connectorcard.send")
c... | components/notifier/tests/destinations/test_teams.py |
import logging
from unittest import mock, TestCase
from destinations.ms_teams import notification_text, send_notification
from models.notification import Notification
from models.metric_notification_data import MetricNotificationData
from ..data_model import DATA_MODEL
@mock.patch("pymsteams.connectorcard.send")
c... | 0.852813 | 0.260936 |
import pandas as pd
from tqdm import tqdm
import numpy as np
import matplotlib.pyplot as plt
import time
import numpy as np
import os
from transformers import pipeline
import dataframe_image as dfi
import seaborn as sns
import emoji
from nltk.corpus import stopwords
import re
from wordcloud import WordCloud, STOPWORDS,... | api/utils_process.py | import pandas as pd
from tqdm import tqdm
import numpy as np
import matplotlib.pyplot as plt
import time
import numpy as np
import os
from transformers import pipeline
import dataframe_image as dfi
import seaborn as sns
import emoji
from nltk.corpus import stopwords
import re
from wordcloud import WordCloud, STOPWORDS,... | 0.256925 | 0.212497 |
import copy
from pizza_cutter_sims.main import (
run_end2end_with_shear,
run_end2end_pair_with_shear,
)
from pizza_cutter_sims.tests.conftest import recursive_equal
def test_run_end2end_with_shear_seeding(sim_config):
seed_kwargs = dict(
rng_seed=42,
gal_rng_seed=43,
coadd_rng_see... | pizza_cutter_sims/tests/test_main.py | import copy
from pizza_cutter_sims.main import (
run_end2end_with_shear,
run_end2end_pair_with_shear,
)
from pizza_cutter_sims.tests.conftest import recursive_equal
def test_run_end2end_with_shear_seeding(sim_config):
seed_kwargs = dict(
rng_seed=42,
gal_rng_seed=43,
coadd_rng_see... | 0.529507 | 0.342764 |
from ovsdbapp.backend.ovs_idl import fixtures
from ovsdbapp.backend.ovs_idl import vlog
from ovsdbapp.tests import base
class TestOvsdbVlog(base.TestCase):
def setUp(self):
super(TestOvsdbVlog, self).setUp()
self.useFixture(fixtures.OvsdbVlogFixture())
def test_vlog_patched(self):
fo... | ovsdbapp/tests/unit/backend/ovs_idl/test_vlog.py |
from ovsdbapp.backend.ovs_idl import fixtures
from ovsdbapp.backend.ovs_idl import vlog
from ovsdbapp.tests import base
class TestOvsdbVlog(base.TestCase):
def setUp(self):
super(TestOvsdbVlog, self).setUp()
self.useFixture(fixtures.OvsdbVlogFixture())
def test_vlog_patched(self):
fo... | 0.428592 | 0.225129 |
import os
# user-defined modules
import data_loader as dl
import clustering as c
import clustering_prime as c_prime
def raster(all_points, precision, threshold, min_size):
## Step 1: Projection
(tiles, scalar) = c.map_to_tiles(all_points, precision, threshold)
## Step 2: Agglomeration
clusters = c.r... | 2_benchmark_python/raster.py | import os
# user-defined modules
import data_loader as dl
import clustering as c
import clustering_prime as c_prime
def raster(all_points, precision, threshold, min_size):
## Step 1: Projection
(tiles, scalar) = c.map_to_tiles(all_points, precision, threshold)
## Step 2: Agglomeration
clusters = c.r... | 0.66236 | 0.630799 |
import gzip, bz2, codecs, json
from glob import glob
#===============================================
class PlainFileReader:
def __init__(self, fname):
self.mInput = codecs.open(fname, 'r', encoding = 'utf-8')
def next(self):
return self.mInput.readline()
def close(self):
self.mIn... | app/prepare/read_json.py | import gzip, bz2, codecs, json
from glob import glob
#===============================================
class PlainFileReader:
def __init__(self, fname):
self.mInput = codecs.open(fname, 'r', encoding = 'utf-8')
def next(self):
return self.mInput.readline()
def close(self):
self.mIn... | 0.384681 | 0.087994 |
from __future__ import annotations
import asyncio
import copy
from datetime import timedelta
from http import HTTPStatus
import logging
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import aiohttp
from aiohttp import hdrs, web
from aiohttp.web_exceptions import HTTPUnauthorized
import p... | tests/test_views.py | from __future__ import annotations
import asyncio
import copy
from datetime import timedelta
from http import HTTPStatus
import logging
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import aiohttp
from aiohttp import hdrs, web
from aiohttp.web_exceptions import HTTPUnauthorized
import p... | 0.822759 | 0.144873 |
import unittest
import os
from .context import solver
import numpy as np
def diff(m1,m2):
dif = np.abs(m1-m2)
return str(dif)
class TestSolver(unittest.TestCase):
grid =np.array([[0,0,0,0,5,0,0,7,0],
[0,0,0,3,0,0,2,5,0],
[0,0,0,0,0,4,0,3,8],
[0,0... | tests/test_solve.py | import unittest
import os
from .context import solver
import numpy as np
def diff(m1,m2):
dif = np.abs(m1-m2)
return str(dif)
class TestSolver(unittest.TestCase):
grid =np.array([[0,0,0,0,5,0,0,7,0],
[0,0,0,3,0,0,2,5,0],
[0,0,0,0,0,4,0,3,8],
[0,0... | 0.480722 | 0.33846 |
from typing import Dict,Sequence,List
from dmt.entity import Entity
from dmt.blueprint import Blueprint
from .blueprints.jonswap6p import Jonswap6PBlueprint
from typing import Dict
from sima.environment.wave import Wave
from sima.environment.wavespreadingtype import WaveSpreadingType
from sima.sima.scriptablevalue impo... | src/sima/environment/jonswap6p.py | from typing import Dict,Sequence,List
from dmt.entity import Entity
from dmt.blueprint import Blueprint
from .blueprints.jonswap6p import Jonswap6PBlueprint
from typing import Dict
from sima.environment.wave import Wave
from sima.environment.wavespreadingtype import WaveSpreadingType
from sima.sima.scriptablevalue impo... | 0.861042 | 0.460653 |
import os
if int(os.getenv('USE_AGG', 1)) == 1:
import matplotlib
matplotlib.use('Agg')
import argparse
import pandas as pd
import numpy as np
from oaprogression.evaluation import tools
from oaprogression.evaluation.tools import pkl2df
if __name__ == "__main__":
parser = argparse.ArgumentParser()
p... | scripts/run_models_comparison_kl_01.py | import os
if int(os.getenv('USE_AGG', 1)) == 1:
import matplotlib
matplotlib.use('Agg')
import argparse
import pandas as pd
import numpy as np
from oaprogression.evaluation import tools
from oaprogression.evaluation.tools import pkl2df
if __name__ == "__main__":
parser = argparse.ArgumentParser()
p... | 0.231527 | 0.154185 |
from django.conf import settings
import requests
ZERO_RESULTS = "ZERO_RESULTS"
GEOCODING_URL = "https://maps.googleapis.com/maps/api/geocode/json"
def create_geocoding_params(address, country_code):
return {
'components': 'country:{}'.format(country_code),
'address': address,
'key': set... | src/django/api/geocoding.py | from django.conf import settings
import requests
ZERO_RESULTS = "ZERO_RESULTS"
GEOCODING_URL = "https://maps.googleapis.com/maps/api/geocode/json"
def create_geocoding_params(address, country_code):
return {
'components': 'country:{}'.format(country_code),
'address': address,
'key': set... | 0.696371 | 0.369912 |
import numbers
import os
import os.path as osp
import time
import glob
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from mmcv.utils import get_git_hash
from mmdet import __version__
from mmdet.apis import train_detector
from mmdet.datasets import build_dataset
from mmdet.models imp... | mpa/det/trainer.py |
import numbers
import os
import os.path as osp
import time
import glob
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from mmcv.utils import get_git_hash
from mmdet import __version__
from mmdet.apis import train_detector
from mmdet.datasets import build_dataset
from mmdet.models imp... | 0.640299 | 0.154951 |
LANGUAGE = 'pl' # app language
# voice language - see here:https://codelabs.developers.google.com/codelabs/cloud-text-speech-python3/#7 and here: https://cloud.google.com/text-to-speech -> DEMO
import os.path
import argparse
from tts.tts import tts
from tts.fileTypes import fileType
import gettext
import json
... | robot.py | LANGUAGE = 'pl' # app language
# voice language - see here:https://codelabs.developers.google.com/codelabs/cloud-text-speech-python3/#7 and here: https://cloud.google.com/text-to-speech -> DEMO
import os.path
import argparse
from tts.tts import tts
from tts.fileTypes import fileType
import gettext
import json
... | 0.234582 | 0.100481 |
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
from itertools import cycle
from sklearn.metrics import adjusted_rand_score, silhouette_score, silhouette_samples
def output_plot(filename, models, numberized, x_min = -0.1, x_max = 1.0, y_distance = 10, x_step = 0.2):
if (x_min < -1... | clusterizer/plotting.py | import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
from itertools import cycle
from sklearn.metrics import adjusted_rand_score, silhouette_score, silhouette_samples
def output_plot(filename, models, numberized, x_min = -0.1, x_max = 1.0, y_distance = 10, x_step = 0.2):
if (x_min < -1... | 0.452052 | 0.558989 |
import struct
from copy import deepcopy
from typing import Optional, Union
class ByteBuffer:
"""
字节缓冲区
"""
# _bytes = None
# _position = 0
def __init__(self, bs: Optional[Union[bytes, bytearray]] = None):
if bs is None:
self._bytes = bytearray()
elif isinstance(bs... | pyjce/buffer.py | import struct
from copy import deepcopy
from typing import Optional, Union
class ByteBuffer:
"""
字节缓冲区
"""
# _bytes = None
# _position = 0
def __init__(self, bs: Optional[Union[bytes, bytearray]] = None):
if bs is None:
self._bytes = bytearray()
elif isinstance(bs... | 0.795261 | 0.367128 |
import logging
import warnings
from flask import abort, g, make_response
from flask_apispec import FlaskApiSpec, MethodResource, marshal_with, use_kwargs
from sqlalchemy.orm import load_only
from sqlalchemy.orm.exc import NoResultFound
from .jwt import jwt_require_claim, jwt_required
from .models import Model, db
fro... | src/model_storage/resources.py | import logging
import warnings
from flask import abort, g, make_response
from flask_apispec import FlaskApiSpec, MethodResource, marshal_with, use_kwargs
from sqlalchemy.orm import load_only
from sqlalchemy.orm.exc import NoResultFound
from .jwt import jwt_require_claim, jwt_required
from .models import Model, db
fro... | 0.608943 | 0.091463 |
import pygame, time
from pygame.locals import *
from random import shuffle
from constants import *
from player import *
class Tile(pygame.Rect):
def __init__(self, x, y, size, is_safe):
pygame.Rect.__init__(self, x, y, size, size)
if is_safe:
self.color = SAFE_TILE
self.defa... | board.py | import pygame, time
from pygame.locals import *
from random import shuffle
from constants import *
from player import *
class Tile(pygame.Rect):
def __init__(self, x, y, size, is_safe):
pygame.Rect.__init__(self, x, y, size, size)
if is_safe:
self.color = SAFE_TILE
self.defa... | 0.582016 | 0.260159 |
from mock import MagicMock
import pytest
from sonic_platform_base.sonic_xcvr.api.public.cmis import CmisApi
from sonic_platform_base.sonic_xcvr.mem_maps.public.cmis import CmisMemMap
from sonic_platform_base.sonic_xcvr.xcvr_eeprom import XcvrEeprom
from sonic_platform_base.sonic_xcvr.codes.public.cmis import CmisCodes
... | tests/sonic_xcvr/test_cmis.py | from mock import MagicMock
import pytest
from sonic_platform_base.sonic_xcvr.api.public.cmis import CmisApi
from sonic_platform_base.sonic_xcvr.mem_maps.public.cmis import CmisMemMap
from sonic_platform_base.sonic_xcvr.xcvr_eeprom import XcvrEeprom
from sonic_platform_base.sonic_xcvr.codes.public.cmis import CmisCodes
... | 0.723016 | 0.449211 |
import re
import requests
import sys
import threading
import io
import json
from multiprocessing import Pool, freeze_support
from bs4 import BeautifulSoup
lockObj = threading.Lock()
links = []
urlPattern = re.compile(
"(\[([\d\/]+\s*[\d:]+\s*\w+)\]).*((http|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+... | parser/parse.py | import re
import requests
import sys
import threading
import io
import json
from multiprocessing import Pool, freeze_support
from bs4 import BeautifulSoup
lockObj = threading.Lock()
links = []
urlPattern = re.compile(
"(\[([\d\/]+\s*[\d:]+\s*\w+)\]).*((http|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+... | 0.146545 | 0.066904 |
import torch
import torch.nn.functional as F
import math
def entropy(relation_matrix):
"""
:param relation_matrix: (B, Ni, Nj)
:return: (B, Ni)
"""
return - torch.sum(relation_matrix * torch.log2(relation_matrix + 1e-7), dim=-1)
def perplexity(relation_matrix):
"""
:param relation_matrix... | relation/perplexity_entropy.py | import torch
import torch.nn.functional as F
import math
def entropy(relation_matrix):
"""
:param relation_matrix: (B, Ni, Nj)
:return: (B, Ni)
"""
return - torch.sum(relation_matrix * torch.log2(relation_matrix + 1e-7), dim=-1)
def perplexity(relation_matrix):
"""
:param relation_matrix... | 0.833968 | 0.72205 |
from math import degrees, atan2
from time import sleep
from pixy2 import (
Pixy2,
MainFeatures,
BARCODE_DEACTIVATE,
BARCODE_ACTIVATE,
BARCODE_FORWARD,
BARCODE_LEFT,
BARCODE_RIGHT,
)
from robot import Robot
# Defining constants
X_REF = 39 # X-center coordinate of view
Y_REF = 25 # Y... | Pixy2/linetracker/linetracker.py | from math import degrees, atan2
from time import sleep
from pixy2 import (
Pixy2,
MainFeatures,
BARCODE_DEACTIVATE,
BARCODE_ACTIVATE,
BARCODE_FORWARD,
BARCODE_LEFT,
BARCODE_RIGHT,
)
from robot import Robot
# Defining constants
X_REF = 39 # X-center coordinate of view
Y_REF = 25 # Y... | 0.638723 | 0.219609 |
# Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Tests for /query api search"""
import ddt
from ggrc.models import all_models
from integration.ggrc import TestCase
from integration.ggrc import api_helper
from integration.ggrc.models import factories... | test/integration/ggrc/services/test_authorizations.py |
# Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Tests for /query api search"""
import ddt
from ggrc.models import all_models
from integration.ggrc import TestCase
from integration.ggrc import api_helper
from integration.ggrc.models import factories... | 0.747063 | 0.196961 |
import sys
import os
import argparse as ap
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
plt.style.use(('presentation',))
from nanowire.optics.postprocess import Simulation
from nanowire.optics.utils.config import Config
from matplotlib.colors import LogNorm
def get_middle_slice(sim):
if 'n... | misc/comsol_compare.py | import sys
import os
import argparse as ap
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
plt.style.use(('presentation',))
from nanowire.optics.postprocess import Simulation
from nanowire.optics.utils.config import Config
from matplotlib.colors import LogNorm
def get_middle_slice(sim):
if 'n... | 0.335895 | 0.448185 |
from math import radians, cos, sin, asin, sqrt
import folium
import pandas as pd
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderUnavailable
import file_process as fp
def user_interaction() -> tuple:
'''
Returns information from user about user location, preferred year
and path to the ... | main.py | from math import radians, cos, sin, asin, sqrt
import folium
import pandas as pd
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderUnavailable
import file_process as fp
def user_interaction() -> tuple:
'''
Returns information from user about user location, preferred year
and path to the ... | 0.439026 | 0.411702 |
import json
import threading
import unittest
import onedrivesdk
from onedrived import get_resource, od_webhook
from tests.test_repo import get_sample_repo
class TestWebhookWorker(unittest.TestCase):
def setUp(self):
self.temp_config_dir, self.temp_repo_dir, self.drive_config, self.repo = get_sample_re... | tests/test_webhook_worker.py | import json
import threading
import unittest
import onedrivesdk
from onedrived import get_resource, od_webhook
from tests.test_repo import get_sample_repo
class TestWebhookWorker(unittest.TestCase):
def setUp(self):
self.temp_config_dir, self.temp_repo_dir, self.drive_config, self.repo = get_sample_re... | 0.276397 | 0.079675 |
import os
from pathlib import Path, WindowsPath
from tempfile import TemporaryDirectory
from typing import List
from unittest.mock import patch
import appdirs
import pytest
from hypothesis import assume, given
from hypothesis.strategies import characters, integers, lists, sampled_from, text
from semantic_version impor... | tests/context/test_system.py | import os
from pathlib import Path, WindowsPath
from tempfile import TemporaryDirectory
from typing import List
from unittest.mock import patch
import appdirs
import pytest
from hypothesis import assume, given
from hypothesis.strategies import characters, integers, lists, sampled_from, text
from semantic_version impor... | 0.780035 | 0.327117 |
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from pydis_site.apps.api.models.bot.role import Role
from pydis_site.apps.api.models.utils import ModelReprMixin
... | pydis_site/apps/api/models/bot/user.py | from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from pydis_site.apps.api.models.bot.role import Role
from pydis_site.apps.api.models.utils import ModelReprMixin
... | 0.849222 | 0.141074 |
from http_lock import HttpLock
import os # Used for os.getpid()
import unittest
from webkitpy.common.system.filesystem_mock import MockFileSystem
from webkitpy.common.system.executive_mock import MockExecutive
# FIXME: These tests all touch the real disk, but could be written to a MockFileSystem instead.
class Htt... | WebKit/Tools/Scripts/webkitpy/layout_tests/port/http_lock_unittest.py |
from http_lock import HttpLock
import os # Used for os.getpid()
import unittest
from webkitpy.common.system.filesystem_mock import MockFileSystem
from webkitpy.common.system.executive_mock import MockExecutive
# FIXME: These tests all touch the real disk, but could be written to a MockFileSystem instead.
class Htt... | 0.269518 | 0.119923 |
config = {
'server': {
'url': 'https://mit.kairosconnect.app/',
'token_file': '.token',
},
'cameras': {
'DTevar-culhuacan-34:56:fe:a3:99:de':
{
'source': "file:///home/aaeon/Downloads/ejercicio2/video3.mp4",
... | python/apps/kairos/configs/Server_Emulatation_configs.py | config = {
'server': {
'url': 'https://mit.kairosconnect.app/',
'token_file': '.token',
},
'cameras': {
'DTevar-culhuacan-34:56:fe:a3:99:de':
{
'source': "file:///home/aaeon/Downloads/ejercicio2/video3.mp4",
... | 0.415492 | 0.215774 |
from tensorflow.keras import layers, models
from tensorflow.python.keras.utils import data_utils
from nets.MaxPoolingWithIndices2D import MaxPoolingWithIndices2D
from nets.MaxUnpoolingWithIndices2D import MaxUnpoolingWithIndices2D
import os
def SegNet(input_shape, num_classes):
"""
论文中介绍的SegNet网络
:param ... | nets/SegNet.py |
from tensorflow.keras import layers, models
from tensorflow.python.keras.utils import data_utils
from nets.MaxPoolingWithIndices2D import MaxPoolingWithIndices2D
from nets.MaxUnpoolingWithIndices2D import MaxUnpoolingWithIndices2D
import os
def SegNet(input_shape, num_classes):
"""
论文中介绍的SegNet网络
:param ... | 0.844633 | 0.811601 |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from utils.utils_metrics import evaluate
def get_lr(optimizer):
for param_group in optimizer.param_groups:
return param_group['lr']
def fit_one_epoch(model_train, model, loss_history,... | utils/utils_fit.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from utils.utils_metrics import evaluate
def get_lr(optimizer):
for param_group in optimizer.param_groups:
return param_group['lr']
def fit_one_epoch(model_train, model, loss_history,... | 0.556159 | 0.329055 |
import logging
import os
import ssl
import time
import uuid
import paho
import paho.mqtt.client as mqtt
from ...tools import Signal
class MQTT(object):
"""
Generic MQTT handler for backend client sessions
"""
def __init__(
self,
username: str,
password: str,
hostname... | wirepas_backend_client/api/mqtt/connectors.py | import logging
import os
import ssl
import time
import uuid
import paho
import paho.mqtt.client as mqtt
from ...tools import Signal
class MQTT(object):
"""
Generic MQTT handler for backend client sessions
"""
def __init__(
self,
username: str,
password: str,
hostname... | 0.434941 | 0.080213 |
from __future__ import absolute_import, unicode_literals
import pytest
import logging
from psd_tools.api.psd_image import PSDImage
from psd_tools.api.shape import (
Rectangle, RoundedRectangle, Ellipse, Line, Invalidated
)
from ..utils import full_name
logger = logging.getLogger(__name__)
VECTOR_MASK2 = PSDImag... | tests/psd_tools/api/test_shape.py | from __future__ import absolute_import, unicode_literals
import pytest
import logging
from psd_tools.api.psd_image import PSDImage
from psd_tools.api.shape import (
Rectangle, RoundedRectangle, Ellipse, Line, Invalidated
)
from ..utils import full_name
logger = logging.getLogger(__name__)
VECTOR_MASK2 = PSDImag... | 0.695028 | 0.589687 |
import os
import pickle
import torch
import nn as mynn
import utils.detectron_weight_helper as dwh
from core.config import cfg
def load_pretrained_imagenet_weights(model):
"""Load pretrained weights
Args:
model: the generalized rcnnn module
"""
_, ext = os.path.splitext(cfg.VGG.IMAGENET_PRET... | lib/utils/vgg_weights_helper.py | import os
import pickle
import torch
import nn as mynn
import utils.detectron_weight_helper as dwh
from core.config import cfg
def load_pretrained_imagenet_weights(model):
"""Load pretrained weights
Args:
model: the generalized rcnnn module
"""
_, ext = os.path.splitext(cfg.VGG.IMAGENET_PRET... | 0.471223 | 0.24726 |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from fastfold.model.fastnn.kernel import LayerNorm
from fastfold.model.fastnn.ops import Transition, SelfAttention
from fastfold.model.fastnn.kernel import bias_dropout_add
from fastfold.distributed import scatter, row_to_col
from fastfold... | fastfold/model/fastnn/msa.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from fastfold.model.fastnn.kernel import LayerNorm
from fastfold.model.fastnn.ops import Transition, SelfAttention
from fastfold.model.fastnn.kernel import bias_dropout_add
from fastfold.distributed import scatter, row_to_col
from fastfold... | 0.937598 | 0.396185 |
from __future__ import (absolute_import, division, print_function)#, unicode_literals)
from __future__ import print_function
import unittest
from nix import *
import numpy as np
class TestMultiTag(unittest.TestCase):
def setUp(self):
self.file = File.open("unittest.h5", FileMode.Overwrite)
... | nix/test/test_multi_tag.py |
from __future__ import (absolute_import, division, print_function)#, unicode_literals)
from __future__ import print_function
import unittest
from nix import *
import numpy as np
class TestMultiTag(unittest.TestCase):
def setUp(self):
self.file = File.open("unittest.h5", FileMode.Overwrite)
... | 0.546254 | 0.451145 |
import os
from typing import Any, Dict, List, Optional
from bs4 import BeautifulSoup, Comment
from sphinx.application import Sphinx
from sphinx.util import logging
from . import __version__
from .icons import ICONS
logger = logging.getLogger(__name__)
def _get_html_files(outdir: str) -> List[str]:
"""Get a lis... | src/sphinxawesome_theme/postprocess.py | import os
from typing import Any, Dict, List, Optional
from bs4 import BeautifulSoup, Comment
from sphinx.application import Sphinx
from sphinx.util import logging
from . import __version__
from .icons import ICONS
logger = logging.getLogger(__name__)
def _get_html_files(outdir: str) -> List[str]:
"""Get a lis... | 0.808143 | 0.154631 |
import json
from enum import Enum
import requests
from openpyxl import Workbook
columnnames = ["编号", "中文名", "英语名", "类别", "法术力费用",
"异能", "稀有度", "攻防", "现开", "轮抓", "构筑"]
raritytranslation = {"common": "普通",
"uncommon": "非普通", "rare": "稀有", "mythic": "秘稀"}
class Languages(Enum):
... | scripts/RatingTableGenerator.py | import json
from enum import Enum
import requests
from openpyxl import Workbook
columnnames = ["编号", "中文名", "英语名", "类别", "法术力费用",
"异能", "稀有度", "攻防", "现开", "轮抓", "构筑"]
raritytranslation = {"common": "普通",
"uncommon": "非普通", "rare": "稀有", "mythic": "秘稀"}
class Languages(Enum):
... | 0.301979 | 0.122576 |
import collections
import typing
from abc import ABCMeta, abstractmethod
from copy import deepcopy
from enum import Enum
from qtpy.QtCore import Signal
from qtpy.QtGui import QHideEvent, QPainter, QPaintEvent
from qtpy.QtWidgets import (
QApplication,
QCheckBox,
QComboBox,
QFormLayout,
QLabel,
... | package/PartSeg/common_gui/algorithms_description.py | import collections
import typing
from abc import ABCMeta, abstractmethod
from copy import deepcopy
from enum import Enum
from qtpy.QtCore import Signal
from qtpy.QtGui import QHideEvent, QPainter, QPaintEvent
from qtpy.QtWidgets import (
QApplication,
QCheckBox,
QComboBox,
QFormLayout,
QLabel,
... | 0.695028 | 0.13319 |
import os
from jasy import UserError
import jasy.core.File as File
class AbstractItem(object):
id = None
project = None
kind = "jasy.Item"
mtime = None
__path = None
__cache = None
__text = None
__textFilter = None
__filteredText = None
@classmethod
def fromPath(cls, ... | jasy/item/Abstract.py |
import os
from jasy import UserError
import jasy.core.File as File
class AbstractItem(object):
id = None
project = None
kind = "jasy.Item"
mtime = None
__path = None
__cache = None
__text = None
__textFilter = None
__filteredText = None
@classmethod
def fromPath(cls, ... | 0.475605 | 0.085327 |
import os
import pathlib
from pprint import pprint
import numpy as np
from scipy import stats
from scipy.spatial import distance
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import trajectorytools as tt
import trajectorytools.plot as ttplot
import trajectorytools.socialcontext as ttsocial
from... | masked_data_csv.py | import os
import pathlib
from pprint import pprint
import numpy as np
from scipy import stats
from scipy.spatial import distance
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import trajectorytools as tt
import trajectorytools.plot as ttplot
import trajectorytools.socialcontext as ttsocial
from... | 0.173044 | 0.372277 |
import cvxpy as cp
from cvxpylayers.torch import CvxpyLayer
import torch
from torch.distributions import MultivariateNormal
import torch.nn as nn
from .misc import Cov2Corr, CovarianceMatrix, KMeans
class AnalyticalMarkowitz(nn.Module):
"""Minimum variance and maximum sharpe ratio with no constraints.
Ther... | deepdow/layers/allocate.py |
import cvxpy as cp
from cvxpylayers.torch import CvxpyLayer
import torch
from torch.distributions import MultivariateNormal
import torch.nn as nn
from .misc import Cov2Corr, CovarianceMatrix, KMeans
class AnalyticalMarkowitz(nn.Module):
"""Minimum variance and maximum sharpe ratio with no constraints.
Ther... | 0.968186 | 0.77768 |
from datetime import date
import pytest
import wikirepo
from wikirepo.data import data_utils, lctn_utils, wd_utils
entities_dict = wd_utils.EntitiesDict()
countries = ["Germany"]
depth = 0
timespan = (date(2009, 1, 1), date(2010, 1, 1))
interval = "yearly"
# Test of values for a given timespan.
df_timespan = wikirep... | tests/conftest.py | from datetime import date
import pytest
import wikirepo
from wikirepo.data import data_utils, lctn_utils, wd_utils
entities_dict = wd_utils.EntitiesDict()
countries = ["Germany"]
depth = 0
timespan = (date(2009, 1, 1), date(2010, 1, 1))
interval = "yearly"
# Test of values for a given timespan.
df_timespan = wikirep... | 0.504394 | 0.520131 |
from unittest import mock
import unittest
import os
import shutil
import zipfile
from datetime import datetime, timezone
from base64 import b64decode
from webscrapbook import WSB_DIR
from webscrapbook import util
from webscrapbook.scrapbook.host import Host
from webscrapbook.scrapbook.check import BookChecker
root_di... | test/test_scrapbook_check.py | from unittest import mock
import unittest
import os
import shutil
import zipfile
from datetime import datetime, timezone
from base64 import b64decode
from webscrapbook import WSB_DIR
from webscrapbook import util
from webscrapbook.scrapbook.host import Host
from webscrapbook.scrapbook.check import BookChecker
root_di... | 0.450359 | 0.360236 |
import logging
import os
import sys
import torch
from torch import nn, optim
from clustre.helpers.datasets import (cifar10_testloader, cifar10_trainloader,
mnist_testloader, mnist_trainloader)
from clustre.helpers.metrics import (classification_report,
... | experiments/attacking/fgsm.py | import logging
import os
import sys
import torch
from torch import nn, optim
from clustre.helpers.datasets import (cifar10_testloader, cifar10_trainloader,
mnist_testloader, mnist_trainloader)
from clustre.helpers.metrics import (classification_report,
... | 0.40251 | 0.230595 |
import numpy as np
from skge.base import Model
from skge.util import grad_sum_matrix, unzip_triples, ccorr, cconv
from skge.param import normless1
import skge.actfun as af
import timeit
class HolE(Model):
def __init__(self, *args, **kwargs):
super(HolE, self).__init__(*args, **kwargs)
self.add_hyp... | skge/hole.py | import numpy as np
from skge.base import Model
from skge.util import grad_sum_matrix, unzip_triples, ccorr, cconv
from skge.param import normless1
import skge.actfun as af
import timeit
class HolE(Model):
def __init__(self, *args, **kwargs):
super(HolE, self).__init__(*args, **kwargs)
self.add_hyp... | 0.54577 | 0.439687 |
#...for the OS stuff.
import os
#...for the logging.
import logging as lg
#...for the plotting.
import matplotlib.pyplot as plt
#...for the MATH.
import numpy as np
# Load the LaTeX text plot libraries.
from matplotlib import rc
# Uncomment to use LaTeX for the plot text.
rc('font',**{'family':'serif','serif':['C... | wrappers/plotting.py |
#...for the OS stuff.
import os
#...for the logging.
import logging as lg
#...for the plotting.
import matplotlib.pyplot as plt
#...for the MATH.
import numpy as np
# Load the LaTeX text plot libraries.
from matplotlib import rc
# Uncomment to use LaTeX for the plot text.
rc('font',**{'family':'serif','serif':['C... | 0.679285 | 0.442877 |
import os
import argparse
from google.cloud import spanner
from subprocess import call, run, PIPE
def set_credentials(path_to_json_file):
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = path_to_json_file
def main_run(args):
create_instance(args)
spanner_client = spanner.Client()
instance = spanner_c... | cloud_spanner/spanner_setup.py | import os
import argparse
from google.cloud import spanner
from subprocess import call, run, PIPE
def set_credentials(path_to_json_file):
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = path_to_json_file
def main_run(args):
create_instance(args)
spanner_client = spanner.Client()
instance = spanner_c... | 0.268749 | 0.07072 |
from flask import g
from . import user
from app.modules.base.base_handler import BaseHandler
from app.modules.vendor.pre_request.flask import filter_params
from app.modules.vendor.pre_request.filter_rules import Rule, Length
from app.models.account.aha_account import AhaAccountModel
from app.models.account.user_black... | app/modules/user/user_black.py | from flask import g
from . import user
from app.modules.base.base_handler import BaseHandler
from app.modules.vendor.pre_request.flask import filter_params
from app.modules.vendor.pre_request.filter_rules import Rule, Length
from app.models.account.aha_account import AhaAccountModel
from app.models.account.user_black... | 0.334916 | 0.054803 |
import pytest
import time
from os import path
from flask import Flask, session, jsonify
from flask.sessions import SecureCookieSessionInterface
from beaker.middleware import SessionMiddleware
from flask_beaker_session import config, session as beaker_session, errors, session_interface
from unittest.mock import Mock
... | tests/test_session.py | import pytest
import time
from os import path
from flask import Flask, session, jsonify
from flask.sessions import SecureCookieSessionInterface
from beaker.middleware import SessionMiddleware
from flask_beaker_session import config, session as beaker_session, errors, session_interface
from unittest.mock import Mock
... | 0.468547 | 0.253548 |
# 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
# Unless required by applicable law or agreed to in writing, software
# distributed under the Licens... | setup.py |
# 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
# Unless required by applicable law or agreed to in writing, software
# distributed under the Licens... | 0.861786 | 0.343397 |
import numpy as np
from .vectors import hat, norm, lonlat
from .quaternions import q_rot
SUN_RADIUS = 6.955e5 # km
def specular_angle(beta, dist, radius, debug=False):
'''Find specular angle with SS in the SS-O-SC plane.
Parameters
----------
beta: float
Angle between SS and SC (radians)... | pyvims/specular.py |
import numpy as np
from .vectors import hat, norm, lonlat
from .quaternions import q_rot
SUN_RADIUS = 6.955e5 # km
def specular_angle(beta, dist, radius, debug=False):
'''Find specular angle with SS in the SS-O-SC plane.
Parameters
----------
beta: float
Angle between SS and SC (radians)... | 0.92153 | 0.83025 |