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 os
from pygments import highlight
from pygments import lexers
from pygments.lexers import get_lexer_for_mimetype
from pygments import styles
from pygments.util import ClassNotFound
from pygments.formatters import BBCodeFormatter
from kivy.uix.codeinput import CodeInput
from kivy.uix.floatlayout import FloatLayo... | editorcontainer/editor/editor.py | import os
from pygments import highlight
from pygments import lexers
from pygments.lexers import get_lexer_for_mimetype
from pygments import styles
from pygments.util import ClassNotFound
from pygments.formatters import BBCodeFormatter
from kivy.uix.codeinput import CodeInput
from kivy.uix.floatlayout import FloatLayo... | 0.632389 | 0.200656 |
import dask.bag as db
import json
import pytest
import pkg_resources
import glob
import os
from impresso_commons.utils.s3 import get_bucket, get_s3_versions, read_jsonlines
from impresso_commons.utils.daskutils import create_even_partitions
from impresso_commons.utils.config_loader import TextImporterConfig
def test... | tests/utils/test_s3.py | import dask.bag as db
import json
import pytest
import pkg_resources
import glob
import os
from impresso_commons.utils.s3 import get_bucket, get_s3_versions, read_jsonlines
from impresso_commons.utils.daskutils import create_even_partitions
from impresso_commons.utils.config_loader import TextImporterConfig
def test... | 0.347869 | 0.226805 |
import re
import requests
import time
import random
import http.cookiejar
import datetime
import ConstantQuantity as cq
session = requests.Session()
BaiduUsername = ""
BaiduPassword = ""
BaiduURLCaptcha = ""
BaiduToken = ""
BaiduVerifyCode = ""
BaiduCodeString = ""
TimeNow = (datetime.datetime.utcnow() + datetime.time... | ModuleLoginTieba.py | import re
import requests
import time
import random
import http.cookiejar
import datetime
import ConstantQuantity as cq
session = requests.Session()
BaiduUsername = ""
BaiduPassword = ""
BaiduURLCaptcha = ""
BaiduToken = ""
BaiduVerifyCode = ""
BaiduCodeString = ""
TimeNow = (datetime.datetime.utcnow() + datetime.time... | 0.079806 | 0.120155 |
import numpy as np
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import math
import os
import shutil
import mplleaflet
class rousys:
def __init__(self, inp_folder = '', crs = 35, typ = 7, vbase = 415, sbase = 1):
#Geogaphical locations of all nodes
... | pyeplan/routing.py | import numpy as np
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import math
import os
import shutil
import mplleaflet
class rousys:
def __init__(self, inp_folder = '', crs = 35, typ = 7, vbase = 415, sbase = 1):
#Geogaphical locations of all nodes
... | 0.365004 | 0.29175 |
import board
import neopixel
import time
import random
from analogio import AnalogIn
from adafruit_circuitplayground.express import cpx
RED = (0x10, 0, 0) # 0x100000 also works
YELLOW=(0x10, 0x10, 0)
GREEN = (0, 0x10, 0)
AQUA = (0, 0x10, 0x10)
BLUE = (0, 0, 0x10)
PURPLE = (0x10, 0, 0x10)
BLACK = (0, 0, 0)
WHITE = (25... | code.py |
import board
import neopixel
import time
import random
from analogio import AnalogIn
from adafruit_circuitplayground.express import cpx
RED = (0x10, 0, 0) # 0x100000 also works
YELLOW=(0x10, 0x10, 0)
GREEN = (0, 0x10, 0)
AQUA = (0, 0x10, 0x10)
BLUE = (0, 0, 0x10)
PURPLE = (0x10, 0, 0x10)
BLACK = (0, 0, 0)
WHITE = (25... | 0.325413 | 0.312377 |
from collections import defaultdict
from typing import Dict
import torch as th
import torch.distributions as td
import torch.nn.functional as F
from rls.algorithms.base.marl_off_policy import MultiAgentOffPolicy
from rls.common.data import Data
from rls.common.decorator import iton
from rls.nn.models impo... | rls/algorithms/multi/maddpg.py |
from collections import defaultdict
from typing import Dict
import torch as th
import torch.distributions as td
import torch.nn.functional as F
from rls.algorithms.base.marl_off_policy import MultiAgentOffPolicy
from rls.common.data import Data
from rls.common.decorator import iton
from rls.nn.models impo... | 0.589835 | 0.228038 |
import os
import time
from datetime import datetime
import numpy as np
from AirSimClient import CarClient, CarControls
from prep_data import Point
class DataControl:
def __init__(self):
self.x1 = Point(0, 0)
self.x2 = Point(0, 0)
self.x3 = Point(0, 0)
self.speed1 = 0
self.... | random_collection.py | import os
import time
from datetime import datetime
import numpy as np
from AirSimClient import CarClient, CarControls
from prep_data import Point
class DataControl:
def __init__(self):
self.x1 = Point(0, 0)
self.x2 = Point(0, 0)
self.x3 = Point(0, 0)
self.speed1 = 0
self.... | 0.325949 | 0.221919 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may no... | networkapi/ambiente/resource/EnvironmentIpConfigResource.py |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may no... | 0.744656 | 0.067026 |
"""Test class for the relay derating module."""
# Third Party Imports
import pytest
# RAMSTK Package Imports
from ramstk.analyses.derating import relay
@pytest.mark.unit
def test_do_derating_analysis_no_stresses(test_stress_limits):
"""should determine the relay is not execeeding any limit."""
_overstress, ... | tests/analyses/derating/models/relay_derating_unit_test.py | """Test class for the relay derating module."""
# Third Party Imports
import pytest
# RAMSTK Package Imports
from ramstk.analyses.derating import relay
@pytest.mark.unit
def test_do_derating_analysis_no_stresses(test_stress_limits):
"""should determine the relay is not execeeding any limit."""
_overstress, ... | 0.902559 | 0.511046 |
import logging
import requests
import urllib3
from trans_sec.exceptions import NotFoundError, AlreadyExistsError
urllib3.disable_warnings()
logger = logging.getLogger('http_session')
class HttpSession:
def __init__(self, url, username=None, password=<PASSWORD>, verify_cert=False):
self.username = usern... | trans_sec/utils/http_session.py | import logging
import requests
import urllib3
from trans_sec.exceptions import NotFoundError, AlreadyExistsError
urllib3.disable_warnings()
logger = logging.getLogger('http_session')
class HttpSession:
def __init__(self, url, username=None, password=<PASSWORD>, verify_cert=False):
self.username = usern... | 0.18591 | 0.104067 |
from pathlib import Path
from math import *
import functools
import numpy as np
import tensorflow as tf
from tensorflow import keras
import config
def format_percentage2(n):
return floor(n * 10000) / 100
# init variables
IMAGE_SIZE = (config.MODEL_INPUT_SIZE, config.MODEL_INPUT_SIZE)
print(f'Using {config.MODEL... | 7_evaluate_model.py | from pathlib import Path
from math import *
import functools
import numpy as np
import tensorflow as tf
from tensorflow import keras
import config
def format_percentage2(n):
return floor(n * 10000) / 100
# init variables
IMAGE_SIZE = (config.MODEL_INPUT_SIZE, config.MODEL_INPUT_SIZE)
print(f'Using {config.MODEL... | 0.587825 | 0.28763 |
import json
from django.utils import timezone
from agiletixapi import AgileError, AgileSalesAPI
from agiletixapi.exceptions import AgileException, InvalidPromoException
from agiletixapi.models import Order
from agiletixapi.utils import datestring_to_ms_datestring
from agiletix.logging import get_logger
logger = get_l... | agiletix/cart.py | import json
from django.utils import timezone
from agiletixapi import AgileError, AgileSalesAPI
from agiletixapi.exceptions import AgileException, InvalidPromoException
from agiletixapi.models import Order
from agiletixapi.utils import datestring_to_ms_datestring
from agiletix.logging import get_logger
logger = get_l... | 0.145115 | 0.061706 |
__author__ = "chaitanya"
from collections import defaultdict
class Graph:
def __init__(self, directed=True):
self.relations = defaultdict()
self.nodes = defaultdict()
self.node2id = {}
self.relation2id = {}
self.edges = {}
self.edgeCount = 0
self.directed ... | src/graph.py | __author__ = "chaitanya"
from collections import defaultdict
class Graph:
def __init__(self, directed=True):
self.relations = defaultdict()
self.nodes = defaultdict()
self.node2id = {}
self.relation2id = {}
self.edges = {}
self.edgeCount = 0
self.directed ... | 0.780704 | 0.293151 |
import ftplib
from io import BytesIO
from pathlib import Path
from typing import Union, List
class FTP(ftplib.FTP):
"""
A modified FTP class that has the capabilities to scan a ftp directory
and provide easy to use download functions with out the need to build
request strings or similiar stuff.
""... | python_dwd/download/ftp_handling.py | import ftplib
from io import BytesIO
from pathlib import Path
from typing import Union, List
class FTP(ftplib.FTP):
"""
A modified FTP class that has the capabilities to scan a ftp directory
and provide easy to use download functions with out the need to build
request strings or similiar stuff.
""... | 0.852076 | 0.361334 |
def snail(a: list[int]) -> list[int]:
pos, start, limit = [], 0, len(a) - 1
while limit:
r = [[start, i] for i in range(start, limit)]
d = [[i, limit] for i in range(start, limit)]
l = [[limit, i] for i in range(limit, start, -1)]
u = [[i, start] for i in range(limit, start, -1)]... | 4kyu/snail.py | def snail(a: list[int]) -> list[int]:
pos, start, limit = [], 0, len(a) - 1
while limit:
r = [[start, i] for i in range(start, limit)]
d = [[i, limit] for i in range(start, limit)]
l = [[limit, i] for i in range(limit, start, -1)]
u = [[i, start] for i in range(limit, start, -1)]... | 0.266453 | 0.495117 |
import codecs
import csv
import hashlib
import logging
import os
import random
import zipfile
import tensorflow as tf
from .. import settings, utils as rainbow_utils
from . import preparer, utils as preparer_utils
logger = logging.getLogger(__name__)
# main class
class JOCIPreparer(preparer.Preparer):
"""P... | src/rainbow/preparation/joci.py |
import codecs
import csv
import hashlib
import logging
import os
import random
import zipfile
import tensorflow as tf
from .. import settings, utils as rainbow_utils
from . import preparer, utils as preparer_utils
logger = logging.getLogger(__name__)
# main class
class JOCIPreparer(preparer.Preparer):
"""P... | 0.627152 | 0.242463 |
import subprocess
class CEosAccount:
def __init__(self, account):
self.set(account)
def set(self, account):
if len(account) != 12:
raise ValueError("unvalid format of @account")
self.a = account
def __str__(self):
return self.a
class CleosCmdBuiler:
... | safecode-env-test/sc-et_u16/docker-fs-root/home/sc-test/script/test-ram/utils.py |
import subprocess
class CEosAccount:
def __init__(self, account):
self.set(account)
def set(self, account):
if len(account) != 12:
raise ValueError("unvalid format of @account")
self.a = account
def __str__(self):
return self.a
class CleosCmdBuiler:
... | 0.495361 | 0.092033 |
import unittest
import sqlite3 as sqlite
from collections import Sequence
class MyConnection(sqlite.Connection):
def __init__(self, *args, **kwargs):
sqlite.Connection.__init__(self, *args, **kwargs)
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[co... | pypy.js-0.2.0/lib/modules/sqlite3/test/factory.py |
import unittest
import sqlite3 as sqlite
from collections import Sequence
class MyConnection(sqlite.Connection):
def __init__(self, *args, **kwargs):
sqlite.Connection.__init__(self, *args, **kwargs)
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[co... | 0.735071 | 0.475727 |
import threading
import time
class database:
DATA = {}
DATABASES = [{} for x in range(16)]
TTL = {}
LOCK = threading.Lock()
CONFIG = {"databases": "16"}
@staticmethod
def select(db_index):
if database.LOCK.acquire():
database.DATA = database.DATABASES[int(db_index)]
... | src/redis_server/store.py | import threading
import time
class database:
DATA = {}
DATABASES = [{} for x in range(16)]
TTL = {}
LOCK = threading.Lock()
CONFIG = {"databases": "16"}
@staticmethod
def select(db_index):
if database.LOCK.acquire():
database.DATA = database.DATABASES[int(db_index)]
... | 0.384681 | 0.073563 |
import os
import argparse
import re
import pandas as pd
import torch
import torchtext
class DataFrameDataset(torchtext.data.Dataset):
"""Class for using pandas DataFrames as a datasource"""
def __init__(self, examples, fields, filter_pred=None):
"""
Create a dataset from a pandas dataframe of... | helpers.py | import os
import argparse
import re
import pandas as pd
import torch
import torchtext
class DataFrameDataset(torchtext.data.Dataset):
"""Class for using pandas DataFrames as a datasource"""
def __init__(self, examples, fields, filter_pred=None):
"""
Create a dataset from a pandas dataframe of... | 0.636805 | 0.365796 |
# module typing is standard in Python 3.5+: https://docs.python.org/3/library/typing.html
# used for type hints used in static type checking in PEP 484
# PEP 484 -- Type Hints: https://www.python.org/dev/peps/pep-0484/
# PEP 525 -- Syntax for Variable Annotations: https://www.python.org/dev/peps/pep-0526/
# use mypy fo... | MediaComp/sounds.py | # module typing is standard in Python 3.5+: https://docs.python.org/3/library/typing.html
# used for type hints used in static type checking in PEP 484
# PEP 484 -- Type Hints: https://www.python.org/dev/peps/pep-0484/
# PEP 525 -- Syntax for Variable Annotations: https://www.python.org/dev/peps/pep-0526/
# use mypy fo... | 0.850189 | 0.565419 |
"""Generates a self-signed CA cert or a CSR for an API Gateway domain."""
import argparse
import datetime
import os
import re
import shutil
import subprocess
import sys
import time
from utils.utils import VERSION, fail, runOpenSslCmd
def _parseArgs():
parser = argparse.ArgumentParser(
description="Genera... | gen_domain_cert.py | """Generates a self-signed CA cert or a CSR for an API Gateway domain."""
import argparse
import datetime
import os
import re
import shutil
import subprocess
import sys
import time
from utils.utils import VERSION, fail, runOpenSslCmd
def _parseArgs():
parser = argparse.ArgumentParser(
description="Genera... | 0.486332 | 0.153454 |
from __future__ import unicode_literals
import json
from multiprocessing import Process
from willie import web
from willie.module import commands, example, NOLIMIT, interval
def poll_minecraft(bot):
url = bot.config.minecraft.url
try:
minecraft_data = json.loads(web.get(url))
players = [player['name'] for p... | willie/modules/minecraft_logins.py | from __future__ import unicode_literals
import json
from multiprocessing import Process
from willie import web
from willie.module import commands, example, NOLIMIT, interval
def poll_minecraft(bot):
url = bot.config.minecraft.url
try:
minecraft_data = json.loads(web.get(url))
players = [player['name'] for p... | 0.316581 | 0.099602 |
import re
import time
from selenium.webdriver.common.by import By
from common.utils import plex_find_lib, get_static_html, text_format
from common.dictionary import translate_text, convert_chinese_number
def get_metadata(driver, plex, plex_title="", replace_poster="", print_only=False, season_index=1):
if len(dri... | services/thetvdb.py | import re
import time
from selenium.webdriver.common.by import By
from common.utils import plex_find_lib, get_static_html, text_format
from common.dictionary import translate_text, convert_chinese_number
def get_metadata(driver, plex, plex_title="", replace_poster="", print_only=False, season_index=1):
if len(dri... | 0.062474 | 0.08698 |
import csv
import os
import copy
import shutil
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse, FormRequest
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from scrapy.http.cookies import CookieJar
... | portfolio/Python/scrapy/shoemetro/shoebacca.py | import csv
import os
import copy
import shutil
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse, FormRequest
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from scrapy.http.cookies import CookieJar
... | 0.289773 | 0.066146 |
import discord
def getPermissionJson(name, value):
return {
"permissionName": name,
"allow": value
}
def getCategoryJson(category):
return {
"name": category.name,
"type": str(category.type),
"nsfw": category.is_nsfw(),
"permissions": [getChannelPermissionJs... | template_server_serializer.py | import discord
def getPermissionJson(name, value):
return {
"permissionName": name,
"allow": value
}
def getCategoryJson(category):
return {
"name": category.name,
"type": str(category.type),
"nsfw": category.is_nsfw(),
"permissions": [getChannelPermissionJs... | 0.533641 | 0.338651 |
import numpy as np
from mpmath import mp
mp.dps = 500
def construct_s(bh):
s = []
for bhj in bh:
if bhj != 0:
s.append(np.sign(bhj))
s = np.array(s)
s = s.reshape((len(s), 1))
return s
def construct_A_XA_Ac_XAc_bhA(X, bh, n, p):
A = []
Ac = []
bhA = []
for... | util.py | import numpy as np
from mpmath import mp
mp.dps = 500
def construct_s(bh):
s = []
for bhj in bh:
if bhj != 0:
s.append(np.sign(bhj))
s = np.array(s)
s = s.reshape((len(s), 1))
return s
def construct_A_XA_Ac_XAc_bhA(X, bh, n, p):
A = []
Ac = []
bhA = []
for... | 0.434941 | 0.386821 |
import os
import pkg_resources
# Anaconda
import pandas as pd
from argparse import ArgumentParser
# Local
from plot_weightlifting.plotstartingstrength import plot_db
from plot_weightlifting.global_vars import (__name__, __version__,
FIGSIZE_DICT)
def main():
""" Main function """
# Argument Parsing
de... | plot_weightlifting/main.py | import os
import pkg_resources
# Anaconda
import pandas as pd
from argparse import ArgumentParser
# Local
from plot_weightlifting.plotstartingstrength import plot_db
from plot_weightlifting.global_vars import (__name__, __version__,
FIGSIZE_DICT)
def main():
""" Main function """
# Argument Parsing
de... | 0.532911 | 0.116487 |
__all__ = ['RequestData', 'Client']
# Cell
import os
import requests
from ..exceptions import (
UnexpectedInputProvided, ExpectedInputMissing,
DataTypeNotImplemented
)
# Cell
class RequestData:
def __init__(self, spec):
"""Factory base class for request data."""
self.spec = spec
... | mod/serving/client.py |
__all__ = ['RequestData', 'Client']
# Cell
import os
import requests
from ..exceptions import (
UnexpectedInputProvided, ExpectedInputMissing,
DataTypeNotImplemented
)
# Cell
class RequestData:
def __init__(self, spec):
"""Factory base class for request data."""
self.spec = spec
... | 0.478285 | 0.196826 |
import pprint
import re # noqa: F401
import six
from jamf.configuration import Configuration
class NetworkV2(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (di... | jamf/models/network_v2.py | import pprint
import re # noqa: F401
import six
from jamf.configuration import Configuration
class NetworkV2(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (di... | 0.54359 | 0.090977 |
import os
from xml.dom import minidom
import unittest
import mock
from pybrightcove import video, enums, connection
class FTPVideoTest(unittest.TestCase):
@mock.patch('ftplib.FTP')
@mock.patch('hashlib.md5') # md5(), md5.hexdigest
@mock.patch('os.path.getsize')
@mock.patch('__builtin__.file')
@m... | tests/test_ftp_video.py |
import os
from xml.dom import minidom
import unittest
import mock
from pybrightcove import video, enums, connection
class FTPVideoTest(unittest.TestCase):
@mock.patch('ftplib.FTP')
@mock.patch('hashlib.md5') # md5(), md5.hexdigest
@mock.patch('os.path.getsize')
@mock.patch('__builtin__.file')
@m... | 0.472927 | 0.099077 |
from pip_services3_expressions.tokenizers.AbstractTokenizer import AbstractTokenizer
from pip_services3_expressions.tokenizers.TokenType import TokenType
from pip_services3_expressions.tokenizers.generic.GenericCommentState import GenericCommentState
from pip_services3_expressions.tokenizers.generic.GenericNumberState... | pip_services3_expressions-3.3.4/pip_services3_expressions/tokenizers/generic/GenericTokenizer.py |
from pip_services3_expressions.tokenizers.AbstractTokenizer import AbstractTokenizer
from pip_services3_expressions.tokenizers.TokenType import TokenType
from pip_services3_expressions.tokenizers.generic.GenericCommentState import GenericCommentState
from pip_services3_expressions.tokenizers.generic.GenericNumberState... | 0.737631 | 0.175044 |
import hashlib
import json
import logging
import re
from pyhocon import ConfigFactory, HOCONConverter
from .dict_tool import merge_dict
logger = logging.getLogger(__name__)
NEW_LINE = '\n'
RE_HOCON_INCLUDE = [
r'include\s+(?:required|url|file|classpath)\(.*\)',
r'include\s+".*\.(?:conf|hocon)"',
]
RE_HOCON... | caper/hocon_string.py | import hashlib
import json
import logging
import re
from pyhocon import ConfigFactory, HOCONConverter
from .dict_tool import merge_dict
logger = logging.getLogger(__name__)
NEW_LINE = '\n'
RE_HOCON_INCLUDE = [
r'include\s+(?:required|url|file|classpath)\(.*\)',
r'include\s+".*\.(?:conf|hocon)"',
]
RE_HOCON... | 0.678859 | 0.103341 |
import unittest
from sorted_squared_array import sortedSquaredArrayNormal, sortedSquaredArrayBetter
import random
import time
class TestSortedSquaredArray(unittest.TestCase):
# Testing of normal algo code
def test_normal_1(self):
self.assertEqual(sortedSquaredArrayNormal([1, 2, 3, 5, 6, 8, 9]),[1, 4, 9, 25, 36,... | SortedSquaredArray/test_sorted_squared_array.py | import unittest
from sorted_squared_array import sortedSquaredArrayNormal, sortedSquaredArrayBetter
import random
import time
class TestSortedSquaredArray(unittest.TestCase):
# Testing of normal algo code
def test_normal_1(self):
self.assertEqual(sortedSquaredArrayNormal([1, 2, 3, 5, 6, 8, 9]),[1, 4, 9, 25, 36,... | 0.479991 | 0.647687 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
__all__ = ['InstanceVariableArgs', 'InstanceVariable']
@pulumi.input_type
class InstanceVariableArgs:
def __init__(__self__, *,
key: pulumi.Input[str]... | sdk/python/pulumi_gitlab/instance_variable.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
__all__ = ['InstanceVariableArgs', 'InstanceVariable']
@pulumi.input_type
class InstanceVariableArgs:
def __init__(__self__, *,
key: pulumi.Input[str]... | 0.883701 | 0.173884 |
import i_worker
import socket
import struct
# Description of the GeoBrick device. Currently hard-coded.
BRICK_HOSTNAME = 'geobrickanta.solar.pvt'
BRICK_PORT = 1025
BRICK_TIMEOUT = 0.5
# Program spaces that can be used in the GeoBrick.
COMMAND_REGIS = 'P1000='
ARG1_REGIS = ' P1001='
ARG2_REGIS = ' P1002='
# Brick com... | core/brick_worker.py | import i_worker
import socket
import struct
# Description of the GeoBrick device. Currently hard-coded.
BRICK_HOSTNAME = 'geobrickanta.solar.pvt'
BRICK_PORT = 1025
BRICK_TIMEOUT = 0.5
# Program spaces that can be used in the GeoBrick.
COMMAND_REGIS = 'P1000='
ARG1_REGIS = ' P1001='
ARG2_REGIS = ' P1002='
# Brick com... | 0.546012 | 0.16238 |
from math import log10, log
def fsPathLoss(dist,freq):
"""
dist : Kilometros
freq : Megahertz
"""
return 32.44 + 20*log10(dist) + 20*log10(freq)
def okumuraHataPL(dist, freq, cityKind, areaKind, hb, hm):
"""OKUMURA-HATA URBAN model
freq: signal frequency(500Mhz e 1500Mhz);
... | Projeto/freeSpace.py | from math import log10, log
def fsPathLoss(dist,freq):
"""
dist : Kilometros
freq : Megahertz
"""
return 32.44 + 20*log10(dist) + 20*log10(freq)
def okumuraHataPL(dist, freq, cityKind, areaKind, hb, hm):
"""OKUMURA-HATA URBAN model
freq: signal frequency(500Mhz e 1500Mhz);
... | 0.357119 | 0.364269 |
from __future__ import annotations
from dnnv.properties.expressions.base import Expression
from ...expressions import BinaryExpression, Call
from ..base import GenericExpressionTransformer
from ._calls import FunctionSubstitutor
from ...visitors import DetailsInference
class SubstituteCalls(GenericExpressionTransfo... | dnnv/properties/transformers/substitute_calls/base.py | from __future__ import annotations
from dnnv.properties.expressions.base import Expression
from ...expressions import BinaryExpression, Call
from ..base import GenericExpressionTransformer
from ._calls import FunctionSubstitutor
from ...visitors import DetailsInference
class SubstituteCalls(GenericExpressionTransfo... | 0.810366 | 0.361249 |
import os
import numpy as np
import onnxruntime as onnxrt
import threading
import sys
from onnxruntime.capi.onnxruntime_pybind11_state import Fail
def RegisterCustomOpsLibrary():
if sys.platform.startswith("win"):
shared_library = 'custom_op_library.dll'
if not os.path.exists(shared_library):
... | ONNX_runtime_hacks/Custom_op_loader.py | import os
import numpy as np
import onnxruntime as onnxrt
import threading
import sys
from onnxruntime.capi.onnxruntime_pybind11_state import Fail
def RegisterCustomOpsLibrary():
if sys.platform.startswith("win"):
shared_library = 'custom_op_library.dll'
if not os.path.exists(shared_library):
... | 0.212722 | 0.129954 |
import re
import csv
import imp
import sys
import yaml
import argparse
import sys
import types
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
# Add !regexp as a known Yaml dialect.
yaml.add_constructor('!regexp', lambda l, n: l.construct_scalar(n))
if PY3: # pragma: no cover
text_type = s... | logsanitizer/__init__.py |
import re
import csv
import imp
import sys
import yaml
import argparse
import sys
import types
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
# Add !regexp as a known Yaml dialect.
yaml.add_constructor('!regexp', lambda l, n: l.construct_scalar(n))
if PY3: # pragma: no cover
text_type = s... | 0.393618 | 0.153232 |
import numpy as np
def str_extended(value):
"""
A small helper function to convert a python object into executable code reproducing that object.
Supported types
---------------
None, bool, int, float, complex, str, list, dict, tuple, numpy.ndarray
"""
np.set_printoptions(threshold=np.inf)
... | polychromosims/save_module_to_script.py | import numpy as np
def str_extended(value):
"""
A small helper function to convert a python object into executable code reproducing that object.
Supported types
---------------
None, bool, int, float, complex, str, list, dict, tuple, numpy.ndarray
"""
np.set_printoptions(threshold=np.inf)
... | 0.409693 | 0.403097 |
import os
BASE_FOLDER = os.path.expanduser('~/rbkcli')
TARGETS_FOLDER = BASE_FOLDER + '/targets'
CONF_FOLDER = BASE_FOLDER + '/conf'
LOGS_FOLDER = BASE_FOLDER + '/logs'
SCRIPTS_FOLDER = BASE_FOLDER + '/scripts'
CMDLETS_FOLDER = CONF_FOLDER + '/cmdlets'
SUPPORTED_API_VERSIONS = ['v1',
... | rbkcli/base/essentials.py |
import os
BASE_FOLDER = os.path.expanduser('~/rbkcli')
TARGETS_FOLDER = BASE_FOLDER + '/targets'
CONF_FOLDER = BASE_FOLDER + '/conf'
LOGS_FOLDER = BASE_FOLDER + '/logs'
SCRIPTS_FOLDER = BASE_FOLDER + '/scripts'
CMDLETS_FOLDER = CONF_FOLDER + '/cmdlets'
SUPPORTED_API_VERSIONS = ['v1',
... | 0.218836 | 0.033495 |
import asyncio
import socket
from pymysql import connections
from greenio import socket as greensocket
class GreenConnection(connections.Connection):
def _connect(self):
try:
if self.unix_socket:
raise NotImplementedError()
else:
sock = greensocket.... | examples/mysql.py | import asyncio
import socket
from pymysql import connections
from greenio import socket as greensocket
class GreenConnection(connections.Connection):
def _connect(self):
try:
if self.unix_socket:
raise NotImplementedError()
else:
sock = greensocket.... | 0.24608 | 0.080792 |
from trees import christmasTrees
from cafe import coolCafe
from ships import coolShips
from lists_dictionaries import InfoDb, for_loop, while_loop, recursive_loop, fibonacci
from cool_classes import dispfac, dispSeries, superfac, printpal
from goodbye import goodbye
from return_to_market import market
def buildMenu(m... | tech_talks/menu.py | from trees import christmasTrees
from cafe import coolCafe
from ships import coolShips
from lists_dictionaries import InfoDb, for_loop, while_loop, recursive_loop, fibonacci
from cool_classes import dispfac, dispSeries, superfac, printpal
from goodbye import goodbye
from return_to_market import market
def buildMenu(m... | 0.302185 | 0.253894 |
from models.minkloc import MinkLoc
from models.minkloc_multimodal import MinkLocMultimodal, ResnetFPN
from misc.utils import MinkLocParams
def model_factory(params: MinkLocParams):
in_channels = 1
# MinkLocMultimodal is our baseline MinkLoc++ model producing 256 dimensional descriptor where
# each modal... | models/model_factory.py |
from models.minkloc import MinkLoc
from models.minkloc_multimodal import MinkLocMultimodal, ResnetFPN
from misc.utils import MinkLocParams
def model_factory(params: MinkLocParams):
in_channels = 1
# MinkLocMultimodal is our baseline MinkLoc++ model producing 256 dimensional descriptor where
# each modal... | 0.73678 | 0.290477 |
from django.conf import settings
from django.contrib.auth.decorators import login_required, permission_required
from django.core.exceptions import ImproperlyConfigured
from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf... | localshop/views.py | from django.conf import settings
from django.contrib.auth.decorators import login_required, permission_required
from django.core.exceptions import ImproperlyConfigured
from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf... | 0.590661 | 0.068475 |
from __future__ import annotations
import os
import io
import click
import json
import difflib
import datacompy
import subprocess
import pandas as pd
import bson
import decimal
from .config import get_sql_for_database, get_config_for_database
from pathlib import Path
from collections import OrderedDict
from typing im... | fabrica/verify.py | from __future__ import annotations
import os
import io
import click
import json
import difflib
import datacompy
import subprocess
import pandas as pd
import bson
import decimal
from .config import get_sql_for_database, get_config_for_database
from pathlib import Path
from collections import OrderedDict
from typing im... | 0.742422 | 0.157428 |
from unittest.mock import ANY
import pytest
from django.core.exceptions import ObjectDoesNotExist
from django.core.validators import URLValidator
from django.test import override_settings
from aca.client import ACAClient
from oidc.endpoints.authorize import authorization
from oidc.models import AuthSession
@pytest.... | oidc/tests/test_endpoints.py | from unittest.mock import ANY
import pytest
from django.core.exceptions import ObjectDoesNotExist
from django.core.validators import URLValidator
from django.test import override_settings
from aca.client import ACAClient
from oidc.endpoints.authorize import authorization
from oidc.models import AuthSession
@pytest.... | 0.475118 | 0.425486 |
import copy
import os
import numpy as np
from .conservative import ListDependenceResult
from .utils import get_pair_id, get_pairs_by_levels, get_possible_structures
GRIDS = ['lhs', 'rand', 'vertices']
LIB_PARAMS = ['iterative_save', 'iterative_load', 'input_names',
'output_names', 'keep_input_samples... | depimpact/iterative_vines.py | import copy
import os
import numpy as np
from .conservative import ListDependenceResult
from .utils import get_pair_id, get_pairs_by_levels, get_possible_structures
GRIDS = ['lhs', 'rand', 'vertices']
LIB_PARAMS = ['iterative_save', 'iterative_load', 'input_names',
'output_names', 'keep_input_samples... | 0.465387 | 0.40116 |
from retirable_resources.resource_manager import DeleteValue
import unittest
from retirable_resources import (
RetirableResourceManager,
SetValue,
AddToList,
ResourceDoesNotExist,
OwnerDoesNotExist,
ResourceOwnerView,
ResourceWatcher,
)
from .fixtures import RetirableResourceManagerTest
... | tests/test.py | from retirable_resources.resource_manager import DeleteValue
import unittest
from retirable_resources import (
RetirableResourceManager,
SetValue,
AddToList,
ResourceDoesNotExist,
OwnerDoesNotExist,
ResourceOwnerView,
ResourceWatcher,
)
from .fixtures import RetirableResourceManagerTest
... | 0.608129 | 0.348728 |
import ctypes
# Grab a handle to kernel32.dll & USer32.dll
k_handle = ctypes.WinDLL("Kernel32.dll")
u_handle = ctypes.WinDLL("User32.dll")
# Access Rights
PROCESS_ALL_ACCESS = (0x000F0000 | 0x00100000 | 0xFFF)
# Token Access Rights
STANDARD_RIGHTS_REQUIRED = 0x000F0000
STANDARD_RIGHTS_READ = 0x00020000
TOKEN_ASSIGN... | opentoken.py | import ctypes
# Grab a handle to kernel32.dll & USer32.dll
k_handle = ctypes.WinDLL("Kernel32.dll")
u_handle = ctypes.WinDLL("User32.dll")
# Access Rights
PROCESS_ALL_ACCESS = (0x000F0000 | 0x00100000 | 0xFFF)
# Token Access Rights
STANDARD_RIGHTS_REQUIRED = 0x000F0000
STANDARD_RIGHTS_READ = 0x00020000
TOKEN_ASSIGN... | 0.189184 | 0.193547 |
from collections import OrderedDict
import copy
import os
from xrsdkit.tools import ymltools as xrsdyml
import fabio
import yaml
import numpy as np
from ..Workflow import Workflow
# NOTE: this workflow is for reading samples
# that were saved with YAML headers
inputs = OrderedDict(
header_file = None,
imag... | paws/workflows/SSRL_BEAMLINE_1_5/Read.py | from collections import OrderedDict
import copy
import os
from xrsdkit.tools import ymltools as xrsdyml
import fabio
import yaml
import numpy as np
from ..Workflow import Workflow
# NOTE: this workflow is for reading samples
# that were saved with YAML headers
inputs = OrderedDict(
header_file = None,
imag... | 0.404507 | 0.106598 |
import unittest
from typing import Any, Dict, List
from unittest.mock import Mock, call, patch
from nuplan.common.utils.helpers import keep_trying, try_n_times
class HelperTestingSetup:
"""Helper configuration class for testing"""
def __init__(self) -> None:
"""Initializes with mock values"""
... | nuplan/common/utils/test/test_helpers.py | import unittest
from typing import Any, Dict, List
from unittest.mock import Mock, call, patch
from nuplan.common.utils.helpers import keep_trying, try_n_times
class HelperTestingSetup:
"""Helper configuration class for testing"""
def __init__(self) -> None:
"""Initializes with mock values"""
... | 0.866895 | 0.587411 |
from tensorflow.keras import Sequential # keras model
from tensorflow.keras.layers import Conv2D, MaxPool2D # Convolution layer
from tensorflow.keras.layers import Dense, Flatten # Affine layer
from tensorflow.keras.layers import Dropout
import os
# dir setting
base_dir = "C:\\Users\\user\\Desktop\\dataset\\... | Classifier_step01.py | from tensorflow.keras import Sequential # keras model
from tensorflow.keras.layers import Conv2D, MaxPool2D # Convolution layer
from tensorflow.keras.layers import Dense, Flatten # Affine layer
from tensorflow.keras.layers import Dropout
import os
# dir setting
base_dir = "C:\\Users\\user\\Desktop\\dataset\\... | 0.823151 | 0.521715 |
emailSender = 'xxx@xxx' # 发件人邮箱账号
emailSenderPassword = '<PASSWORD>' # 发件人邮箱密码
emailSenderName = "昵称" # 发件人昵称
emailSMTPAddress = "xxxx" # 发件人邮箱SMTP地址(一般为smtp.邮箱后缀,如smtp.126.com)
email... | SendEmails.py | emailSender = 'xxx@xxx' # 发件人邮箱账号
emailSenderPassword = '<PASSWORD>' # 发件人邮箱密码
emailSenderName = "昵称" # 发件人昵称
emailSMTPAddress = "xxxx" # 发件人邮箱SMTP地址(一般为smtp.邮箱后缀,如smtp.126.com)
email... | 0.036511 | 0.053502 |
import numpy as np
import pandas as pd
from .association_index import association_index
from .index_terms2counters import index_terms2counters
from .tf_matrix import tf_matrix
# pyltin: disable=c0103
# pylint: disable=too-many-arguments
# pylint: disable=invalid-name
def occurrence_matrix(
column,
by=None,
... | techminer2/occurrence_matrix.py | import numpy as np
import pandas as pd
from .association_index import association_index
from .index_terms2counters import index_terms2counters
from .tf_matrix import tf_matrix
# pyltin: disable=c0103
# pylint: disable=too-many-arguments
# pylint: disable=invalid-name
def occurrence_matrix(
column,
by=None,
... | 0.401688 | 0.21963 |
import numpy as np
import scipy
import scipy.stats
from scipy.interpolate import interp1d, UnivariateSpline
# functions more or less directly from scipy or numpy
def linregress(x, y, _larch=None):
return scipy.stats.linregress(x, y)
linregress.__doc__ = scipy.stats.linregress.__doc__
def polyfit(x, y, deg, rcond=... | plugins/math/mathutils.py | import numpy as np
import scipy
import scipy.stats
from scipy.interpolate import interp1d, UnivariateSpline
# functions more or less directly from scipy or numpy
def linregress(x, y, _larch=None):
return scipy.stats.linregress(x, y)
linregress.__doc__ = scipy.stats.linregress.__doc__
def polyfit(x, y, deg, rcond=... | 0.78233 | 0.601301 |
import haiku as hk
import jax
import jax.numpy as jnp
from jdetr._typing import JaxArray
from jdetr.utils import maybe
__all__ = ["Transformer"]
class MultiHeadAttentionLayer(hk.Module):
def __init__(
self,
feature_dim: int,
value_dim: int,
num_heads: int,
key_query_dim: ... | jdetr/models/transformer.py | import haiku as hk
import jax
import jax.numpy as jnp
from jdetr._typing import JaxArray
from jdetr.utils import maybe
__all__ = ["Transformer"]
class MultiHeadAttentionLayer(hk.Module):
def __init__(
self,
feature_dim: int,
value_dim: int,
num_heads: int,
key_query_dim: ... | 0.731442 | 0.373533 |
# Copyright (c) Latona. All rights reserved.
from StatusJsonPythonModule import StatusJsonRest
from datetime import datetime
import pyaudio
import os
import sys
import wave
from datetime import datetime as dt
from aion.logger_library.LoggerClient import LoggerClient
from six.moves import queue
log = LoggerClient("Ca... | main.py |
# Copyright (c) Latona. All rights reserved.
from StatusJsonPythonModule import StatusJsonRest
from datetime import datetime
import pyaudio
import os
import sys
import wave
from datetime import datetime as dt
from aion.logger_library.LoggerClient import LoggerClient
from six.moves import queue
log = LoggerClient("Ca... | 0.542379 | 0.079603 |
import numpy as np
import pandas as pd
import pytest
from asdf import ValidationError
from weldx import Q_, TimeSeries
from weldx.asdf.types import WxSyntaxError
from weldx.asdf.util import write_buffer, write_read_buffer
from weldx.asdf.validators import _custom_shape_validator
from weldx.tags.debug.test_property_tag... | weldx/tests/asdf_tests/test_asdf_validators.py | import numpy as np
import pandas as pd
import pytest
from asdf import ValidationError
from weldx import Q_, TimeSeries
from weldx.asdf.types import WxSyntaxError
from weldx.asdf.util import write_buffer, write_read_buffer
from weldx.asdf.validators import _custom_shape_validator
from weldx.tags.debug.test_property_tag... | 0.558568 | 0.640945 |
import datetime as dt
import json
from typing import Dict, List, Optional
from _autoclimate.state import State
from _autoclimate.utils import climate_name
from adplus import Hass
"""
Laston - create new sensors that track the last time the climate
was "on" as defined by autoclimate entity_rules.
sensor.autoclimate_... | _autoclimate/laston.py | import datetime as dt
import json
from typing import Dict, List, Optional
from _autoclimate.state import State
from _autoclimate.utils import climate_name
from adplus import Hass
"""
Laston - create new sensors that track the last time the climate
was "on" as defined by autoclimate entity_rules.
sensor.autoclimate_... | 0.8308 | 0.26594 |
# In[1]:
import pandas as pd
# In[2]:
data=pd.read_csv('analysis.mf_acc_xns.txt',sep="\t")
# In[3]:
data.info()
# In[4]:
data.head()
# In[43]:
year=[[0 for i in range(12)]for _ in range(3)]
for i, row in enumerate(data.groupby(['acc_id'])['xn_date'].first()):
temp=row.split('-')
if(temp[0]=='... | DataAnalysis/sliding window graph.py |
# In[1]:
import pandas as pd
# In[2]:
data=pd.read_csv('analysis.mf_acc_xns.txt',sep="\t")
# In[3]:
data.info()
# In[4]:
data.head()
# In[43]:
year=[[0 for i in range(12)]for _ in range(3)]
for i, row in enumerate(data.groupby(['acc_id'])['xn_date'].first()):
temp=row.split('-')
if(temp[0]=='... | 0.19544 | 0.302359 |
import argparse
import base64
import traceback
import zlib
import flask
from flask import request, jsonify
from mailer import Mailer, Message
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("--port", default=5000, type=int, help="Port to bind the http api to")
parser.add_arg... | main.py | import argparse
import base64
import traceback
import zlib
import flask
from flask import request, jsonify
from mailer import Mailer, Message
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("--port", default=5000, type=int, help="Port to bind the http api to")
parser.add_arg... | 0.367951 | 0.057998 |
import pprint
import re # noqa: F401
import six
class DomainListingsServiceV1ModelDomainListingsApiModelQueryResultsListingTenantDetails(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types... | src/domainClient/models/domain_listings_service_v1_model_domain_listings_api_model_query_results_listing_tenant_details.py | import pprint
import re # noqa: F401
import six
class DomainListingsServiceV1ModelDomainListingsApiModelQueryResultsListingTenantDetails(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types... | 0.531696 | 0.05875 |
import json
import os
from os.path import join, isdir
from os import mkdir, makedirs
import cv2
import numpy as np
import re
def tryint(s):
try:
return int(s)
except:
return s
def alphanum_key(s):
""" Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"] ... | data/PoseTrack/gen_json.py | import json
import os
from os.path import join, isdir
from os import mkdir, makedirs
import cv2
import numpy as np
import re
def tryint(s):
try:
return int(s)
except:
return s
def alphanum_key(s):
""" Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"] ... | 0.226698 | 0.225353 |
from absl import logging
import gin
from multi_representation_adversary import data
from multi_representation_adversary import helper
from multi_representation_adversary import resnet
from multi_representation_adversary import selectors
import tensorflow.compat.v2 as tf
@gin.configurable
def learning_rate_scheduler(e... | research/multi_representation_adversary/multi_representation_adversary/trainer.py | from absl import logging
import gin
from multi_representation_adversary import data
from multi_representation_adversary import helper
from multi_representation_adversary import resnet
from multi_representation_adversary import selectors
import tensorflow.compat.v2 as tf
@gin.configurable
def learning_rate_scheduler(e... | 0.896416 | 0.366731 |
from functools import wraps
from django.http import HttpResponse, JsonResponse, FileResponse, Http404
from django.shortcuts import get_object_or_404
from django.conf import settings
from rest_framework import viewsets
from . import models
from . import digests
from . import ocr
from . import collections
from . import s... | snoop/data/views.py | from functools import wraps
from django.http import HttpResponse, JsonResponse, FileResponse, Http404
from django.shortcuts import get_object_or_404
from django.conf import settings
from rest_framework import viewsets
from . import models
from . import digests
from . import ocr
from . import collections
from . import s... | 0.726717 | 0.20458 |
import sqlite3
import re
from urllib import parse
import hashlib
def url_pas(data):
return(parse.quote(data).replace('/','%2F'))
def sha224(data):
return(hashlib.sha224(bytes(data, 'utf-8')).hexdigest())
def link(conn, title, data, num, category, backlink):
curs = conn.cursor()
data = data.replace('... | set_mark/link.py | import sqlite3
import re
from urllib import parse
import hashlib
def url_pas(data):
return(parse.quote(data).replace('/','%2F'))
def sha224(data):
return(hashlib.sha224(bytes(data, 'utf-8')).hexdigest())
def link(conn, title, data, num, category, backlink):
curs = conn.cursor()
data = data.replace('... | 0.056894 | 0.193262 |
from typing import Optional, Tuple
import numpy as np
import scipy.stats
def random_spd_eigendecomposition(
N: int,
dtype: Optional[np.dtype] = np.double,
rng: Optional[np.random.Generator] = None,
) -> Tuple[np.ndarray, np.ndarray]:
"""Generates a random eigendecomposition of a symmetric positive d... | src/cholupdates/utils.py |
from typing import Optional, Tuple
import numpy as np
import scipy.stats
def random_spd_eigendecomposition(
N: int,
dtype: Optional[np.dtype] = np.double,
rng: Optional[np.random.Generator] = None,
) -> Tuple[np.ndarray, np.ndarray]:
"""Generates a random eigendecomposition of a symmetric positive d... | 0.967747 | 0.786705 |
import logging
import os
import sys
import time
import unittest
sys.path.insert(0, os.path.abspath('..'))
from osdp import *
log = logging.getLogger('osdp')
class ControlPanelTestCase(unittest.TestCase):
"""Test Bus for OSDP Python Module."""
def setUp(self):
"""Setup."""
self.last_reply = None
def tearDow... | tests/test_control_panel.py | import logging
import os
import sys
import time
import unittest
sys.path.insert(0, os.path.abspath('..'))
from osdp import *
log = logging.getLogger('osdp')
class ControlPanelTestCase(unittest.TestCase):
"""Test Bus for OSDP Python Module."""
def setUp(self):
"""Setup."""
self.last_reply = None
def tearDow... | 0.224735 | 0.122786 |
import logging
from metadatadb_driver_interface.plugin import AbstractPlugin
from metadatadb_driver_interface.search_model import FullTextModel, QueryModel
from metadata_driver_elasticsearch.instance import get_database_instance
class Plugin(AbstractPlugin):
"""Elasticsearch ledger plugin for `Metadata DB's Pyth... | metadata_driver_elasticsearch/plugin.py | import logging
from metadatadb_driver_interface.plugin import AbstractPlugin
from metadatadb_driver_interface.search_model import FullTextModel, QueryModel
from metadata_driver_elasticsearch.instance import get_database_instance
class Plugin(AbstractPlugin):
"""Elasticsearch ledger plugin for `Metadata DB's Pyth... | 0.752922 | 0.146392 |
import click
import yaml
import json
import re
proxies = []
proxy_count = 1
def flatten_dict(dd, separator=".", prefix=""):
return (
{
prefix + separator + k if prefix else k: v
for kk, vv in dd.items()
for k, v in flatten_dict(vv, separator, kk).items()
}
... | scripts/parflow/read_run.py | import click
import yaml
import json
import re
proxies = []
proxy_count = 1
def flatten_dict(dd, separator=".", prefix=""):
return (
{
prefix + separator + k if prefix else k: v
for kk, vv in dd.items()
for k, v in flatten_dict(vv, separator, kk).items()
}
... | 0.448909 | 0.214147 |
import logging
from cohesity_management_sdk.api_helper import APIHelper
from cohesity_management_sdk.configuration import Configuration
from cohesity_management_sdk.controllers.base_controller import BaseController
from cohesity_management_sdk.http.auth.auth_manager import AuthManager
from cohesity_management_sdk.mode... | cohesity_management_sdk/controllers/certificates_controller.py |
import logging
from cohesity_management_sdk.api_helper import APIHelper
from cohesity_management_sdk.configuration import Configuration
from cohesity_management_sdk.controllers.base_controller import BaseController
from cohesity_management_sdk.http.auth.auth_manager import AuthManager
from cohesity_management_sdk.mode... | 0.826607 | 0.089733 |
from mimetypes import MimeTypes
from pathlib import Path
from typing import Iterator, Optional
from flask import Response, send_from_directory, stream_with_context
from werkzeug.utils import secure_filename
from restapi.config import DATA_PATH
from restapi.exceptions import NotFound
from restapi.services.uploader imp... | restapi/services/download.py | from mimetypes import MimeTypes
from pathlib import Path
from typing import Iterator, Optional
from flask import Response, send_from_directory, stream_with_context
from werkzeug.utils import secure_filename
from restapi.config import DATA_PATH
from restapi.exceptions import NotFound
from restapi.services.uploader imp... | 0.768038 | 0.137359 |
import copy
import pickle
import pandas as pd
import numpy as np
import os, sys
from ..Model import models
from ..Input import readInput as readIn
from ..Data import curate as curate
from ..Data import descriptors as descr
from ..Data import postprocess as pproc
from ..Validation import modelability as modi
from ..Vali... | models/classes/pyQSAR/Src/Model/c_model.py | import copy
import pickle
import pandas as pd
import numpy as np
import os, sys
from ..Model import models
from ..Input import readInput as readIn
from ..Data import curate as curate
from ..Data import descriptors as descr
from ..Data import postprocess as pproc
from ..Validation import modelability as modi
from ..Vali... | 0.383641 | 0.261405 |
"""Setup module."""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_requires():
"""Read requirements.txt."""
requirements = open("requirements.txt", "r").read()
return list(filter(lambda x: x != "", requirements.split()))
def read_description():
... | setup.py | """Setup module."""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_requires():
"""Read requirements.txt."""
requirements = open("requirements.txt", "r").read()
return list(filter(lambda x: x != "", requirements.split()))
def read_description():
... | 0.686055 | 0.307306 |
import numpy as np
import pytest
import mindspore.nn as nn
import mindspore.nn.probability.distribution as msd
from mindspore import dtype
from mindspore import Tensor
def test_gumbel_shape_errpr():
"""
Invalid shapes.
"""
with pytest.raises(ValueError):
msd.Gumbel([[2.], [1.]], [[2.], [3.], [4... | tests/ut/python/nn/probability/distribution/test_gumbel.py | import numpy as np
import pytest
import mindspore.nn as nn
import mindspore.nn.probability.distribution as msd
from mindspore import dtype
from mindspore import Tensor
def test_gumbel_shape_errpr():
"""
Invalid shapes.
"""
with pytest.raises(ValueError):
msd.Gumbel([[2.], [1.]], [[2.], [3.], [4... | 0.733833 | 0.667703 |
import os
import platform
import tempfile
import time
from pathlib import Path
from test.conftest import TEST_REF, conan_create_and_upload
from typing import List
from conan_app_launcher.core.conan import (ConanApi, ConanCleanup,
_create_key_value_pair_list)
from co... | test/01_unit/test_conan.py | import os
import platform
import tempfile
import time
from pathlib import Path
from test.conftest import TEST_REF, conan_create_and_upload
from typing import List
from conan_app_launcher.core.conan import (ConanApi, ConanCleanup,
_create_key_value_pair_list)
from co... | 0.510496 | 0.194483 |
import komand
import json
from .schema import SendInput, SendOutput
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
class Send(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name='send',
... | smtp/komand_smtp/actions/send/action.py | import komand
import json
from .schema import SendInput, SendOutput
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
class Send(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name='send',
... | 0.340814 | 0.070784 |
from webob import exc
from oslo_log import log as logging
from senlin.api.openstack.v1 import util
from senlin.common import consts
from senlin.common.i18n import _
from senlin.common import serializers
from senlin.common import utils
from senlin.common import wsgi
from senlin.rpc import client as rpc_client
LOG = ... | senlin/api/openstack/v1/actions.py |
from webob import exc
from oslo_log import log as logging
from senlin.api.openstack.v1 import util
from senlin.common import consts
from senlin.common.i18n import _
from senlin.common import serializers
from senlin.common import utils
from senlin.common import wsgi
from senlin.rpc import client as rpc_client
LOG = ... | 0.595257 | 0.110567 |
import atexit
import os
import signal
import sys
class Daemon(object):
"""A basic daemon class. Credits to <NAME>, the developers of daemonize and
python-daemon, Python Cookbook 3rd Ed. by <NAME> and <NAME>, and more.
"""
def __init__(self, pidfile, stdin=os.devnull, stdout=os.devnull, stderr=os.devnu... | daemon.py | import atexit
import os
import signal
import sys
class Daemon(object):
"""A basic daemon class. Credits to <NAME>, the developers of daemonize and
python-daemon, Python Cookbook 3rd Ed. by <NAME> and <NAME>, and more.
"""
def __init__(self, pidfile, stdin=os.devnull, stdout=os.devnull, stderr=os.devnu... | 0.223631 | 0.172555 |
from pyriemann.utils.distance import distance
from similarity import similarity_matrix
import sys
sys.path.append('/home/tevo/Documents/UFABC/Spikes')
sys.path.append('/home/tevo/Documents/UFABC/SingleUnit Spike Learning/src/models/')
import os
os.chdir('/home/tevo/Documents/UFABC/Spikes')
from spikeHelper.loadSpike im... | src/analysis/hypothesis_testing/similarity_evolution.py | from pyriemann.utils.distance import distance
from similarity import similarity_matrix
import sys
sys.path.append('/home/tevo/Documents/UFABC/Spikes')
sys.path.append('/home/tevo/Documents/UFABC/SingleUnit Spike Learning/src/models/')
import os
os.chdir('/home/tevo/Documents/UFABC/Spikes')
from spikeHelper.loadSpike im... | 0.333612 | 0.274315 |
from gym_minigrid.minigrid import *
from gym_minigrid.register import register
from operator import add
class DoorKeyObstEnv(MiniGridEnv):
"""
Environment with a door and key, sparse reward, with 0 or n obstacles
"""
def __init__(self, size=7, n_obstacles=1, key_pos=(1, 1)):
# Reduce obstacl... | gym_minigrid/envs/doorkeywithobstacles.py | from gym_minigrid.minigrid import *
from gym_minigrid.register import register
from operator import add
class DoorKeyObstEnv(MiniGridEnv):
"""
Environment with a door and key, sparse reward, with 0 or n obstacles
"""
def __init__(self, size=7, n_obstacles=1, key_pos=(1, 1)):
# Reduce obstacl... | 0.81928 | 0.387343 |
from os import close
import pygame
import time
import random
pygame.init()
width,height=800,600#screen
disp=pygame.display.set_mode((width,height))
pygame.display.set_caption("SNEK")
green,red,black,white,grey=(0,204,153),(255,8,0),(0,0,0),(255,255,255),(128,128,128)
font_style=pygame.font.SysFont(None,30)
cell=20
le... | main.py | from os import close
import pygame
import time
import random
pygame.init()
width,height=800,600#screen
disp=pygame.display.set_mode((width,height))
pygame.display.set_caption("SNEK")
green,red,black,white,grey=(0,204,153),(255,8,0),(0,0,0),(255,255,255),(128,128,128)
font_style=pygame.font.SysFont(None,30)
cell=20
le... | 0.099105 | 0.104112 |
import config
class Attacker():
def __init__(self, name, expertise, softwares, probability):
self.name = name
self.expertise = expertise
self.softwares = softwares
self.attacks = []
self.cve_list = []
self.prob = probability
def getAttackers():
attackers = []
f = open('{0}/attackers.cfg'... | src/attacker.py | import config
class Attacker():
def __init__(self, name, expertise, softwares, probability):
self.name = name
self.expertise = expertise
self.softwares = softwares
self.attacks = []
self.cve_list = []
self.prob = probability
def getAttackers():
attackers = []
f = open('{0}/attackers.cfg'... | 0.131996 | 0.124585 |
import numpy as np
try:
from sklearn.base import BaseEstimator, RegressorMixin, MultiOutputMixin
from sklearn.utils import check_X_y
from sklearn.utils.validation import (check_is_fitted, check_array,
FLOAT_DTYPES)
except ImportError:
raise ImportError(
... | gmr/sklearn.py | import numpy as np
try:
from sklearn.base import BaseEstimator, RegressorMixin, MultiOutputMixin
from sklearn.utils import check_X_y
from sklearn.utils.validation import (check_is_fitted, check_array,
FLOAT_DTYPES)
except ImportError:
raise ImportError(
... | 0.916643 | 0.62134 |
import os
import subprocess
from subprocess import STDOUT
from sys import platform
def setupLilypondClean(path_to_lily):
path = os.environ['PATH']
new_path = path_to_lily + os.path.pathsep + path
os.environ['PATH'] = new_path
def setup_lilypond(path_to_lilypond_folder="default"):
'''
Optional he... | MuseParse/classes/Output/helpers.py | import os
import subprocess
from subprocess import STDOUT
from sys import platform
def setupLilypondClean(path_to_lily):
path = os.environ['PATH']
new_path = path_to_lily + os.path.pathsep + path
os.environ['PATH'] = new_path
def setup_lilypond(path_to_lilypond_folder="default"):
'''
Optional he... | 0.227469 | 0.242015 |
from argparse import ArgumentParser
import os
import numpy as np
from scipy.optimize import brentq
from scipy.interpolate import interp1d
from sklearn.metrics import roc_curve
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm
from PIL import Image
def load_image(filename):
try:
wit... | evaluate.py | from argparse import ArgumentParser
import os
import numpy as np
from scipy.optimize import brentq
from scipy.interpolate import interp1d
from sklearn.metrics import roc_curve
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm
from PIL import Image
def load_image(filename):
try:
wit... | 0.609873 | 0.217358 |
from maya import cmds
from maya import mel
import re
window = 'cube_unwrap_window'
def select_by_normal(object, vector):
normals = cmds.polyInfo(object, faceNormals=True)
faces = []
for i in range(cmds.polyEvaluate(object, f=True)):
normal = [float(normals[i].rsplit(' ', 3)[j]) for j in range(-3... | maya/scripts/py/cube_unwrap.py |
from maya import cmds
from maya import mel
import re
window = 'cube_unwrap_window'
def select_by_normal(object, vector):
normals = cmds.polyInfo(object, faceNormals=True)
faces = []
for i in range(cmds.polyEvaluate(object, f=True)):
normal = [float(normals[i].rsplit(' ', 3)[j]) for j in range(-3... | 0.300335 | 0.227041 |
from itertools import product
from math import log
from typing import List, Tuple
import numpy as np
from scipy.special import logsumexp
from data import FeatVec
from hmm.state import State, NULL_OBSERVATION
TP_EPS = 1e-15
def _compute_adjacency(states: List[State]) -> Tuple[dict, dict]:
e_in, e_out = {s: [] f... | hmm/baum_welch.py | from itertools import product
from math import log
from typing import List, Tuple
import numpy as np
from scipy.special import logsumexp
from data import FeatVec
from hmm.state import State, NULL_OBSERVATION
TP_EPS = 1e-15
def _compute_adjacency(states: List[State]) -> Tuple[dict, dict]:
e_in, e_out = {s: [] f... | 0.597373 | 0.561996 |
import speech_recognition as sr
import os
from pocketsphinx import LiveSpeech, get_model_path
import socket
print("###welcome to the 🗣️ speech-recognition-command-line-utility🗣️ ###")
print("#Initiating speech recognition ...")
print("\nNow checking the internet connectivity of your device ...🤖️🤖️")
REMOTE_SERVE... | script.py |
import speech_recognition as sr
import os
from pocketsphinx import LiveSpeech, get_model_path
import socket
print("###welcome to the 🗣️ speech-recognition-command-line-utility🗣️ ###")
print("#Initiating speech recognition ...")
print("\nNow checking the internet connectivity of your device ...🤖️🤖️")
REMOTE_SERVE... | 0.136551 | 0.125762 |
from __future__ import print_function
import numpy as np
from openmdao.api import IndepVarComp, Component, Group, Problem
class AngularVelocity321(Component):
"""
Notes
------
Evaluates the body frame angular velocity from 321 Euler angles and their derivatives
Units are in radians and radians/s
Params
... | src/hyperloop/Python/angular_velocity321.py | from __future__ import print_function
import numpy as np
from openmdao.api import IndepVarComp, Component, Group, Problem
class AngularVelocity321(Component):
"""
Notes
------
Evaluates the body frame angular velocity from 321 Euler angles and their derivatives
Units are in radians and radians/s
Params
... | 0.881085 | 0.785638 |
from typing import Dict
from apysc._animation.animation_skew_y_interface import AnimationSkewYInterface
from apysc._type.attr_linking_interface import AttrLinkingInterface
from apysc._type.int import Int
from apysc._type.revert_interface import RevertInterface
class SkewYInterface(
AnimationSkewYInt... | apysc/_display/skew_y_interface.py | from typing import Dict
from apysc._animation.animation_skew_y_interface import AnimationSkewYInterface
from apysc._type.attr_linking_interface import AttrLinkingInterface
from apysc._type.int import Int
from apysc._type.revert_interface import RevertInterface
class SkewYInterface(
AnimationSkewYInt... | 0.872293 | 0.115811 |
from django.db import models
from accounts.models import User
# Create your models here.
#
class parts(models.Model):
part_id = models.IntegerField(primary_key=True)
ok = models.BooleanField(default=True)
part_name = models.CharField(max_length=255)
short_desc = mo... | design/models.py | from django.db import models
from accounts.models import User
# Create your models here.
#
class parts(models.Model):
part_id = models.IntegerField(primary_key=True)
ok = models.BooleanField(default=True)
part_name = models.CharField(max_length=255)
short_desc = mo... | 0.662032 | 0.149749 |
import yarom as Y
from yarom.utils import slice_dict
import six
class Worm(Y.DataObject):
datatypeProperties = [{'name': 'scientific_name', 'multiple': False}]
objectProperties = ['neuron_network', 'muscle']
def defined_augment(self):
if len(self.scientific_name.values) < 1:
return Fa... | examples/c_elegans.py | import yarom as Y
from yarom.utils import slice_dict
import six
class Worm(Y.DataObject):
datatypeProperties = [{'name': 'scientific_name', 'multiple': False}]
objectProperties = ['neuron_network', 'muscle']
def defined_augment(self):
if len(self.scientific_name.values) < 1:
return Fa... | 0.805594 | 0.521654 |
import sys, time, re, socket, psycopg2
from db_con import conn, cur, ipam_ip_indx_rst, dcim_iface_indx_rst, dcim_device_indx_rst
#Time stamps for DB updates.
date = time.strftime("%Y-%m-%d")
time_stamp = time.strftime("%Y-%m-%d %H:%M:%S")
def ipam_mgmt_ip():
#Create "mgmt" network interface for existing devices... | ipam_mgmt.py | import sys, time, re, socket, psycopg2
from db_con import conn, cur, ipam_ip_indx_rst, dcim_iface_indx_rst, dcim_device_indx_rst
#Time stamps for DB updates.
date = time.strftime("%Y-%m-%d")
time_stamp = time.strftime("%Y-%m-%d %H:%M:%S")
def ipam_mgmt_ip():
#Create "mgmt" network interface for existing devices... | 0.028734 | 0.057865 |
import datetime
from app import app
from auth import auth
from models import User, Note
from flask import request, redirect, url_for, render_template, flash
from flask_turboduck.utils import get_object_or_404, object_list
# Note List
@app.route('/note/', methods=['GET','POST'])
@app.route('/notes/', methods=['GET','P... | flask_netpad/views.py |
import datetime
from app import app
from auth import auth
from models import User, Note
from flask import request, redirect, url_for, render_template, flash
from flask_turboduck.utils import get_object_or_404, object_list
# Note List
@app.route('/note/', methods=['GET','POST'])
@app.route('/notes/', methods=['GET','P... | 0.313105 | 0.053379 |
import os
import sys
from copy import deepcopy
import numpy as np
import pandas as pd
import parse_spe_reaction_info as psri
import parse_pattern as pp
def prepare_pathway_name(
data_dir, top_n=5, flag="", end_s_idx=None, species_path=False,
path_reg=None, no_path_reg=None, spe_idx=None, spe_productio... | prepare_path_name_time.py | import os
import sys
from copy import deepcopy
import numpy as np
import pandas as pd
import parse_spe_reaction_info as psri
import parse_pattern as pp
def prepare_pathway_name(
data_dir, top_n=5, flag="", end_s_idx=None, species_path=False,
path_reg=None, no_path_reg=None, spe_idx=None, spe_productio... | 0.168309 | 0.093761 |
# Import
import sqlite3
from logging import getLogger
from os import walk, mkdir
from os.path import join, isdir
from shutil import rmtree
from params import (LOGGER_NAME, INSPECT_COLLECT_DIR, SQLITE_DB_DIR)
from utils import json_deserialize
# Basic info
__version__ = "0.0.0-Beta"
__all__ = []
__author_... | lib/core/assemble.py | # Import
import sqlite3
from logging import getLogger
from os import walk, mkdir
from os.path import join, isdir
from shutil import rmtree
from params import (LOGGER_NAME, INSPECT_COLLECT_DIR, SQLITE_DB_DIR)
from utils import json_deserialize
# Basic info
__version__ = "0.0.0-Beta"
__all__ = []
__author_... | 0.272896 | 0.080647 |
import requests
from .log import LOGGER
from requests.auth import HTTPBasicAuth as Auth
class HttpApi(object):
"""
User and Password are data from Flussonic Server
(see to edit_auth, view_auth).
HTTP Basic auth.
"""
def __init__(self, user, password, url):
self.auth = Auth(user, pass... | api/http.py | import requests
from .log import LOGGER
from requests.auth import HTTPBasicAuth as Auth
class HttpApi(object):
"""
User and Password are data from Flussonic Server
(see to edit_auth, view_auth).
HTTP Basic auth.
"""
def __init__(self, user, password, url):
self.auth = Auth(user, pass... | 0.368292 | 0.080321 |