code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from pathlib import Path
from sys import platform
from cffi import FFI
from platform import architecture, machine
_ffi_def = """
extern char* ffiverify(char* proofQREncoded, char* configpath);
extern void freeCString(char* s);
"""
def _libpath():
return Path(__file__).parent.absolute()
def listlibs():
retu... | verifier/lib/__init__.py | from pathlib import Path
from sys import platform
from cffi import FFI
from platform import architecture, machine
_ffi_def = """
extern char* ffiverify(char* proofQREncoded, char* configpath);
extern void freeCString(char* s);
"""
def _libpath():
return Path(__file__).parent.absolute()
def listlibs():
retu... | 0.264263 | 0.104432 |
from pathlib import Path
from typing import (
TYPE_CHECKING,
Dict,
Iterable,
List,
Optional,
Set,
Tuple,
)
import attr
import pytest
from .constants import EXIT_STATUS_FAIL_UNUSED
from .data import SnapshotFossils
from .report import SnapshotReport
if TYPE_CHECKING:
from .assertion im... | src/syrupy/session.py | from pathlib import Path
from typing import (
TYPE_CHECKING,
Dict,
Iterable,
List,
Optional,
Set,
Tuple,
)
import attr
import pytest
from .constants import EXIT_STATUS_FAIL_UNUSED
from .data import SnapshotFossils
from .report import SnapshotReport
if TYPE_CHECKING:
from .assertion im... | 0.764188 | 0.210198 |
from pycocotools import mask as maskUtils
import mmcv
import numpy as np
from .coco import CocoDataset
from .builder import DATASETS
@DATASETS.register_module()
class OCHumanDataset(CocoDataset):
CLASSES = ('person')
def _ochuman_segm2json(self, results):
"""Convert instance segmentation results to COCO json... | mmdet/datasets/ochuman.py | from pycocotools import mask as maskUtils
import mmcv
import numpy as np
from .coco import CocoDataset
from .builder import DATASETS
@DATASETS.register_module()
class OCHumanDataset(CocoDataset):
CLASSES = ('person')
def _ochuman_segm2json(self, results):
"""Convert instance segmentation results to COCO json... | 0.617051 | 0.242071 |
import codecs
import locale
import pathlib
import os
import re
class Cite:
"""Citation package emurating contents and commands.
Parameters
----------
citeleft : str, default '['
Left delimiter of list.
citeright : str, default ']'
Right delimiter of list.
use_cite_package : bo... | wdbibtex/latex.py | import codecs
import locale
import pathlib
import os
import re
class Cite:
"""Citation package emurating contents and commands.
Parameters
----------
citeleft : str, default '['
Left delimiter of list.
citeright : str, default ']'
Right delimiter of list.
use_cite_package : bo... | 0.714628 | 0.132767 |
import os
import torch
from settings import constants, arg
from game import card_tools, TerminalEquity
from logs import logger
import numpy as np
import random
from scipy import stats
class TreeMatch():
def __init__(self):
self.match_nums = 1000000
self.terminal_equity_cache = {}
def match(se... | src/tree/tree_match.py | import os
import torch
from settings import constants, arg
from game import card_tools, TerminalEquity
from logs import logger
import numpy as np
import random
from scipy import stats
class TreeMatch():
def __init__(self):
self.match_nums = 1000000
self.terminal_equity_cache = {}
def match(se... | 0.325413 | 0.278609 |
import os
import hashlib
from termcolor import colored
import pickle
from . import init as user_init
from . import utility as user_utility
from . import drive as user_drive
class Folder:
def __init__(self, name, root, parent_id, folder_id):
self.name = name
self.root = root
self.parent_id... | src/scan.py | import os
import hashlib
from termcolor import colored
import pickle
from . import init as user_init
from . import utility as user_utility
from . import drive as user_drive
class Folder:
def __init__(self, name, root, parent_id, folder_id):
self.name = name
self.root = root
self.parent_id... | 0.318591 | 0.133981 |
from pylark.lark_request import RawRequestReq, _new_method_option
from pylark import lark_type, lark_type_sheet, lark_type_approval
import attr
import typing
import io
@attr.s
class CreateApprovalInstanceReq(object):
approval_code: str = attr.ib(
default="", metadata={"req_type": "json", "key": "approval... | pylark/api_service_approval_instance_create.py |
from pylark.lark_request import RawRequestReq, _new_method_option
from pylark import lark_type, lark_type_sheet, lark_type_approval
import attr
import typing
import io
@attr.s
class CreateApprovalInstanceReq(object):
approval_code: str = attr.ib(
default="", metadata={"req_type": "json", "key": "approval... | 0.354098 | 0.191082 |
import os
from time import sleep,time
from rm_dir import remover
#Function to scan and put empty directories in an dictionary
def dir_scanner(path):
emptys=[]
for paths,dirs,files in os.walk(path):
if len(files)<=0 and len(dirs)<=0:
emptys.append(paths)
print("\n***Empty dir... | main.py | import os
from time import sleep,time
from rm_dir import remover
#Function to scan and put empty directories in an dictionary
def dir_scanner(path):
emptys=[]
for paths,dirs,files in os.walk(path):
if len(files)<=0 and len(dirs)<=0:
emptys.append(paths)
print("\n***Empty dir... | 0.078539 | 0.101991 |
import resource
import signal
import time
import pytest
from bitmath import MiB
from pji.control.model import ProcessResult
_DEMO_RUSAGE = resource.struct_rusage((2.0, 1.0, 131072, 0, 0, 0, 2216, 0, 0, 0, 0, 0, 0, 0, 246, 129))
_TIME_0_0 = time.time()
_TIME_1_0 = _TIME_0_0 + 1.0
_TIME_1_5 = _TIME_0_0 + 1.5
_TIME_3_... | test/control/model/test_process.py | import resource
import signal
import time
import pytest
from bitmath import MiB
from pji.control.model import ProcessResult
_DEMO_RUSAGE = resource.struct_rusage((2.0, 1.0, 131072, 0, 0, 0, 2216, 0, 0, 0, 0, 0, 0, 0, 246, 129))
_TIME_0_0 = time.time()
_TIME_1_0 = _TIME_0_0 + 1.0
_TIME_1_5 = _TIME_0_0 + 1.5
_TIME_3_... | 0.488283 | 0.458894 |
from unittest.mock import AsyncMock
import pytest
from pytest_mock.plugin import MockerFixture
from app.core.exceptions import TakeSnapshotError
from app.services.browser import Browser
from app.services.browsers.httpx import HttpxBrowser
from app.services.browsers.playwright import PlaywrightBrowser
@pytest.mark.a... | tests/services/test_browser.py | from unittest.mock import AsyncMock
import pytest
from pytest_mock.plugin import MockerFixture
from app.core.exceptions import TakeSnapshotError
from app.services.browser import Browser
from app.services.browsers.httpx import HttpxBrowser
from app.services.browsers.playwright import PlaywrightBrowser
@pytest.mark.a... | 0.681091 | 0.452959 |
import random
from pathlib import Path
import numpy as np
import textgrid
from scipy.io import wavfile
from vietTTS.nat.model import DurationModel
from .config import AcousticInput, DurationInput
def load_phonemes_set_from_lexicon_file(fn: Path):
S = set()
for line in open(fn, 'r').readlines():
word, phonem... | vietTTS/nat/data_loader.py | import random
from pathlib import Path
import numpy as np
import textgrid
from scipy.io import wavfile
from vietTTS.nat.model import DurationModel
from .config import AcousticInput, DurationInput
def load_phonemes_set_from_lexicon_file(fn: Path):
S = set()
for line in open(fn, 'r').readlines():
word, phonem... | 0.410756 | 0.352035 |
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.NewsAggregationValue import NewsAggregationValue
from alipay.aop.api.domain.NewsAggregationValue import NewsAggregationValue
from alipay.aop.api.domain.NewsAggregationValue import NewsAggregationValue
class NewsEntityAggregat... | alipay/aop/api/domain/NewsEntityAggregation.py | import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.NewsAggregationValue import NewsAggregationValue
from alipay.aop.api.domain.NewsAggregationValue import NewsAggregationValue
from alipay.aop.api.domain.NewsAggregationValue import NewsAggregationValue
class NewsEntityAggregat... | 0.426202 | 0.070848 |
'''ModelArts model v2 action implementations'''
import logging
from osc_lib import utils
from osc_lib.command import command
from otcextensions.common import sdk_utils
from otcextensions.i18n import _
LOG = logging.getLogger(__name__)
def _flatten_output(obj):
data = {
'model_name': obj.model_name,
... | otcextensions/osclient/modelarts/v1/models.py | '''ModelArts model v2 action implementations'''
import logging
from osc_lib import utils
from osc_lib.command import command
from otcextensions.common import sdk_utils
from otcextensions.i18n import _
LOG = logging.getLogger(__name__)
def _flatten_output(obj):
data = {
'model_name': obj.model_name,
... | 0.717408 | 0.149314 |
import argparse
import unittest
from unittest import mock
import skelebot as sb
class TestExecutor(unittest.TestCase):
@mock.patch('skelebot.systems.execution.executor.print')
@mock.patch('skelebot.systems.parsing.skeleParser')
@mock.patch('skelebot.systems.execution.executor.VERSION', '6.6.6')
def t... | test/test_systems_execution_executor.py | import argparse
import unittest
from unittest import mock
import skelebot as sb
class TestExecutor(unittest.TestCase):
@mock.patch('skelebot.systems.execution.executor.print')
@mock.patch('skelebot.systems.parsing.skeleParser')
@mock.patch('skelebot.systems.execution.executor.VERSION', '6.6.6')
def t... | 0.630116 | 0.443781 |
import math
import os
import sys
if(len(sys.argv)<2):
print "execution : $ python FHT.py <path to directory containing files>"
exit()
# path of the directory of files for generating header matrix
path = "/Users/charanshampur/newAwsDump/dumpedContents/application/rdf+xml";
#path="/Users/charanshampur/newAwsDump... | 6.FHT/FHT.py | import math
import os
import sys
if(len(sys.argv)<2):
print "execution : $ python FHT.py <path to directory containing files>"
exit()
# path of the directory of files for generating header matrix
path = "/Users/charanshampur/newAwsDump/dumpedContents/application/rdf+xml";
#path="/Users/charanshampur/newAwsDump... | 0.043305 | 0.100172 |
import streamlit as st
import pandas as pd
import pyfolio as pf
import matplotlib.pyplot as plt
from fastbt.rapid import backtest
from fastbt.datasource import DataSource
@st.cache
def load_data(x, y):
tmp = x[x.symbol.isin(y)]
return tmp
@st.cache
def transform(data):
"""
Return transform data
... | examples/apps/simple.py | import streamlit as st
import pandas as pd
import pyfolio as pf
import matplotlib.pyplot as plt
from fastbt.rapid import backtest
from fastbt.datasource import DataSource
@st.cache
def load_data(x, y):
tmp = x[x.symbol.isin(y)]
return tmp
@st.cache
def transform(data):
"""
Return transform data
... | 0.506591 | 0.352369 |
import pytest
from django.core.validators import (
MaxValueValidator,
MinValueValidator,
)
from django.db import models
from django.test import TestCase
from rest_framework import (
exceptions,
metadata,
serializers,
status,
versioning,
views
)
from rest_framework.renderers import Brow... | tests/tests.py | import pytest
from django.core.validators import (
MaxValueValidator,
MinValueValidator,
)
from django.db import models
from django.test import TestCase
from rest_framework import (
exceptions,
metadata,
serializers,
status,
versioning,
views
)
from rest_framework.renderers import Brow... | 0.6488 | 0.332785 |
from abc import ABC, abstractmethod
import paho.mqtt.client as mqtt
from beamline.model.parameters import *
class AbstractMiner(ABC):
def __init__(self, id):
self._id = id
self._name = ""
self._description = ""
self._running = False
self._configured = True
self._st... | beamline/miners/abstract.py | from abc import ABC, abstractmethod
import paho.mqtt.client as mqtt
from beamline.model.parameters import *
class AbstractMiner(ABC):
def __init__(self, id):
self._id = id
self._name = ""
self._description = ""
self._running = False
self._configured = True
self._st... | 0.744285 | 0.086323 |
import json
import uuid
from typing import Any, Tuple
import numpy as np
from aea.exceptions import enforce
from aea.helpers.search.generic import (
AGENT_LOCATION_MODEL,
AGENT_PERSONALITY_MODEL,
AGENT_REMOVE_SERVICE_MODEL,
AGENT_SET_SERVICE_MODEL,
SIMPLE_DATA_MODEL,
)
from aea.helpers.search.mode... | packages/fetchai/skills/ml_data_provider/strategy.py | import json
import uuid
from typing import Any, Tuple
import numpy as np
from aea.exceptions import enforce
from aea.helpers.search.generic import (
AGENT_LOCATION_MODEL,
AGENT_PERSONALITY_MODEL,
AGENT_REMOVE_SERVICE_MODEL,
AGENT_SET_SERVICE_MODEL,
SIMPLE_DATA_MODEL,
)
from aea.helpers.search.mode... | 0.900311 | 0.246772 |
data = {
"apache-2.0": {
"name": "Apache-2.0",
"fullName": "Apache License 2.0",
"rules": {
"appendNoticeFileIfExists": True,
"distributeOriginalLicenseText": True,
}
},
"beerware": {
"name": "Beerware",
"fullName": "Beerware",
... | vgazer/licenses.py | data = {
"apache-2.0": {
"name": "Apache-2.0",
"fullName": "Apache License 2.0",
"rules": {
"appendNoticeFileIfExists": True,
"distributeOriginalLicenseText": True,
}
},
"beerware": {
"name": "Beerware",
"fullName": "Beerware",
... | 0.401219 | 0.465205 |
from types import SimpleNamespace
import torch
import torch.nn as nn
from torch import Tensor
from transformers import AutoConfig, AutoModel
class AttentionHead(nn.Module):
def __init__(self, in_size: int = 768, hidden_size: int = 512) -> None:
super().__init__()
self.W = nn.Linear(in_size, hidde... | models.py |
from types import SimpleNamespace
import torch
import torch.nn as nn
from torch import Tensor
from transformers import AutoConfig, AutoModel
class AttentionHead(nn.Module):
def __init__(self, in_size: int = 768, hidden_size: int = 512) -> None:
super().__init__()
self.W = nn.Linear(in_size, hidde... | 0.954816 | 0.535766 |
import sys
sys.path.append('thirdparty/AdaptiveWingLoss')
import os, glob
import numpy as np
import cv2
import argparse
from src.dataset.image_translation import landmark_extraction, landmark_image_to_data
from approaches.train_image_translation import Image_translation_block
import platform
import torch
if platform.... | Tencent/Video_Generation/MakeItTalk/main_train_image_translation.py | import sys
sys.path.append('thirdparty/AdaptiveWingLoss')
import os, glob
import numpy as np
import cv2
import argparse
from src.dataset.image_translation import landmark_extraction, landmark_image_to_data
from approaches.train_image_translation import Image_translation_block
import platform
import torch
if platform.... | 0.2676 | 0.070592 |
import sys
import threading
import warnings
from pyaedt.generic.general_methods import is_ironpython
if not is_ironpython:
try:
import numpy as np
except ImportError:
warnings.warn(
"The NumPy module is required to run some functionalities of PostProcess.\n"
"Install wi... | pyaedt/generic/python_optimizers.py | import sys
import threading
import warnings
from pyaedt.generic.general_methods import is_ironpython
if not is_ironpython:
try:
import numpy as np
except ImportError:
warnings.warn(
"The NumPy module is required to run some functionalities of PostProcess.\n"
"Install wi... | 0.549157 | 0.368065 |
from __future__ import annotations
from typing import Any, Callable, TYPE_CHECKING, Iterator, Tuple
from django.apps import apps
from maybe import Maybe
from subtypes import Str
from .config import SqlConfig
if TYPE_CHECKING:
from .sql import DjangoSql
class DjangoApp(SqlConfig.Sql.Constructors.Schema):
... | sqlhandler/django/database.py | from __future__ import annotations
from typing import Any, Callable, TYPE_CHECKING, Iterator, Tuple
from django.apps import apps
from maybe import Maybe
from subtypes import Str
from .config import SqlConfig
if TYPE_CHECKING:
from .sql import DjangoSql
class DjangoApp(SqlConfig.Sql.Constructors.Schema):
... | 0.81721 | 0.10393 |
import hashlib
import os
import sys
import time
import simplejson as json
import requests
from .utils import week_number
from .errors import CredentialsMissingError
API_BASE_URL = "https://searchlight.conductor.com"
class SearchlightService(object):
def __init__(self, **kwargs):
self._api_key = kwargs.... | searchlight_api/client.py | import hashlib
import os
import sys
import time
import simplejson as json
import requests
from .utils import week_number
from .errors import CredentialsMissingError
API_BASE_URL = "https://searchlight.conductor.com"
class SearchlightService(object):
def __init__(self, **kwargs):
self._api_key = kwargs.... | 0.47658 | 0.101367 |
import io
import numpy
import os
import pandas
import matplotlib.pyplot as plt
class DataManager:
def __init__(self, filename, hasId=True):
print('I am going to open file: %s' % (filename,))
pd = pandas.read_table(filename, comment='#', delim_whitespace=True)
#print(pd)
fldArray = pd.keys()
mapp... | DataManager.py | import io
import numpy
import os
import pandas
import matplotlib.pyplot as plt
class DataManager:
def __init__(self, filename, hasId=True):
print('I am going to open file: %s' % (filename,))
pd = pandas.read_table(filename, comment='#', delim_whitespace=True)
#print(pd)
fldArray = pd.keys()
mapp... | 0.252845 | 0.212099 |
import os
import torch
import torchvision
from time import time
try:
import wandb
except:
pass
from snf.train.statsrecorder import StatsRecorder
default_config = {
'name': None,
'notes': None,
'wandb': False,
'wandb_project': 'YOU_PROJECT_NAME',
'wandb_entity': 'YOUR_... | snf/train/experiment.py | import os
import torch
import torchvision
from time import time
try:
import wandb
except:
pass
from snf.train.statsrecorder import StatsRecorder
default_config = {
'name': None,
'notes': None,
'wandb': False,
'wandb_project': 'YOU_PROJECT_NAME',
'wandb_entity': 'YOUR_... | 0.589007 | 0.172015 |
# added warning
import pickle # nosec
import time
from argparse import ArgumentParser
import os
from itertools import repeat
from typing import Tuple, List
from glob import glob
from multiprocessing import Pool, cpu_count
import pathlib
from giant._typing import PATH
from giant.ray_tracer.kdtree import KDTree
from gi... | giant/scripts/spc_to_feature_catalogue.py | # added warning
import pickle # nosec
import time
from argparse import ArgumentParser
import os
from itertools import repeat
from typing import Tuple, List
from glob import glob
from multiprocessing import Pool, cpu_count
import pathlib
from giant._typing import PATH
from giant.ray_tracer.kdtree import KDTree
from gi... | 0.489015 | 0.266451 |
from django.db.models import Q
from antinex_utils.consts import SUCCESS
from antinex_utils.consts import ERROR
from spylunking.log.setup_logging import build_colorized_logger
from drf_network_pipeline.pipeline.build_worker_result_node import \
build_worker_result_node
from drf_network_pipeline.pipeline.models impor... | webapp/drf_network_pipeline/pipeline/process_worker_results.py | from django.db.models import Q
from antinex_utils.consts import SUCCESS
from antinex_utils.consts import ERROR
from spylunking.log.setup_logging import build_colorized_logger
from drf_network_pipeline.pipeline.build_worker_result_node import \
build_worker_result_node
from drf_network_pipeline.pipeline.models impor... | 0.496826 | 0.082107 |
# TODO: use ndarray of numpy replace original python list implementation(next PR)
from copy import deepcopy
def min_edit_distance(
source: str,
target: str,
del_cost=1,
ins_cost=1,
sub_cost=2,
):
"""Minimum-Edit-Distance(DP)
Args:
`source`: source chars.
`target`: target c... | lna/algorithms/min_edit_distance.py | # TODO: use ndarray of numpy replace original python list implementation(next PR)
from copy import deepcopy
def min_edit_distance(
source: str,
target: str,
del_cost=1,
ins_cost=1,
sub_cost=2,
):
"""Minimum-Edit-Distance(DP)
Args:
`source`: source chars.
`target`: target c... | 0.581541 | 0.670959 |
import os
import matplotlib.pyplot as plt
import numpy as np
import seaborn
from matplotlib.animation import FuncAnimation
from legendre_series import legendre_polynomials, legendre_series, \
step_function, v_function, convergence_rate, convergence_line_log
DEFAULT_DIR = os.path.join(os.path.dirname(__file__), "... | plots.py | import os
import matplotlib.pyplot as plt
import numpy as np
import seaborn
from matplotlib.animation import FuncAnimation
from legendre_series import legendre_polynomials, legendre_series, \
step_function, v_function, convergence_rate, convergence_line_log
DEFAULT_DIR = os.path.join(os.path.dirname(__file__), "... | 0.588771 | 0.508361 |
from typing import Callable
import pandas as pd
from random import choice
import numpy as np
from datasets.base_dataset import PathBaseDataset
class TripletsCSVDataset(PathBaseDataset):
'''
Csv dataset representation (csv will be in RAM) for triplets
'''
def __init__(
self,
... | src/datasets/triplets_csv_dataset.py | from typing import Callable
import pandas as pd
from random import choice
import numpy as np
from datasets.base_dataset import PathBaseDataset
class TripletsCSVDataset(PathBaseDataset):
'''
Csv dataset representation (csv will be in RAM) for triplets
'''
def __init__(
self,
... | 0.758242 | 0.323293 |
import config
import datetime
import errors
import flask
def call(func):
"""Call API wrapper.
Gracefully responds to requests that raise exceptions.
:param func [function]: function to call
:returns [tuple[dict, int]]: JSON response via helper functions
"""
try:
return _success(func(... | utils/handler.py | import config
import datetime
import errors
import flask
def call(func):
"""Call API wrapper.
Gracefully responds to requests that raise exceptions.
:param func [function]: function to call
:returns [tuple[dict, int]]: JSON response via helper functions
"""
try:
return _success(func(... | 0.642769 | 0.397061 |
import re
import sys
from hashlib import sha1
import logging
import subprocess as sp
from pathlib import Path
from remake.util import sysrun
from remake.setup_logging import setup_stdout_logging
from remake.loader import load_remake
from remake.task import Task, RescanFileTask
from remake.executor.base_executor import... | remake/executor/slurm_executor.py | import re
import sys
from hashlib import sha1
import logging
import subprocess as sp
from pathlib import Path
from remake.util import sysrun
from remake.setup_logging import setup_stdout_logging
from remake.loader import load_remake
from remake.task import Task, RescanFileTask
from remake.executor.base_executor import... | 0.266739 | 0.065187 |
from unittest import TestCase
from day7.part1.get_signal_for_wire import get_signal_for_wire
class TestGetSignalForWire(TestCase):
def test_get_signal_for_wire_1(self):
expected_value = 72
instructions = [
"123 -> x",
"456 -> y",
"x AND y -> d"
]
... | day7/part1/test_get_signal_for_wire.py | from unittest import TestCase
from day7.part1.get_signal_for_wire import get_signal_for_wire
class TestGetSignalForWire(TestCase):
def test_get_signal_for_wire_1(self):
expected_value = 72
instructions = [
"123 -> x",
"456 -> y",
"x AND y -> d"
]
... | 0.782746 | 0.691344 |
# Import Packages
import pandas as pd
import numpy as np
import math
from pylab import *
from scipy import linalg as la
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt
import matplotlib.transforms as mtrans
from matplotlib.offsetbox im... | GPS_Strain/GPS_Strain.py |
# Import Packages
import pandas as pd
import numpy as np
import math
from pylab import *
from scipy import linalg as la
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt
import matplotlib.transforms as mtrans
from matplotlib.offsetbox im... | 0.67971 | 0.398787 |
import sys
import os
import glob as gb
from subprocess import check_output, Popen, PIPE, STDOUT
import pytest
from idftags import __version__ as VERSION
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
class TestHelp():
"""
Py.test class for the help
"""
def test_help(self):
"""
... | tests/test_cli.py |
import sys
import os
import glob as gb
from subprocess import check_output, Popen, PIPE, STDOUT
import pytest
from idftags import __version__ as VERSION
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
class TestHelp():
"""
Py.test class for the help
"""
def test_help(self):
"""
... | 0.399343 | 0.317876 |
import time
import requests
from bs4 import BeautifulSoup
from crawlers.generic import BaseCrawler
from settings import BEGIN_CRAWL_SINCE, UTC_HOUR_DIFF
class OneJuxCrawler(BaseCrawler):
def __init__(self, *args, **kwargs):
super(OneJuxCrawler, self).__init__(source='one_jux', *args, **kwargs)
s... | crawlers/one_jux.py | import time
import requests
from bs4 import BeautifulSoup
from crawlers.generic import BaseCrawler
from settings import BEGIN_CRAWL_SINCE, UTC_HOUR_DIFF
class OneJuxCrawler(BaseCrawler):
def __init__(self, *args, **kwargs):
super(OneJuxCrawler, self).__init__(source='one_jux', *args, **kwargs)
s... | 0.209955 | 0.122156 |
import csv
import os
from six import string_types, Iterator
from toolz.functoolz import curry, identity
from functools import partial
def sortcsv(input_filename, output_filename, on_cols, input_file_callable=lambda x: open(x, 'r'),
output_file_callable=lambda x: open(x, 'w'), input_csv_config={},
... | oreader/sortcsv.py | import csv
import os
from six import string_types, Iterator
from toolz.functoolz import curry, identity
from functools import partial
def sortcsv(input_filename, output_filename, on_cols, input_file_callable=lambda x: open(x, 'r'),
output_file_callable=lambda x: open(x, 'w'), input_csv_config={},
... | 0.182025 | 0.09947 |
class Error(Exception):
pass
class Line(str):
"""A line of text with associated filename and line number."""
def error(self, message):
"""Return an error relating to this line."""
return Error("{0}({1}): {2}\n{3}"
.format(self.filename, self.lineno, message, self))
cla... | readFastQ.py | class Error(Exception):
pass
class Line(str):
"""A line of text with associated filename and line number."""
def error(self, message):
"""Return an error relating to this line."""
return Error("{0}({1}): {2}\n{3}"
.format(self.filename, self.lineno, message, self))
cla... | 0.856242 | 0.335215 |
import unittest
import os
from shutil import rmtree
import numpy as np
import torch
import torch.nn as nn
from inferno.trainers.basic import Trainer
from torch.utils.data.dataset import TensorDataset
from torch.utils.data.dataloader import DataLoader
from inferno.trainers.callbacks.logging.tensorboard import Tensorboa... | tests/test_training/test_callbacks/test_logging/test_tensorboard.py | import unittest
import os
from shutil import rmtree
import numpy as np
import torch
import torch.nn as nn
from inferno.trainers.basic import Trainer
from torch.utils.data.dataset import TensorDataset
from torch.utils.data.dataloader import DataLoader
from inferno.trainers.callbacks.logging.tensorboard import Tensorboa... | 0.792625 | 0.430387 |
import tweepy as tw
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import pandas as pd
from tqdm import tqdm
from os import getenv, path, remove
class Tweet:
def __init__(self) -> None:
self.file_path = 'tmp/tweets_to_work.csv'
self._auth = tw.OAuthHandler(
geten... | Tweet.py |
import tweepy as tw
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import pandas as pd
from tqdm import tqdm
from os import getenv, path, remove
class Tweet:
def __init__(self) -> None:
self.file_path = 'tmp/tweets_to_work.csv'
self._auth = tw.OAuthHandler(
geten... | 0.273769 | 0.075176 |
import torch
import torch.nn as nn
def weights_init_reg(m):
if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.Batch... | .backup/ProREG.py | import torch
import torch.nn as nn
def weights_init_reg(m):
if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.Batch... | 0.937397 | 0.546194 |
import tkinter as tk
import subprocess
import os
import signal
from tkinter import *
from tkinter import ttk, filedialog, messagebox, colorchooser
from copy import copy, deepcopy
from time import sleep
from threading import Timer
sign = lambda x: (1, -1)[x < 0]
global colour_selected, colour_possible_mo... | checkers_gui.py | import tkinter as tk
import subprocess
import os
import signal
from tkinter import *
from tkinter import ttk, filedialog, messagebox, colorchooser
from copy import copy, deepcopy
from time import sleep
from threading import Timer
sign = lambda x: (1, -1)[x < 0]
global colour_selected, colour_possible_mo... | 0.219923 | 0.105257 |
def load_result_file(path):
results = []
with open(path) as f:
r = Result()
for line in f:
if line.startswith('==='):
results.append(r)
r = Result()
continue
name, val = line.split(':')
if name == 'total ports':
... | exp/motivation/more_ports_exp/exp_result.py | def load_result_file(path):
results = []
with open(path) as f:
r = Result()
for line in f:
if line.startswith('==='):
results.append(r)
r = Result()
continue
name, val = line.split(':')
if name == 'total ports':
... | 0.408631 | 0.194349 |
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn import metrics
import pandas as pd
import numpy as np
import seaborn as sns
import os
import matplotlib.pyplot as plt
from scipy import stats
diabetes = load_diabetes()
diabetes_df = pd.DataFrame(data=np.c_[di... | Python_Scripts/linear_regression.py | from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn import metrics
import pandas as pd
import numpy as np
import seaborn as sns
import os
import matplotlib.pyplot as plt
from scipy import stats
diabetes = load_diabetes()
diabetes_df = pd.DataFrame(data=np.c_[di... | 0.629319 | 0.670258 |
import numpy
import os
folder_gdsc = os.path.dirname(__file__)+"/"
gdsc_file = folder_gdsc+"ic50_excl_empty_filtered_cell_lines_drugs.txt"
gdsc_file_std = folder_gdsc+"ic50_excl_empty_filtered_cell_lines_drugs_standardised.txt"
def load_gdsc(location=None,standardised=False,sep=","):
"""
Load in data. We get... | data_drug_sensitivity/gdsc/load_data.py | import numpy
import os
folder_gdsc = os.path.dirname(__file__)+"/"
gdsc_file = folder_gdsc+"ic50_excl_empty_filtered_cell_lines_drugs.txt"
gdsc_file_std = folder_gdsc+"ic50_excl_empty_filtered_cell_lines_drugs_standardised.txt"
def load_gdsc(location=None,standardised=False,sep=","):
"""
Load in data. We get... | 0.305801 | 0.442576 |
import pandas as pd
import numpy as np
import MAIN.Basics as basics
import MAIN.Reinforcement as RL
import tensorflow as tf
import seaborn as sns
import matplotlib.pyplot as plt
from UTIL import FileIO
from STRATEGY.Cointegration import EGCointegration
# Read config
config_path = 'CONFIG\config_train.yml'
config_tra... | EXAMPLE/RunningScript.py | import pandas as pd
import numpy as np
import MAIN.Basics as basics
import MAIN.Reinforcement as RL
import tensorflow as tf
import seaborn as sns
import matplotlib.pyplot as plt
from UTIL import FileIO
from STRATEGY.Cointegration import EGCointegration
# Read config
config_path = 'CONFIG\config_train.yml'
config_tra... | 0.488771 | 0.288043 |
import tensorflow as tf
from tensorflow.python.keras.layers import Flatten, Dense, Conv2D, Dropout, BatchNormalization
from abc import ABC, abstractmethod
import numpy as np
import warnings
def dqn_mask_loss(batch_data, y_pred):
# The target is defined only for the action that was taken during the replay, hence t... | src/main/models/nets.py | import tensorflow as tf
from tensorflow.python.keras.layers import Flatten, Dense, Conv2D, Dropout, BatchNormalization
from abc import ABC, abstractmethod
import numpy as np
import warnings
def dqn_mask_loss(batch_data, y_pred):
# The target is defined only for the action that was taken during the replay, hence t... | 0.90662 | 0.403596 |
import numpy as np
from sklearn.model_selection import train_test_split
import tensorflow as tf
import tensorflow.keras as tfk
import tensorflow.keras.layers as tfkl
import tensorflow.keras.models as tfkm
class GENERICorama(object):
"""Generic panorama generator.
"""
def __init__(self, dataset,
... | PanoramAI/generic.py | import numpy as np
from sklearn.model_selection import train_test_split
import tensorflow as tf
import tensorflow.keras as tfk
import tensorflow.keras.layers as tfkl
import tensorflow.keras.models as tfkm
class GENERICorama(object):
"""Generic panorama generator.
"""
def __init__(self, dataset,
... | 0.856932 | 0.671363 |
import pytest
import crummycm as ccm
from example_files.a import flat_a, nested_a, flat_a_pop_exact
ex_config = {
"flat_a_yml_0": (
(flat_a, "tests/unit/template/basic/example_files/out_yml/flat_a.yml", 0),
{
"my_mixed": {
"kd_num": "<class 'int'>[Numeric]*",
... | tests/unit/template/basic/test_basic_template.py | import pytest
import crummycm as ccm
from example_files.a import flat_a, nested_a, flat_a_pop_exact
ex_config = {
"flat_a_yml_0": (
(flat_a, "tests/unit/template/basic/example_files/out_yml/flat_a.yml", 0),
{
"my_mixed": {
"kd_num": "<class 'int'>[Numeric]*",
... | 0.407569 | 0.391988 |
import json
def merge_base_poly():
details = []
with open('polyphone_final.json', 'r', encoding='utf-8') as words:
contents = json.load(words)
for single in contents:
details.append(single)
print(len(details))
results = []
with open('char_base.json', 'r', encoding='utf... | scripts/hanzi_base.py | import json
def merge_base_poly():
details = []
with open('polyphone_final.json', 'r', encoding='utf-8') as words:
contents = json.load(words)
for single in contents:
details.append(single)
print(len(details))
results = []
with open('char_base.json', 'r', encoding='utf... | 0.114814 | 0.101679 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, logging
from pprint import pprint
from utils import config as cfg
if cfg.ROOT_DIR.startswith('/home'):
import torch
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # set tensorflow logger to WARNING... | utils/base_solver.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, logging
from pprint import pprint
from utils import config as cfg
if cfg.ROOT_DIR.startswith('/home'):
import torch
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # set tensorflow logger to WARNING... | 0.529993 | 0.075312 |
from time import sleep
def coolCafe():
print("Welcome to Cathy's Café!")
for key in cafemenu_options.keys():
print(key, '--', cafemenu_options[key])
runCafeOptions()
cafemenu_options = {
1: "Coffee",
2: "Cake",
3: "Tea",
4: "Exit",
}
def coffee():
print("One hot cup of coffee... | tech_talks/cafe.py | from time import sleep
def coolCafe():
print("Welcome to Cathy's Café!")
for key in cafemenu_options.keys():
print(key, '--', cafemenu_options[key])
runCafeOptions()
cafemenu_options = {
1: "Coffee",
2: "Cake",
3: "Tea",
4: "Exit",
}
def coffee():
print("One hot cup of coffee... | 0.19544 | 0.223441 |
import redis
from rq import Queue, Connection
from flask import render_template, Blueprint, jsonify, request, current_app
from project.server.main.tasks import create_task_classify, create_task_calibrate
main_blueprint = Blueprint("main", __name__,)
from project.server.main.logger import get_logger
logger = get_logg... | project/server/main/views.py | import redis
from rq import Queue, Connection
from flask import render_template, Blueprint, jsonify, request, current_app
from project.server.main.tasks import create_task_classify, create_task_calibrate
main_blueprint = Blueprint("main", __name__,)
from project.server.main.logger import get_logger
logger = get_logg... | 0.219923 | 0.09122 |
import numpy as np
np.seterr(all='ignore')
# np.set_printoptions(threshold=sys.maxsize)
class Power(object):
"""
Container for power spectra for each component, with any shape
Attributes
----------
c11 : :class:`~numpy.ndarray`
Power spectral density for component 1 (any shape)
c22 :... | obstools/atacr/classes/containers.py | import numpy as np
np.seterr(all='ignore')
# np.set_printoptions(threshold=sys.maxsize)
class Power(object):
"""
Container for power spectra for each component, with any shape
Attributes
----------
c11 : :class:`~numpy.ndarray`
Power spectral density for component 1 (any shape)
c22 :... | 0.840259 | 0.615983 |
from flask import request
import os
from flask_wtf import FlaskForm
from wtforms import TextField, BooleanField, TextAreaField, SubmitField
import pandas as pd
from flask_mail import Mail, Message
import secrets
import json
import pandas as pd
import numpy as np
from utils import get_data_utils as get_data_utils
from... | helper.py | from flask import request
import os
from flask_wtf import FlaskForm
from wtforms import TextField, BooleanField, TextAreaField, SubmitField
import pandas as pd
from flask_mail import Mail, Message
import secrets
import json
import pandas as pd
import numpy as np
from utils import get_data_utils as get_data_utils
from... | 0.522202 | 0.202759 |
import lief
import pathlib
from utils import get_sample
def test_exports_trie():
target = lief.parse(get_sample('MachO/MachO64_x86-64_binary_exports-trie-LLVM.bin'))
assert target.has_dyld_info
exports = target.dyld_info.exports
assert len(exports) == 6
assert exports[0].address == 0
assert e... | tests/macho/test_dyld.py | import lief
import pathlib
from utils import get_sample
def test_exports_trie():
target = lief.parse(get_sample('MachO/MachO64_x86-64_binary_exports-trie-LLVM.bin'))
assert target.has_dyld_info
exports = target.dyld_info.exports
assert len(exports) == 6
assert exports[0].address == 0
assert e... | 0.587588 | 0.573678 |
from django.shortcuts import render,redirect,get_object_or_404
from django.contrib.auth import login,authenticate
from django.contrib.auth.decorators import login_required
from .models import Profile,NeighbourHood,Post,Business
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
fro... | hood/views.py | from django.shortcuts import render,redirect,get_object_or_404
from django.contrib.auth import login,authenticate
from django.contrib.auth.decorators import login_required
from .models import Profile,NeighbourHood,Post,Business
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
fro... | 0.31279 | 0.056055 |
from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from ..date import SplitDateWidget, SplitDateField
class SplitDateWidgetTests(TestCase):
def test_render_assigns_ids_and_labels(self):
widget = SplitDateWidget()
content = widget.render('... | frontend/tests/test_date.py | from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from ..date import SplitDateWidget, SplitDateField
class SplitDateWidgetTests(TestCase):
def test_render_assigns_ids_and_labels(self):
widget = SplitDateWidget()
content = widget.render('... | 0.707506 | 0.533276 |
import typing as ty
import numpy as np
from .dataset_adapters import Dataset
from .kernel_specs import (
AdditiveKernelSpec,
KernelSpec,
BaseKernelSpec,
GenericKernelSpec,
PeriodicKernelSpec,
PeriodicNoConstKernelSpec,
ConstraintBounds as CB,
ProductKernelSpec,
TopLevelKernelSpec,
)... | autostat/constraints.py | import typing as ty
import numpy as np
from .dataset_adapters import Dataset
from .kernel_specs import (
AdditiveKernelSpec,
KernelSpec,
BaseKernelSpec,
GenericKernelSpec,
PeriodicKernelSpec,
PeriodicNoConstKernelSpec,
ConstraintBounds as CB,
ProductKernelSpec,
TopLevelKernelSpec,
)... | 0.545528 | 0.41947 |
import yfinance as yf
import pandas as pd
import datetime as dt
from pandas_datareader import data as pdr
import yfinance as yf
import util as util
yf.pdr_override()
start = dt.datetime.now() - dt.timedelta(days=365)
now = dt.datetime.now()
index_change_dict = {}
def get_relative_strength(stock, index, data = None)... | indicators.py | import yfinance as yf
import pandas as pd
import datetime as dt
from pandas_datareader import data as pdr
import yfinance as yf
import util as util
yf.pdr_override()
start = dt.datetime.now() - dt.timedelta(days=365)
now = dt.datetime.now()
index_change_dict = {}
def get_relative_strength(stock, index, data = None)... | 0.355663 | 0.419529 |
from naoth.LogReader import LogReader
from naoth.LogReader import Parser
from matplotlib import pyplot
import numpy
class XABSLSymbols:
def __init__(self):
self.values = {}
self.decimalIdToName = {}
self.booleanIdToName = {}
self.enumIdToName = {}
class BehaviorParser(Parser):
... | Utils/py/MotionAnalysis/BehaviorParser.py | from naoth.LogReader import LogReader
from naoth.LogReader import Parser
from matplotlib import pyplot
import numpy
class XABSLSymbols:
def __init__(self):
self.values = {}
self.decimalIdToName = {}
self.booleanIdToName = {}
self.enumIdToName = {}
class BehaviorParser(Parser):
... | 0.438785 | 0.29 |
from starlette.requests import Request
from starlette.responses import JSONResponse
from .dataaccess import employeeda
from .permissions import Role
async def get_employees(request: Request):
employees = await employeeda.get_employees()
for e in employees:
e['role'] = Role(e['role']).name
return... | tmeister/employees.py | from starlette.requests import Request
from starlette.responses import JSONResponse
from .dataaccess import employeeda
from .permissions import Role
async def get_employees(request: Request):
employees = await employeeda.get_employees()
for e in employees:
e['role'] = Role(e['role']).name
return... | 0.38341 | 0.083367 |
import time
import numpy as np
import argparse
import sys
sys.path.append("../../")
import grpc
from grpc_ps import ps_service_pb2_grpc
from grpc_ps.client import ps_client
# algorithm setting
NUM_EPOCHS = 10
NUM_BATCHES = 1
MODEL_NAME = "w.b"
LEARNING_RATE = 0.1
def handler(event, context):
s... | grpc_ps/test/ps_client_test_handler.py | import time
import numpy as np
import argparse
import sys
sys.path.append("../../")
import grpc
from grpc_ps import ps_service_pb2_grpc
from grpc_ps.client import ps_client
# algorithm setting
NUM_EPOCHS = 10
NUM_BATCHES = 1
MODEL_NAME = "w.b"
LEARNING_RATE = 0.1
def handler(event, context):
s... | 0.277865 | 0.090374 |
from __future__ import annotations
import argparse
import io
from enum import Enum
from pathlib import Path
from typing import Type, Any
from opentrons_hardware.drivers.can_bus import (
MessageId,
FunctionCode,
NodeId,
)
class block:
"""C block generator."""
def __init__(self, output: io.StringI... | hardware/opentrons_hardware/scripts/generate_header.py | from __future__ import annotations
import argparse
import io
from enum import Enum
from pathlib import Path
from typing import Type, Any
from opentrons_hardware.drivers.can_bus import (
MessageId,
FunctionCode,
NodeId,
)
class block:
"""C block generator."""
def __init__(self, output: io.StringI... | 0.873363 | 0.227888 |
import random
import linecache
import vk_api
import requests
from bs4 import BeautifulSoup
import time
from vk_api import VkUpload
import configparser
import logging
import os
from datetime import datetime
def get_files(path):
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path,... | autoposter.py | import random
import linecache
import vk_api
import requests
from bs4 import BeautifulSoup
import time
from vk_api import VkUpload
import configparser
import logging
import os
from datetime import datetime
def get_files(path):
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path,... | 0.146667 | 0.061565 |
import configparser
import datetime
import numpy
from data_providing_module import configurable_registry
from data_providing_module import data_provider_registry
from data_providing_module.data_providers import data_provider_static_names
from general_utils.config import config_util
from general_utils.loggi... | src/data_providing_module/data_providers/indicator_block_provider.py | import configparser
import datetime
import numpy
from data_providing_module import configurable_registry
from data_providing_module import data_provider_registry
from data_providing_module.data_providers import data_provider_static_names
from general_utils.config import config_util
from general_utils.loggi... | 0.542136 | 0.329823 |
from kqueen.kubeapi import KubernetesAPI
from kubernetes.client.rest import ApiException
from pprint import pprint as print
import pytest
import yaml
import kubernetes
def fake_raise(exc):
def fn(self, *args, **kwargs):
raise exc
return fn
class TestKubeApi:
def test_missing_cluster_param(self... | kqueen/tests/test_kubeapi.py | from kqueen.kubeapi import KubernetesAPI
from kubernetes.client.rest import ApiException
from pprint import pprint as print
import pytest
import yaml
import kubernetes
def fake_raise(exc):
def fn(self, *args, **kwargs):
raise exc
return fn
class TestKubeApi:
def test_missing_cluster_param(self... | 0.692642 | 0.29931 |
import sys
from PyQt5.QtCore import *
class WorkerSignals(QObject):
"""PyQt signals custom class"""
program_finished = pyqtSignal()
program_error = pyqtSignal(BaseException)
result = pyqtSignal(object)
def __init__(self) -> None:
super().__init__()
class LongWorker(QRunnable):
"""
... | AppVoor/resources/frontend_scripts/parallel.py | import sys
from PyQt5.QtCore import *
class WorkerSignals(QObject):
"""PyQt signals custom class"""
program_finished = pyqtSignal()
program_error = pyqtSignal(BaseException)
result = pyqtSignal(object)
def __init__(self) -> None:
super().__init__()
class LongWorker(QRunnable):
"""
... | 0.371023 | 0.21034 |
from metagraph import translator
from metagraph.plugins import has_scipy, has_networkx, has_grblas, has_pandas
import numpy as np
if has_scipy:
import scipy.sparse as ss
from .types import ScipyEdgeMap, ScipyEdgeSet, ScipyGraph
@translator
def edgemap_to_edgeset(x: ScipyEdgeMap, **props) -> ScipyEdgeS... | metagraph/plugins/scipy/translators.py | from metagraph import translator
from metagraph.plugins import has_scipy, has_networkx, has_grblas, has_pandas
import numpy as np
if has_scipy:
import scipy.sparse as ss
from .types import ScipyEdgeMap, ScipyEdgeSet, ScipyGraph
@translator
def edgemap_to_edgeset(x: ScipyEdgeMap, **props) -> ScipyEdgeS... | 0.583441 | 0.394376 |
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras.layers import (
Conv2D,
MaxPooling2D,
AveragePooling2D,
ZeroPadding2D,
GlobalAveragePooling2D,
)
from tensorflow.keras.layers import (
Flatten,
Dense,
Dropout,
BatchNormalization,
Activation,
Convo... | nets/inception_v3.py | import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras.layers import (
Conv2D,
MaxPooling2D,
AveragePooling2D,
ZeroPadding2D,
GlobalAveragePooling2D,
)
from tensorflow.keras.layers import (
Flatten,
Dense,
Dropout,
BatchNormalization,
Activation,
Convo... | 0.898093 | 0.555435 |
import argparse
import contextlib
import os
import sys
import path
import schema
import ui
import tbump.config
from tbump.file_bumper import FileBumper
from tbump.git_bumper import GitBumper
TBUMP_VERSION = "1.0.0"
@contextlib.contextmanager
def bump_git(git_bumper, new_version, dry_run=False):
git_bumper.che... | tbump/main.py | import argparse
import contextlib
import os
import sys
import path
import schema
import ui
import tbump.config
from tbump.file_bumper import FileBumper
from tbump.git_bumper import GitBumper
TBUMP_VERSION = "1.0.0"
@contextlib.contextmanager
def bump_git(git_bumper, new_version, dry_run=False):
git_bumper.che... | 0.128088 | 0.082994 |
from collections import OrderedDict
from typing import List, Dict
import mysql.connector
from mysql.connector.errors import DatabaseError, ProgrammingError
from slugify import slugify
from wwdtm.panelist import utility
#region Retrieval Functions
def retrieve_all(database_connection: mysql.connector.connect) -> List[D... | wwdtm/panelist/info.py | from collections import OrderedDict
from typing import List, Dict
import mysql.connector
from mysql.connector.errors import DatabaseError, ProgrammingError
from slugify import slugify
from wwdtm.panelist import utility
#region Retrieval Functions
def retrieve_all(database_connection: mysql.connector.connect) -> List[D... | 0.745769 | 0.27133 |
import numpy as np
import matplotlib.pyplot as plt
filename1 = './init_field_hit.dat'
filename2 = './init_field_hit_2.dat'
dataIn1 = np.loadtxt(filename1,dtype=np.double)
dataIn2 = np.loadtxt(filename2,dtype=np.double)
N = 129
U1 = np.empty((N-1,N-1,N-1),dtype=np.double)
V1 = np.empty((N-1,N-1,N-1),dt... | MiscTools/loadinithit_withpressure_largedomain.py | import numpy as np
import matplotlib.pyplot as plt
filename1 = './init_field_hit.dat'
filename2 = './init_field_hit_2.dat'
dataIn1 = np.loadtxt(filename1,dtype=np.double)
dataIn2 = np.loadtxt(filename2,dtype=np.double)
N = 129
U1 = np.empty((N-1,N-1,N-1),dtype=np.double)
V1 = np.empty((N-1,N-1,N-1),dt... | 0.042712 | 0.328893 |
from argparse import ArgumentParser
from glob import glob
import logging
from collections import OrderedDict
import json
from ssl import CERT_NONE, create_default_context
from parsedmarc import IMAPError, get_dmarc_reports_from_inbox, \
parse_report_file, elastic, kafkaclient, splunk, save_output, \
watch_inbo... | parsedmarc/cli.py | from argparse import ArgumentParser
from glob import glob
import logging
from collections import OrderedDict
import json
from ssl import CERT_NONE, create_default_context
from parsedmarc import IMAPError, get_dmarc_reports_from_inbox, \
parse_report_file, elastic, kafkaclient, splunk, save_output, \
watch_inbo... | 0.386763 | 0.089177 |
import re
from troposphere import (
AWS_REGION,
AWS_ACCOUNT_ID
)
from troposphere import (
ImportValue,
Parameter,
GetAtt,
Sub,
Ref
)
from troposphere.iam import (
Role
)
from troposphere.s3 import Bucket
from troposphere.awslambda import Function
from troposphere.kms import (
Key, A... | ozone/filters/arns.py | import re
from troposphere import (
AWS_REGION,
AWS_ACCOUNT_ID
)
from troposphere import (
ImportValue,
Parameter,
GetAtt,
Sub,
Ref
)
from troposphere.iam import (
Role
)
from troposphere.s3 import Bucket
from troposphere.awslambda import Function
from troposphere.kms import (
Key, A... | 0.631026 | 0.25326 |
# todo: daemonize?
# todo: kickass idea: make all timers use one thread that will sleep smartly
# to send all events correctly.
import threading
import time
import wx
from python_toolbox.wx_tools.timing import cute_base_timer
wxEVT_THREAD_TIMER = wx.NewEventType()
EVT_THREAD_TIMER = wx.PyEventBinder(wxEVT_THREAD_... | python_toolbox/wx_tools/timing/thread_timer.py |
# todo: daemonize?
# todo: kickass idea: make all timers use one thread that will sleep smartly
# to send all events correctly.
import threading
import time
import wx
from python_toolbox.wx_tools.timing import cute_base_timer
wxEVT_THREAD_TIMER = wx.NewEventType()
EVT_THREAD_TIMER = wx.PyEventBinder(wxEVT_THREAD_... | 0.277865 | 0.129926 |
__author__ = '<NAME>'
__date__ = '2021-11-07'
__copyright__ = '(C) 2021, <NAME>'
from PyQt5.QtCore import QCoreApplication, QVariant
from qgis.core import (QgsProcessing,
QgsFeatureSink,
QgsWkbTypes,
QgsFields,
QgsField,
... | processing_provider/Rast_getPointValue.py | __author__ = '<NAME>'
__date__ = '2021-11-07'
__copyright__ = '(C) 2021, <NAME>'
from PyQt5.QtCore import QCoreApplication, QVariant
from qgis.core import (QgsProcessing,
QgsFeatureSink,
QgsWkbTypes,
QgsFields,
QgsField,
... | 0.492432 | 0.185947 |
import numpy as np
def speed(u, v):
return np.sqrt(u ** 2 + v ** 2)
def day_night_split(solzen: np.ndarray) -> tuple:
"""
solar zenith angle (degrees, 0->180; daytime if < 85)
:param solzen: 天顶角矩阵
:return: 表示白天,黑夜的矩阵索引的元组
Reference
------
.. [#] AIRS/AMSU/HSB Version 5 Level 1B Pro... | esep/physics/base.py | import numpy as np
def speed(u, v):
return np.sqrt(u ** 2 + v ** 2)
def day_night_split(solzen: np.ndarray) -> tuple:
"""
solar zenith angle (degrees, 0->180; daytime if < 85)
:param solzen: 天顶角矩阵
:return: 表示白天,黑夜的矩阵索引的元组
Reference
------
.. [#] AIRS/AMSU/HSB Version 5 Level 1B Pro... | 0.599837 | 0.734548 |
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'schedule_file',
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('year', sa.Small... | alembic/versions/6312e2ecbbd6_init.py | from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'schedule_file',
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('year', sa.Small... | 0.364099 | 0.141519 |
import math, random
import numpy as np
from PuzzleLib.Backend import gpuarray
from PuzzleLib.Backend.Kernels.Costs import ctcLoss, ctcLossTest
from PuzzleLib.Cost.Cost import Cost
class CTC(Cost):
def __init__(self, blank, vocabsize=None, normalized=False):
super().__init__()
self.normalized = normalized
i... | Cost/CTC.py | import math, random
import numpy as np
from PuzzleLib.Backend import gpuarray
from PuzzleLib.Backend.Kernels.Costs import ctcLoss, ctcLossTest
from PuzzleLib.Cost.Cost import Cost
class CTC(Cost):
def __init__(self, blank, vocabsize=None, normalized=False):
super().__init__()
self.normalized = normalized
i... | 0.350421 | 0.53777 |
from datetime import datetime
import os
from sqlalchemy import Column, DateTime, String, BigInteger, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.schema import Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.postgresql import JSON
from sqlalchemy im... | extract/models.py | from datetime import datetime
import os
from sqlalchemy import Column, DateTime, String, BigInteger, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.schema import Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.postgresql import JSON
from sqlalchemy im... | 0.599837 | 0.138753 |
import numpy as np
from frbpoppy.log import pprint
from frbpoppy.number_density import NumberDensity
from frbpoppy.population import Population
import frbpoppy.distributions as dis
import frbpoppy.galacticops as go
import frbpoppy.precalc as pc
class CosmicPopulation(Population):
"""Generate a cosmic FRB populat... | frbpoppy/cosmic_pop.py | import numpy as np
from frbpoppy.log import pprint
from frbpoppy.number_density import NumberDensity
from frbpoppy.population import Population
import frbpoppy.distributions as dis
import frbpoppy.galacticops as go
import frbpoppy.precalc as pc
class CosmicPopulation(Population):
"""Generate a cosmic FRB populat... | 0.845305 | 0.448426 |
from __future__ import absolute_import
import os
import mxnet as mx
from mxnet import autograd
from mxnet.gluon import nn
from .rcnn_target import RCNNTargetSampler, RCNNTargetGenerator
from ..rcnn import RCNN2
from ..rpn import RPN
from ...nn.coder import NormalizedBoxCenterDecoder, MultiPerClassDecoder
from easydict... | gluoncv/model_zoo/cascade_rcnn/cascade_rcnn.py | from __future__ import absolute_import
import os
import mxnet as mx
from mxnet import autograd
from mxnet.gluon import nn
from .rcnn_target import RCNNTargetSampler, RCNNTargetGenerator
from ..rcnn import RCNN2
from ..rpn import RPN
from ...nn.coder import NormalizedBoxCenterDecoder, MultiPerClassDecoder
from easydict... | 0.815894 | 0.332148 |
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import framework
from pxr import Usd, UsdGeom, UsdShade, Vt
stage = framework.createWorkStage("fort.usda")
framework.appendLayer(stage, "more_materials.usda")
doorPrim = stage.GetPrimAtPath("/Meshes/Door/Cube_002")
leftTowerP... | prototypes/fort_collections.py | import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import framework
from pxr import Usd, UsdGeom, UsdShade, Vt
stage = framework.createWorkStage("fort.usda")
framework.appendLayer(stage, "more_materials.usda")
doorPrim = stage.GetPrimAtPath("/Meshes/Door/Cube_002")
leftTowerP... | 0.309754 | 0.117218 |
from __future__ import unicode_literals
import frappe
from six import string_types
import frappe.share
from frappe import _
from frappe.utils import cstr, now_datetime, cint, flt, get_time, get_datetime, get_link_to_form, date_diff, nowdate
from ifitwala_ed.controllers.status_updater import StatusUpdater
class UOM... | ifitwala_ed/utilities/transaction_base.py |
from __future__ import unicode_literals
import frappe
from six import string_types
import frappe.share
from frappe import _
from frappe.utils import cstr, now_datetime, cint, flt, get_time, get_datetime, get_link_to_form, date_diff, nowdate
from ifitwala_ed.controllers.status_updater import StatusUpdater
class UOM... | 0.349311 | 0.1495 |
from . import HermesTestCase
from .. import models
class PostListViewTestCase(HermesTestCase):
def url(self):
return super(PostListViewTestCase, self).url('hermes_post_list')
def test_context_contains_posts(self):
"""The PostListView Context should contain a QuerySet of all Posts"""
r... | hermes/tests/test_views.py | from . import HermesTestCase
from .. import models
class PostListViewTestCase(HermesTestCase):
def url(self):
return super(PostListViewTestCase, self).url('hermes_post_list')
def test_context_contains_posts(self):
"""The PostListView Context should contain a QuerySet of all Posts"""
r... | 0.68056 | 0.403802 |
import numpy as np
from abc import ABC, abstractmethod
import matplotlib.pyplot as plt
import shapely.geometry
from shapely.geometry.point import Point
from shapely.geometry.linestring import LineString
from shapely.geometry.polygon import LinearRing, Polygon
import shapely.affinity as affinity
from starr.misc import p... | src/starr/geometry_component.py | import numpy as np
from abc import ABC, abstractmethod
import matplotlib.pyplot as plt
import shapely.geometry
from shapely.geometry.point import Point
from shapely.geometry.linestring import LineString
from shapely.geometry.polygon import LinearRing, Polygon
import shapely.affinity as affinity
from starr.misc import p... | 0.737442 | 0.592313 |
from unittest import mock
import pytest
from tulius.core.ckeditor import html_converter
from djfw.wysibb import models
from djfw.wysibb.templatetags import bbcodes
@pytest.mark.parametrize('data,value', [
[ # Check structure support
'aaa<b>d<some_tag>f</some_tag>f<s>fd</s>ff</b>bb',
'aaa[b]dff... | tests/test_html_converter.py | from unittest import mock
import pytest
from tulius.core.ckeditor import html_converter
from djfw.wysibb import models
from djfw.wysibb.templatetags import bbcodes
@pytest.mark.parametrize('data,value', [
[ # Check structure support
'aaa<b>d<some_tag>f</some_tag>f<s>fd</s>ff</b>bb',
'aaa[b]dff... | 0.671255 | 0.576482 |
__version__ = 2.1
__all__ = ['fatal_error', 'print_image', 'plot_image', 'color_palette', 'plot_colorbar', 'apply_mask', 'readimage',
'laplace_filter', 'sobel_filter', 'scharr_filter', 'hist_equalization', 'plot_hist', 'image_add',
'image_subtract', 'erode', 'dilate', 'watershed', 'rectangle_mask'... | plantcv/__init__.py | __version__ = 2.1
__all__ = ['fatal_error', 'print_image', 'plot_image', 'color_palette', 'plot_colorbar', 'apply_mask', 'readimage',
'laplace_filter', 'sobel_filter', 'scharr_filter', 'hist_equalization', 'plot_hist', 'image_add',
'image_subtract', 'erode', 'dilate', 'watershed', 'rectangle_mask'... | 0.678007 | 0.391929 |
def time_validation(time):
if ":" not in time:
return False, "Incorrect time format try hour:min"
hour = time.split(":")[0]
min = time.split(":")[1]
if int(hour) not in range(0, 24):
return False, "Incorrect hour format, hour must be between 0-23"
if int(min) not in range(0, 60):
... | SmartSleep/validation.py | def time_validation(time):
if ":" not in time:
return False, "Incorrect time format try hour:min"
hour = time.split(":")[0]
min = time.split(":")[1]
if int(hour) not in range(0, 24):
return False, "Incorrect hour format, hour must be between 0-23"
if int(min) not in range(0, 60):
... | 0.476092 | 0.24971 |
import sys, argparse
import socket
import serial
import json
import struct
import numpy as np
import time
import multiprocessing
import matplotlib
matplotlib.use('GTKAgg')
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figu... | apps/listener/scripts/listener_pdoa.py |
import sys, argparse
import socket
import serial
import json
import struct
import numpy as np
import time
import multiprocessing
import matplotlib
matplotlib.use('GTKAgg')
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figu... | 0.373533 | 0.15662 |
import shutil
import ipywidgets
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from ipywidgets import Button
from PIL import Image
from typing import List, Optional
from cocpit.auto_str import auto_str
import cocpit
plt_params = {
"axes.labelsize": "xx-large",
"axe... | cocpit/gui_wrong.py | import shutil
import ipywidgets
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from ipywidgets import Button
from PIL import Image
from typing import List, Optional
from cocpit.auto_str import auto_str
import cocpit
plt_params = {
"axes.labelsize": "xx-large",
"axe... | 0.810104 | 0.517937 |
import logging
from pathlib import Path
from typing import Any, Dict, List, Optional
import torch
from torch import Tensor
from fairseq import checkpoint_utils, utils
from fairseq.models import (
FairseqEncoderModel,
FairseqEncoderDecoderModel,
FairseqLanguageModel,
register_model,
register_model... | fairseq/models/speech_to_speech/s2s_transformer.py |
import logging
from pathlib import Path
from typing import Any, Dict, List, Optional
import torch
from torch import Tensor
from fairseq import checkpoint_utils, utils
from fairseq.models import (
FairseqEncoderModel,
FairseqEncoderDecoderModel,
FairseqLanguageModel,
register_model,
register_model... | 0.945889 | 0.218242 |
import logging
import socket
import time
import picamera
from platypush.backend import Backend
class CameraPiBackend(Backend):
def __init__(self, listen_port, x_resolution=640, y_resolution=480,
framerate=24, hflip=False, vflip=False,
sharpness=0, contrast=0, brightness=50,
... | platypush/backend/camera/pi.py | import logging
import socket
import time
import picamera
from platypush.backend import Backend
class CameraPiBackend(Backend):
def __init__(self, listen_port, x_resolution=640, y_resolution=480,
framerate=24, hflip=False, vflip=False,
sharpness=0, contrast=0, brightness=50,
... | 0.731251 | 0.118947 |
import random
from os.path import realpath
import aiohttp
from aiohttp import client_exceptions
class UnableToFetchCarbon(Exception):
pass
themes = [
"3024-night",
"a11y-dark",
"blackboard",
"base16-dark",
"base16-light",
"cobalt",
"duotone-dark",
"dracula-pro",
"hopscotch"... | YukkiMusic/platforms/Carbon.py |
import random
from os.path import realpath
import aiohttp
from aiohttp import client_exceptions
class UnableToFetchCarbon(Exception):
pass
themes = [
"3024-night",
"a11y-dark",
"blackboard",
"base16-dark",
"base16-light",
"cobalt",
"duotone-dark",
"dracula-pro",
"hopscotch"... | 0.36557 | 0.183283 |
import logging
from os import environ
import pandas as pd
import kaiko.utils as ut
try:
from cStringIO import StringIO # Python 2
except ImportError:
from io import StringIO
# Base URLs
_BASE_URL_KAIKO_US = 'https://us.market-api.kaiko.io/'
_BASE_URL_KAIKO_EU = 'https://eu.market-api.kaiko.io/'
_BASE_U... | kaiko/kaiko.py | import logging
from os import environ
import pandas as pd
import kaiko.utils as ut
try:
from cStringIO import StringIO # Python 2
except ImportError:
from io import StringIO
# Base URLs
_BASE_URL_KAIKO_US = 'https://us.market-api.kaiko.io/'
_BASE_URL_KAIKO_EU = 'https://eu.market-api.kaiko.io/'
_BASE_U... | 0.716814 | 0.191592 |
from baselayer.app.access import auth_or_token
from ..base import BaseHandler
from ...models import DBSession, Group, Photometry, Spectrum
class SharingHandler(BaseHandler):
@auth_or_token
def post(self):
"""
---
description: Share data with additional groups/users
requestBody:... | skyportal/handlers/api/sharing.py | from baselayer.app.access import auth_or_token
from ..base import BaseHandler
from ...models import DBSession, Group, Photometry, Spectrum
class SharingHandler(BaseHandler):
@auth_or_token
def post(self):
"""
---
description: Share data with additional groups/users
requestBody:... | 0.762778 | 0.292696 |
from sims4.gsi.dispatcher import GsiHandler
from sims4.gsi.schema import GsiGridSchema
import services
from venues.venue_service import VenueService
venue_game_schema = GsiGridSchema(label='Venue Game Service')
venue_game_schema.add_field('zone', label='Venue', width=1, unique_field=True)
venue_game_schema.add_field('v... | S4/S4 Library/simulation/venues/civic_policies/venue_civic_policy_handlers.py | from sims4.gsi.dispatcher import GsiHandler
from sims4.gsi.schema import GsiGridSchema
import services
from venues.venue_service import VenueService
venue_game_schema = GsiGridSchema(label='Venue Game Service')
venue_game_schema.add_field('zone', label='Venue', width=1, unique_field=True)
venue_game_schema.add_field('v... | 0.256646 | 0.118998 |