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 datetime import date, timedelta
import pytest
from isodate.duration import Duration
from ..interval import IntervalManager
def test_get_intervalled_forms(manager, create_forms, cleanup_db):
forms = manager.get_intervalled_forms()
assert len(forms) == 2
@pytest.mark.parametrize(
"value,exp_startda... | caluma_interval/tests/test_interval.py | from datetime import date, timedelta
import pytest
from isodate.duration import Duration
from ..interval import IntervalManager
def test_get_intervalled_forms(manager, create_forms, cleanup_db):
forms = manager.get_intervalled_forms()
assert len(forms) == 2
@pytest.mark.parametrize(
"value,exp_startda... | 0.710929 | 0.547162 |
"""Argument parser.
"""
import argparse
import typing
from .. import api
from . import constants, utils
DEFAULTS = dict(
loglevel=0, list=False, output=None, itype=None, otype=None, atype=None,
merge=api.MS_DICTS, ignore_missing=False, template=False, env=False,
schema=None, validate=False, gen_schema=Fa... | src/anyconfig/cli/parse_args.py | """Argument parser.
"""
import argparse
import typing
from .. import api
from . import constants, utils
DEFAULTS = dict(
loglevel=0, list=False, output=None, itype=None, otype=None, atype=None,
merge=api.MS_DICTS, ignore_missing=False, template=False, env=False,
schema=None, validate=False, gen_schema=Fa... | 0.629888 | 0.145996 |
import numpy as np
import sys
from sklearn.preprocessing import normalize
class Bee:
"""
A single bee, used in one run of the model.
A neat way of storing useful variables and methods for use by the main loop.
"""
def __init__(self, set_2013_probs):
"""
Matrix representing distances... | trapline_formation/singleBee.py | import numpy as np
import sys
from sklearn.preprocessing import normalize
class Bee:
"""
A single bee, used in one run of the model.
A neat way of storing useful variables and methods for use by the main loop.
"""
def __init__(self, set_2013_probs):
"""
Matrix representing distances... | 0.528047 | 0.603611 |
from __future__ import division, absolute_import, unicode_literals, print_function
import h5py
import numpy as np
from collections import Iterable
__all__ = ['flatten_complex_to_real', 'get_compound_sub_dtypes', 'flatten_compound_to_real', 'check_dtype',
'stack_real_to_complex', 'validate_dtype',
... | pycroscopy/core/io/dtype_utils.py | from __future__ import division, absolute_import, unicode_literals, print_function
import h5py
import numpy as np
from collections import Iterable
__all__ = ['flatten_complex_to_real', 'get_compound_sub_dtypes', 'flatten_compound_to_real', 'check_dtype',
'stack_real_to_complex', 'validate_dtype',
... | 0.782621 | 0.575767 |
from __future__ import annotations
from typing import Type, Any
class _InvalidCase:
"""Sentinel object for defining when a case is not met."""
_INVALID_CASE = _InvalidCase()
class _UndefinedEval:
"""Sentinel object for defining when a switch statement has not been evaluated yet."""
_UNDEFINED_EVAL = _Un... | switch/__init__.py | from __future__ import annotations
from typing import Type, Any
class _InvalidCase:
"""Sentinel object for defining when a case is not met."""
_INVALID_CASE = _InvalidCase()
class _UndefinedEval:
"""Sentinel object for defining when a switch statement has not been evaluated yet."""
_UNDEFINED_EVAL = _Un... | 0.932622 | 0.270003 |
from __future__ import print_function
import sys
import json
import regex
from tqdm import tqdm
from .filters import style
from .utils import clone_pull, execute_cmd, is_git_dir, utf8_decode
from .parser import parse_arguments
from .clients import render
def main(args=sys.argv[1:], render_results=True, skip_clone... | poirot/poirot.py |
from __future__ import print_function
import sys
import json
import regex
from tqdm import tqdm
from .filters import style
from .utils import clone_pull, execute_cmd, is_git_dir, utf8_decode
from .parser import parse_arguments
from .clients import render
def main(args=sys.argv[1:], render_results=True, skip_clone... | 0.397938 | 0.182462 |
PBPTonscreenText = 0.2
# battle/RewardPanel.py
RPdirectFrame = (1.75, 1, 0.75)
RPtrackLabels = 0.05
RPmeritBarLabels = 0.165
# battle/RewardPanel.py
RPmeritLabelXPosition = 0.55
RPmeritBarsXPosition = 0.825
# battle/BattleBase.py
BBbattleInputTimeout = 20.0
# battle/FireCogPanel.py
FCPtextFrameScale = 0.08
# build... | toontown/toonbase/TTLocalizerEnglishProperty.py | PBPTonscreenText = 0.2
# battle/RewardPanel.py
RPdirectFrame = (1.75, 1, 0.75)
RPtrackLabels = 0.05
RPmeritBarLabels = 0.165
# battle/RewardPanel.py
RPmeritLabelXPosition = 0.55
RPmeritBarsXPosition = 0.825
# battle/BattleBase.py
BBbattleInputTimeout = 20.0
# battle/FireCogPanel.py
FCPtextFrameScale = 0.08
# build... | 0.158044 | 0.164987 |
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import DataPlatForm.service_pb2 as service__pb2
class DACStub(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channe... | src/DataPlatForm/service_pb2_grpc.py | """Client and server classes corresponding to protobuf-defined services."""
import grpc
import DataPlatForm.service_pb2 as service__pb2
class DACStub(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channe... | 0.761627 | 0.099164 |
from bigo import questions as big_o
from binsearch import questions as bsearch
from binsearchtree import questions as bst
from graph import questions as graphs
from hashing import questions as hashing
from insertion import insertion_sort as isort
from quicksort import questions as qsort
from stringsearch import questio... | main.py | from bigo import questions as big_o
from binsearch import questions as bsearch
from binsearchtree import questions as bst
from graph import questions as graphs
from hashing import questions as hashing
from insertion import insertion_sort as isort
from quicksort import questions as qsort
from stringsearch import questio... | 0.273769 | 0.225257 |
from unittest import TestCase
import numpy as np
from scipy.sparse import csr_matrix
from amfe.solver.integrator import *
from numpy.testing import assert_allclose
import matplotlib.pyplot as plt
from amfe.linalg.linearsolvers import ScipySparseLinearSolver
def M(q, dq, t):
return 2 * csr_matrix(np.eye(4))
def ... | tests/test_integrator.py | from unittest import TestCase
import numpy as np
from scipy.sparse import csr_matrix
from amfe.solver.integrator import *
from numpy.testing import assert_allclose
import matplotlib.pyplot as plt
from amfe.linalg.linearsolvers import ScipySparseLinearSolver
def M(q, dq, t):
return 2 * csr_matrix(np.eye(4))
def ... | 0.729327 | 0.664903 |
import boto3
import time
import os
from hypchat import HypChat
# given how modules work with python it was easiest to use globals
# I know, I know
messages = []
hc_room = None
# yeah this is a mess and should have been fully static sometimes
# it is easier to just avoid side effects, you know?
class KLog(object):
... | lib/krampus_logging.py | import boto3
import time
import os
from hypchat import HypChat
# given how modules work with python it was easiest to use globals
# I know, I know
messages = []
hc_room = None
# yeah this is a mess and should have been fully static sometimes
# it is easier to just avoid side effects, you know?
class KLog(object):
... | 0.133698 | 0.169337 |
from collections import namedtuple
from prophyc.generators import base, word_wrap
INDENT_STR = u" "
MAX_LINE_WIDTH = 100
DocStr = namedtuple("DocStr", "block, inline")
def _form_doc(model_node, max_inl_docstring_len, indent_level):
block_doc, inline_doc = "", ""
if model_node.docstring:
if len(m... | prophyc/generators/prophy.py | from collections import namedtuple
from prophyc.generators import base, word_wrap
INDENT_STR = u" "
MAX_LINE_WIDTH = 100
DocStr = namedtuple("DocStr", "block, inline")
def _form_doc(model_node, max_inl_docstring_len, indent_level):
block_doc, inline_doc = "", ""
if model_node.docstring:
if len(m... | 0.584745 | 0.177704 |
import pytest
import numpy as np
import pandas as pd
from trees.RobustTree import RobustTreeClassifier
def test_RobustTree_X_noninteger_error():
"""Test whether X is integer-valued"""
clf = RobustTreeClassifier(depth=1, time_limit=20)
with pytest.raises(
ValueError,
match="Found non-int... | trees/tests/test_RobustTree.py | import pytest
import numpy as np
import pandas as pd
from trees.RobustTree import RobustTreeClassifier
def test_RobustTree_X_noninteger_error():
"""Test whether X is integer-valued"""
clf = RobustTreeClassifier(depth=1, time_limit=20)
with pytest.raises(
ValueError,
match="Found non-int... | 0.621656 | 0.741884 |
from __future__ import print_function
import os
import sys
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
from keras.layers import Dense, Input, GlobalMaxPooling1D
from keras.layers import Conv1D, MaxPoolin... | src/pretrained_word_embeddings.py | from __future__ import print_function
import os
import sys
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
from keras.layers import Dense, Input, GlobalMaxPooling1D
from keras.layers import Conv1D, MaxPoolin... | 0.575946 | 0.367327 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import math
from measurement_stats import value
class Angle(object):
"""A type for representing angular measurements with uncertainties"""
def __init__(self, ... | measurement_stats/angle.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import math
from measurement_stats import value
class Angle(object):
"""A type for representing angular measurements with uncertainties"""
def __init__(self, ... | 0.918809 | 0.428801 |
from collections import defaultdict
import math
from typing import Mapping, List, Union
import numpy as np
import tensorflow as tf
from neuromorphy.train.data_info import DataInfo
from neuromorphy.train.corpus_iterator import CorpusIterator
class BatchGenerator:
class Generator:
def __init__(self, gene... | neuromorphy/train/batch_generator.py |
from collections import defaultdict
import math
from typing import Mapping, List, Union
import numpy as np
import tensorflow as tf
from neuromorphy.train.data_info import DataInfo
from neuromorphy.train.corpus_iterator import CorpusIterator
class BatchGenerator:
class Generator:
def __init__(self, gene... | 0.882333 | 0.397588 |
from __future__ import absolute_import
import os
import re
import textwrap
from sybil import Region
from testfixtures import diff
FILEBLOCK_START = re.compile(r'^\.\.\s*topic::?\s*(.+)\b', re.MULTILINE)
FILEBLOCK_END = re.compile(r'(\n\Z|\n(?=\S))')
CLASS = re.compile(r'\s+:class:\s*(read|write)-file')
class FileB... | testfixtures/sybil.py | from __future__ import absolute_import
import os
import re
import textwrap
from sybil import Region
from testfixtures import diff
FILEBLOCK_START = re.compile(r'^\.\.\s*topic::?\s*(.+)\b', re.MULTILINE)
FILEBLOCK_END = re.compile(r'(\n\Z|\n(?=\S))')
CLASS = re.compile(r'\s+:class:\s*(read|write)-file')
class FileB... | 0.560493 | 0.128116 |
import sys
sys.path.append('../src/ptprobe')
import logging
import threading
import time
import argparse
import board
from sinks import InfluxDBSampleSink
import json
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
... | client/examples/read_to_influxdb.py | import sys
sys.path.append('../src/ptprobe')
import logging
import threading
import time
import argparse
import board
from sinks import InfluxDBSampleSink
import json
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
... | 0.263031 | 0.061509 |
from htm.bindings.algorithms import TemporalMemory
from htm.bindings.sdr import SDR
from htm.encoders.rdse import RDSE, RDSE_Parameters
import argparse
import itertools
import numpy as np
import random
import time
default_parameters = {
'num_cells': 2000,
'local_sparsity': .02,
'apical_denrites': {
... | main.py | from htm.bindings.algorithms import TemporalMemory
from htm.bindings.sdr import SDR
from htm.encoders.rdse import RDSE, RDSE_Parameters
import argparse
import itertools
import numpy as np
import random
import time
default_parameters = {
'num_cells': 2000,
'local_sparsity': .02,
'apical_denrites': {
... | 0.720467 | 0.266441 |
def lex_sexp(sexp_string: str):
"""
Tokenizes an s-expression string not containing comments.
Example: lex_sexp transforms the string " \n \t (a ( bc d) 1)" into the sequence
("(", "a", "(", "bc", "d", ")", "1", ")").
:param sexp_string: An s-expression string that does not contain comments.
... | cscl_examples/smt_qfbv_solver/sexp_parser.py | def lex_sexp(sexp_string: str):
"""
Tokenizes an s-expression string not containing comments.
Example: lex_sexp transforms the string " \n \t (a ( bc d) 1)" into the sequence
("(", "a", "(", "bc", "d", ")", "1", ")").
:param sexp_string: An s-expression string that does not contain comments.
... | 0.875255 | 0.613526 |
import sys
import glob
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import scipy
import imageio
import cv2
import pathlib
import skimage
import PIL
from PIL import Image
from interactive_crop import interactive_crop
def crop_datastack(exp_folde... | analysis_scripts/crop_datastack.py | import sys
import glob
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import scipy
import imageio
import cv2
import pathlib
import skimage
import PIL
from PIL import Image
from interactive_crop import interactive_crop
def crop_datastack(exp_folde... | 0.108862 | 0.213275 |
import sys, inspect
from core.config.enumerator import EnumeratationConfig
from core.recon.subenum.reverser.revip import *
from core.recon.subenum.sublist3r.sublist3r import *
class IDomainEnumerator:
def __init__(self, config: EnumeratationConfig) -> None:
self.config = config
self.domain = self.c... | core/recon/subenum/enumerator.py | import sys, inspect
from core.config.enumerator import EnumeratationConfig
from core.recon.subenum.reverser.revip import *
from core.recon.subenum.sublist3r.sublist3r import *
class IDomainEnumerator:
def __init__(self, config: EnumeratationConfig) -> None:
self.config = config
self.domain = self.c... | 0.235548 | 0.065336 |
from __future__ import annotations
import json
from typing import List
from .exceptions import MaterialExists, MaterialNotFound
class MaterialMeta(type):
"""Material metaclass."""
@property
def all(cls) -> List["Material"]:
"""Return list of all materials registered."""
return list(cls.... | fdtd/materials.py | from __future__ import annotations
import json
from typing import List
from .exceptions import MaterialExists, MaterialNotFound
class MaterialMeta(type):
"""Material metaclass."""
@property
def all(cls) -> List["Material"]:
"""Return list of all materials registered."""
return list(cls.... | 0.946448 | 0.196575 |
import socket
from odoo.addons.test_mail.data.test_mail_data import MAIL_TEMPLATE
from odoo.addons.test_mail.tests.test_mail_gateway import TestMailgateway
from odoo.tools import mute_logger
from email.utils import formataddr
class TestFetchmailNotifyErrorToSender(TestMailgateway):
def setUp(self):
supe... | addons/fetchmail_notify_error_to_sender/tests/test_fetchmail_notify_error_to_sender.py |
import socket
from odoo.addons.test_mail.data.test_mail_data import MAIL_TEMPLATE
from odoo.addons.test_mail.tests.test_mail_gateway import TestMailgateway
from odoo.tools import mute_logger
from email.utils import formataddr
class TestFetchmailNotifyErrorToSender(TestMailgateway):
def setUp(self):
supe... | 0.360489 | 0.167695 |
from analyzer import StockAnalyzer
from stock import Stock
from bs4 import BeautifulSoup
import pandas as panda
import yfinance as yf
import requests
import re
import datetime
import os
import openpyxl
import argparse
class StockScanner:
def __init__(self):
self.winner_stock_list = list()
self.... | src/main.py | from analyzer import StockAnalyzer
from stock import Stock
from bs4 import BeautifulSoup
import pandas as panda
import yfinance as yf
import requests
import re
import datetime
import os
import openpyxl
import argparse
class StockScanner:
def __init__(self):
self.winner_stock_list = list()
self.... | 0.307878 | 0.151153 |
import gym
from gym.utils import seeding
import numpy as np
import logging
logger = logging.getLogger(__name__)
class Example_v0(gym.Env):
LF_MIN = 1
RT_MAX = 10
MOVE_LF = 0
MOVE_RT = 1
MAX_STEPS = 10
REWARD_AWAY = -2
REWARD_STEP = -1
REWARD_GOAL = MAX_STEPS
metadata = {
"render.modes": ["human"]
}
def ... | environments/gym_env_example.py | import gym
from gym.utils import seeding
import numpy as np
import logging
logger = logging.getLogger(__name__)
class Example_v0(gym.Env):
LF_MIN = 1
RT_MAX = 10
MOVE_LF = 0
MOVE_RT = 1
MAX_STEPS = 10
REWARD_AWAY = -2
REWARD_STEP = -1
REWARD_GOAL = MAX_STEPS
metadata = {
"render.modes": ["human"]
}
def ... | 0.585457 | 0.167253 |
from collections import namedtuple
'''
This module contains namedtuples that store the necessary parameters for the
real-case tests. Some tuples like as db_params could have also be used as
fixtures. However, to avoid the confusion of using some of parameters as
fixtures and some as namedtuple, all the necessary p... | tests/integration_tests/utils/parameters.py | from collections import namedtuple
'''
This module contains namedtuples that store the necessary parameters for the
real-case tests. Some tuples like as db_params could have also be used as
fixtures. However, to avoid the confusion of using some of parameters as
fixtures and some as namedtuple, all the necessary p... | 0.714528 | 0.335514 |
import time
import socket
import struct
import threading
import numpy as np
class BaseReadData(object):
def __init__(self, ip_address='172.16.31.10', sample_rate=1000, buffer_time=30, end_flag_trial=33):
self.collecting = False
self.data = []
self.CHANNELS = [
'FP... | TCPServer/neuroScanClient.py | import time
import socket
import struct
import threading
import numpy as np
class BaseReadData(object):
def __init__(self, ip_address='172.16.31.10', sample_rate=1000, buffer_time=30, end_flag_trial=33):
self.collecting = False
self.data = []
self.CHANNELS = [
'FP... | 0.219756 | 0.14682 |
import re
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from douban_spider.items import DoubanSpiderItem
class DoubanSpider(CrawlSpider):
name = 'douban'
allowed_domains = ['douban.com']
start_urls = ['https://movie.douban.com/top250']
rul... | spider_project/douban_spider/douban_spider/spiders/douban.py | import re
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from douban_spider.items import DoubanSpiderItem
class DoubanSpider(CrawlSpider):
name = 'douban'
allowed_domains = ['douban.com']
start_urls = ['https://movie.douban.com/top250']
rul... | 0.233095 | 0.082033 |
import logging
from rest_framework import generics
from rest_framework.response import Response
from rest_framework import status
from django.shortcuts import get_object_or_404
from cajas.api.CsrfExempt import CsrfExemptSessionAuthentication
from cajas.concepts.models.concepts import Concept
from cajas.inventory.mod... | cajas/movement/api/views/movement_daily_square/update_movement.py | import logging
from rest_framework import generics
from rest_framework.response import Response
from rest_framework import status
from django.shortcuts import get_object_or_404
from cajas.api.CsrfExempt import CsrfExemptSessionAuthentication
from cajas.concepts.models.concepts import Concept
from cajas.inventory.mod... | 0.382257 | 0.102529 |
def write_todo(open_file, todo):
line = ' - ' + todo + '\n'
open_file.write(line)
def write_todos_for_module(open_file, todo_list):
for todo in todo_list:
write_todo(open_file, todo)
def write_newline(open_file):
open_file.write('\n')
def format_as_details(open_file, todo_list)... | todos/aggregate_todos.py |
def write_todo(open_file, todo):
line = ' - ' + todo + '\n'
open_file.write(line)
def write_todos_for_module(open_file, todo_list):
for todo in todo_list:
write_todo(open_file, todo)
def write_newline(open_file):
open_file.write('\n')
def format_as_details(open_file, todo_list)... | 0.177063 | 0.144752 |
from django.conf import settings
from mighty.functions import make_searchable
from company.backends.search import SearchBackend
from company.choices.fr import LEGALFORM, APE
from io import BytesIO
import base64, pycurl, json, re, logging, time, datetime
logger = logging.getLogger(__name__)
class SearchBackend(Searc... | backends/search/insee.py | from django.conf import settings
from mighty.functions import make_searchable
from company.backends.search import SearchBackend
from company.choices.fr import LEGALFORM, APE
from io import BytesIO
import base64, pycurl, json, re, logging, time, datetime
logger = logging.getLogger(__name__)
class SearchBackend(Searc... | 0.187765 | 0.095518 |
import numpy as np
import json, pickle
out_dir = '../sample_output/pickles/'
def feature_vector(density_symmetry, roughness_max, roughness_symmetry, filename):
# print(density_symmetry, roughness_max, roughness_symmetry)
arr = np.append(density_symmetry, roughness_max, axis = 0)
arr = np.append(arr, roughness_sym... | scripts/save_features.py |
import numpy as np
import json, pickle
out_dir = '../sample_output/pickles/'
def feature_vector(density_symmetry, roughness_max, roughness_symmetry, filename):
# print(density_symmetry, roughness_max, roughness_symmetry)
arr = np.append(density_symmetry, roughness_max, axis = 0)
arr = np.append(arr, roughness_sym... | 0.093949 | 0.27648 |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... | main/migrations/0001_initial.py | from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... | 0.583441 | 0.138491 |
from __future__ import print_function
from unicorn import *
from unicorn.arm_const import *
# code to be emulated
ARM_CODE = b"\xe3\xa0\x00\x37\xe0\x42\x10\x03" # mov r0, #0x37; sub r1, r2, r3
THUMB_CODE = b"\xb0\x83" # sub sp, #0xc
# memory address where emulation starts
ADDRESS = 0x10000
# callback for t... | unicorn/bindings/python/sample_armeb.py |
from __future__ import print_function
from unicorn import *
from unicorn.arm_const import *
# code to be emulated
ARM_CODE = b"\xe3\xa0\x00\x37\xe0\x42\x10\x03" # mov r0, #0x37; sub r1, r2, r3
THUMB_CODE = b"\xb0\x83" # sub sp, #0xc
# memory address where emulation starts
ADDRESS = 0x10000
# callback for t... | 0.569853 | 0.280296 |
import argparse
import os
import re
def report_coverage_summary(refs, ofile_path):
ofh = open(ofile_path, 'w')
ofh.write("ref_id\tuncovered_bases\tref_length\n")
for ref in refs:
last_pos = 0
c_uncovered = 0
mol_length = refs[ref]['length']
for range in refs[ref]['ra... | sandbox/jorvis/nucmer_genome_coverage_summary.py |
import argparse
import os
import re
def report_coverage_summary(refs, ofile_path):
ofh = open(ofile_path, 'w')
ofh.write("ref_id\tuncovered_bases\tref_length\n")
for ref in refs:
last_pos = 0
c_uncovered = 0
mol_length = refs[ref]['length']
for range in refs[ref]['ra... | 0.340705 | 0.376938 |
import uuid
from typing import Any, Callable, List, Optional
import structlog
from flask import Flask, jsonify
from flask_injector import FlaskInjector
from flask_migrate import Migrate
from flask_restx import Api
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from sqlalchemy import MetaData... | src/mitre/securingai/restapi/app.py | import uuid
from typing import Any, Callable, List, Optional
import structlog
from flask import Flask, jsonify
from flask_injector import FlaskInjector
from flask_migrate import Migrate
from flask_restx import Api
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from sqlalchemy import MetaData... | 0.852905 | 0.139924 |
from __future__ import absolute_import, print_function
import os
import sys
import time
import signal
import locale
import unittest
import pyuv
import gruvi
from gruvi.hub import get_hub
from gruvi.errors import Timeout
from gruvi.process import Process, PIPE, DEVNULL
from gruvi.stream import StreamClient
from supp... | tests/test_process.py |
from __future__ import absolute_import, print_function
import os
import sys
import time
import signal
import locale
import unittest
import pyuv
import gruvi
from gruvi.hub import get_hub
from gruvi.errors import Timeout
from gruvi.process import Process, PIPE, DEVNULL
from gruvi.stream import StreamClient
from supp... | 0.52756 | 0.313105 |
# Import libraries
import os
from docopt import docopt
import pandas as pd
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import (
OneHotEncoder,
StandardScaler
)
from skl... | src/ml_model.py | # Import libraries
import os
from docopt import docopt
import pandas as pd
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import (
OneHotEncoder,
StandardScaler
)
from skl... | 0.794624 | 0.428652 |
import json
import urllib.parse
from json import JSONDecodeError
import requests_cache as requests
from neon_utils.logger import LOG
from requests.adapters import HTTPAdapter
from . import AUTH_CONFIG, NeonAPI, request_neon_api
SESSION = requests.CachedSession(backend='memory', cache_name="alpha_vantage")
SESSION.m... | neon_utils/service_apis/alpha_vantage.py |
import json
import urllib.parse
from json import JSONDecodeError
import requests_cache as requests
from neon_utils.logger import LOG
from requests.adapters import HTTPAdapter
from . import AUTH_CONFIG, NeonAPI, request_neon_api
SESSION = requests.CachedSession(backend='memory', cache_name="alpha_vantage")
SESSION.m... | 0.494873 | 0.187932 |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User,Group
from registration.serializers import UserSerializer
from profBasic.models import profBasic
from pr... | registration/views.py | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User,Group
from registration.serializers import UserSerializer
from profBasic.models import profBasic
from pr... | 0.672009 | 0.091626 |
tz_str = None
sep = ' -- '
testFunctions = True
import datetime as dt
class time:
def now(tz_str):
tz_now = dt.datetime.now(tz_str)
return tz_now
def timestamp():
rightnow = time.now(tz_str)
stamp = str(rightnow)# + ' // TZ: ' + str(tz_str)
return stamp
class logger:
sep = ':'
def println... | helper_functions.py | tz_str = None
sep = ' -- '
testFunctions = True
import datetime as dt
class time:
def now(tz_str):
tz_now = dt.datetime.now(tz_str)
return tz_now
def timestamp():
rightnow = time.now(tz_str)
stamp = str(rightnow)# + ' // TZ: ' + str(tz_str)
return stamp
class logger:
sep = ':'
def println... | 0.343232 | 0.143128 |
from conans.assets.templates.new_v2_cmake import source_cpp, source_h, test_main
conanfile_sources_v2 = """
import os
from conan import ConanFile
from conan.tools.google import Bazel, bazel_layout
from conan.tools.files import copy
class {package_name}Conan(ConanFile):
name = "{name}"
version = "{version}"
... | conans/assets/templates/new_v2_bazel.py | from conans.assets.templates.new_v2_cmake import source_cpp, source_h, test_main
conanfile_sources_v2 = """
import os
from conan import ConanFile
from conan.tools.google import Bazel, bazel_layout
from conan.tools.files import copy
class {package_name}Conan(ConanFile):
name = "{name}"
version = "{version}"
... | 0.416678 | 0.141786 |
import asyncio
from asyncio.tasks import sleep
import websockets
import json
import constants
import time
SERVER_URL = 'ws://localhost:8765'
LOGIN_REQUEST = {
"request_data": "ValueToBeReturnedInResponse",
"md_login_request":
{
"login_id": constants.LOGIN_ID,
"password": <PASSWORD>,
... | consumer.py |
import asyncio
from asyncio.tasks import sleep
import websockets
import json
import constants
import time
SERVER_URL = 'ws://localhost:8765'
LOGIN_REQUEST = {
"request_data": "ValueToBeReturnedInResponse",
"md_login_request":
{
"login_id": constants.LOGIN_ID,
"password": <PASSWORD>,
... | 0.160628 | 0.120775 |
from __future__ import annotations
from typing import Optional, Type
import jax
import jax.numpy as jnp
from tjax import Generator, RealArray, Shape
from tjax.dataclasses import dataclass
from ..expectation_parametrization import ExpectationParametrization
from ..natural_parametrization import NaturalParametrization... | efax/_src/distributions/weibull.py | from __future__ import annotations
from typing import Optional, Type
import jax
import jax.numpy as jnp
from tjax import Generator, RealArray, Shape
from tjax.dataclasses import dataclass
from ..expectation_parametrization import ExpectationParametrization
from ..natural_parametrization import NaturalParametrization... | 0.889876 | 0.451327 |
import base64
import collections
import hashlib
import random
import struct
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from httplite import HTTPResponse
__all__ = ["WebSocket", "SingleOptionPolicy", "UnrestrictedPolicy"]
def split_field(s):
retu... | Telemetry/websocket.py | import base64
import collections
import hashlib
import random
import struct
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from httplite import HTTPResponse
__all__ = ["WebSocket", "SingleOptionPolicy", "UnrestrictedPolicy"]
def split_field(s):
retu... | 0.433022 | 0.064065 |
import datetime
import json
import logging
import os
from django.conf import settings
from django.http import HttpResponseForbidden, HttpResponse
from django.shortcuts import render, redirect
from django.views.generic import DetailView, ListView
from websocket import create_connection
from websocket._exceptions import... | events/views.py | import datetime
import json
import logging
import os
from django.conf import settings
from django.http import HttpResponseForbidden, HttpResponse
from django.shortcuts import render, redirect
from django.views.generic import DetailView, ListView
from websocket import create_connection
from websocket._exceptions import... | 0.311636 | 0.06165 |
import sys
import mock
import keiko.app
class TestApp(object):
"""Smoke test only."""
def setup(self):
keiko.app.app.keiko = mock.MagicMock()
keiko.app.jsonify = mock.MagicMock(return_value='')
self.app = keiko.app.app.test_client()
def test_index(self):
assert self.app... | tests/test_app.py | import sys
import mock
import keiko.app
class TestApp(object):
"""Smoke test only."""
def setup(self):
keiko.app.app.keiko = mock.MagicMock()
keiko.app.jsonify = mock.MagicMock(return_value='')
self.app = keiko.app.app.test_client()
def test_index(self):
assert self.app... | 0.410402 | 0.311689 |
class acc:
"""加速度を扱います。"""
TANNI = {"m/s2": 1, "km/h/s": 0.27777777, "ft/h/s": 0.00008466666666, "in/min/s": 0.000423333333, "ft/min/s": 0.00508, "Gal": 0.01,
"in/s2": 0.0254, "ft/s2": 0.3048, "mi/h/s": 0.44704, "kn/s": 0.5144444, "g": 9.80665, "mi/min/s": 26.8224, "mi/s2": 1609.344}
def ... | Python/unit_change.py | class acc:
"""加速度を扱います。"""
TANNI = {"m/s2": 1, "km/h/s": 0.27777777, "ft/h/s": 0.00008466666666, "in/min/s": 0.000423333333, "ft/min/s": 0.00508, "Gal": 0.01,
"in/s2": 0.0254, "ft/s2": 0.3048, "mi/h/s": 0.44704, "kn/s": 0.5144444, "g": 9.80665, "mi/min/s": 26.8224, "mi/s2": 1609.344}
def ... | 0.390825 | 0.513668 |
from opqua.model import Model
model = Model()
model.newSetup('setup_normal', preset='vector-borne')
model.newSetup(
'setup_cluster',
contact_rate_host_vector = ( 2 *
model.setups['setup_normal'].contact_rate_host_vector ),
preset='vector-borne'
) # uses default parameters but doubles contact ra... | examples/tutorials/metapopulations/metapopulations_migration_example.py | from opqua.model import Model
model = Model()
model.newSetup('setup_normal', preset='vector-borne')
model.newSetup(
'setup_cluster',
contact_rate_host_vector = ( 2 *
model.setups['setup_normal'].contact_rate_host_vector ),
preset='vector-borne'
) # uses default parameters but doubles contact ra... | 0.637369 | 0.478102 |
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from organization.models import Organization
from squac.test_mixins import sample_user, create_group
'''Tests for org models:
*Org
to run only the app tests:
/mg.sh "t... | app/organization/tests/test_organization_api.py | from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from organization.models import Organization
from squac.test_mixins import sample_user, create_group
'''Tests for org models:
*Org
to run only the app tests:
/mg.sh "t... | 0.360602 | 0.281529 |
from PIL import Image
import numpy as np
from os import path
from json import load
import random
class bingoCard:
def __init__(self,background="map_background.png",save="overlay.png",icons="icons"):
self.card = Image.open(background)
self.card = self.card.convert("RGBA")
self.location=save
... | bingoCard.py | from PIL import Image
import numpy as np
from os import path
from json import load
import random
class bingoCard:
def __init__(self,background="map_background.png",save="overlay.png",icons="icons"):
self.card = Image.open(background)
self.card = self.card.convert("RGBA")
self.location=save
... | 0.14137 | 0.123603 |
import sys
import os
import argparse
import traceback
from disk import mount_point
from mod import set_self_dir, run_shell, run_shell_input
'''
How to build VMbox image?
VBoxManage internalcommands createrawvmdk -filename run/image/disk.vmdk -rawdisk run/image/disk.img
'''
# set ovmf_path if boot from UEFI
ovmf_path... | util/run.py | import sys
import os
import argparse
import traceback
from disk import mount_point
from mod import set_self_dir, run_shell, run_shell_input
'''
How to build VMbox image?
VBoxManage internalcommands createrawvmdk -filename run/image/disk.vmdk -rawdisk run/image/disk.img
'''
# set ovmf_path if boot from UEFI
ovmf_path... | 0.079896 | 0.05621 |
from hrmachine import Machine, Letter
from hrmachine.utils import string_to_values
def test_string_to_values():
expected = [Letter.P, Letter.Y, Letter.T, Letter.H, Letter.O, Letter.N]
assert string_to_values('python') == expected
expected = [Letter.L, Letter.I, Letter.N, Letter.U, Letter.X, 0]
assert... | tests.py | from hrmachine import Machine, Letter
from hrmachine.utils import string_to_values
def test_string_to_values():
expected = [Letter.P, Letter.Y, Letter.T, Letter.H, Letter.O, Letter.N]
assert string_to_values('python') == expected
expected = [Letter.L, Letter.I, Letter.N, Letter.U, Letter.X, 0]
assert... | 0.693577 | 0.792103 |
import padog
import PA_STABLIZE
from math import pi,tan
x1=0;x2=0;x3=0;x4=0;y1=0;y2=0;y3=0;y4=0
def pit_cause_cg_adjust(sita,h,Kp):
result=round((h*tan((sita)*Kp)),2)
return result
def foward_cg_stab(r1,r4,r2,r3,gait_need,enable):
if enable==True and (abs(r1)+abs(r4)+abs(r2)+abs(r3))!=0: # When Key_stap set T... | Py Apple Dynamics V7.3 SRC/PA-Dynamics V7.3/PA_GAIT.py | import padog
import PA_STABLIZE
from math import pi,tan
x1=0;x2=0;x3=0;x4=0;y1=0;y2=0;y3=0;y4=0
def pit_cause_cg_adjust(sita,h,Kp):
result=round((h*tan((sita)*Kp)),2)
return result
def foward_cg_stab(r1,r4,r2,r3,gait_need,enable):
if enable==True and (abs(r1)+abs(r4)+abs(r2)+abs(r3))!=0: # When Key_stap set T... | 0.172939 | 0.136033 |
import argparse
import girder_worker
import os
import sys
def get_config(section, option):
return girder_worker.config.get(section, option)
def set_config(section, option, value):
if not girder_worker.config.has_section(section):
girder_worker.config.add_section(section)
girder_worker.config.set... | packages/girder_worker/girder_worker/configure.py | import argparse
import girder_worker
import os
import sys
def get_config(section, option):
return girder_worker.config.get(section, option)
def set_config(section, option, value):
if not girder_worker.config.has_section(section):
girder_worker.config.add_section(section)
girder_worker.config.set... | 0.263884 | 0.063337 |
import logging
from rest_framework import serializers
from . import models
from recipients.models import Recipient
logger = logging.getLogger('adoptions')
class AdoptionSerializer(serializers.ModelSerializer):
status = serializers.CharField(read_only=True)
status_set_at = serializers.DateTimeField(read_only... | server/adoptions/serializers.py | import logging
from rest_framework import serializers
from . import models
from recipients.models import Recipient
logger = logging.getLogger('adoptions')
class AdoptionSerializer(serializers.ModelSerializer):
status = serializers.CharField(read_only=True)
status_set_at = serializers.DateTimeField(read_only... | 0.47171 | 0.177419 |
import pathlib
import matplotlib.pyplot as plt
import numpy as np
np.set_printoptions(suppress=True)
PATH_HERE = pathlib.Path(__file__).parent.resolve()
CSV_PATH = PATH_HERE.joinpath("../../data/norm_1000_12_34.csv").resolve()
CSV_VALUES = np.loadtxt(CSV_PATH)
print(f"Loaded {len(CSV_VALUES)} values from {CSV_PATH}")
p... | dev/python/histogram/hist.py | import pathlib
import matplotlib.pyplot as plt
import numpy as np
np.set_printoptions(suppress=True)
PATH_HERE = pathlib.Path(__file__).parent.resolve()
CSV_PATH = PATH_HERE.joinpath("../../data/norm_1000_12_34.csv").resolve()
CSV_VALUES = np.loadtxt(CSV_PATH)
print(f"Loaded {len(CSV_VALUES)} values from {CSV_PATH}")
p... | 0.589362 | 0.485844 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Courses',
fields=[
('id', models.AutoField(auto_created=Tr... | rate/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Courses',
fields=[
('id', models.AutoField(auto_created=Tr... | 0.579281 | 0.144511 |
import asyncio
import itertools
import threading
import time
import rclpy
from rclpy.callback_groups import ReentrantCallbackGroup
from rclpy.executors import SingleThreadedExecutor
from rclpy.node import Node
from std_srvs.srv import SetBool
import asyncx
import asyncx_ros2
_thread = asyncx.EventLoopThread()
SERVIC... | examples/ros2/service.py | import asyncio
import itertools
import threading
import time
import rclpy
from rclpy.callback_groups import ReentrantCallbackGroup
from rclpy.executors import SingleThreadedExecutor
from rclpy.node import Node
from std_srvs.srv import SetBool
import asyncx
import asyncx_ros2
_thread = asyncx.EventLoopThread()
SERVIC... | 0.390476 | 0.100879 |
import pytest
import time
import random
from endpoints.stores import ReadStoreError
from services import service_factories
from tools import tools
from endpoints.tests.emulators import (
DSMR_Emulator,
Fronius_Emulator
)
from services.strategies.basic import Log_Strategy
from services.events import Periodic... | services/tests/logger_fixtures.py | import pytest
import time
import random
from endpoints.stores import ReadStoreError
from services import service_factories
from tools import tools
from endpoints.tests.emulators import (
DSMR_Emulator,
Fronius_Emulator
)
from services.strategies.basic import Log_Strategy
from services.events import Periodic... | 0.242385 | 0.123524 |
import tempfile
import subprocess
class Visualizer(object):
"""
An abstract class to visualize Armor containers using graphviz.
"""
def __init__(self, digraph):
self._digraph = digraph
def _write_dot_nodes(self, key_mapper_inverse):
raise NotImplementedError()
def _write_dot_... | debug/python/rmr/visualizers.py | import tempfile
import subprocess
class Visualizer(object):
"""
An abstract class to visualize Armor containers using graphviz.
"""
def __init__(self, digraph):
self._digraph = digraph
def _write_dot_nodes(self, key_mapper_inverse):
raise NotImplementedError()
def _write_dot_... | 0.606964 | 0.324369 |
import os
import sys
from subprocess import Popen, PIPE
import paramiko
import rospy
from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue
class IwConfigParser():
def __init__(self, interface):
self.interface = interface
self.norm = ""
self.essid = ""
self.m... | python-checker/Examples/FULL/cob_monitoring/src/wlan_monitor.py |
import os
import sys
from subprocess import Popen, PIPE
import paramiko
import rospy
from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue
class IwConfigParser():
def __init__(self, interface):
self.interface = interface
self.norm = ""
self.essid = ""
self.m... | 0.291787 | 0.125627 |
import unittest
from amonone.web.template import *
from nose.tools import eq_
class TestTemplateFilters(unittest.TestCase):
def test_dateformat(self):
date = dateformat(1319737106)
eq_('27-10-2011-17:38', date)
def test_timeformat(self):
time = timeformat(1319737106)
eq_('17:38', time)
def test_date_to_... | amonone/web/apps/core/tests/template_filters_test.py | import unittest
from amonone.web.template import *
from nose.tools import eq_
class TestTemplateFilters(unittest.TestCase):
def test_dateformat(self):
date = dateformat(1319737106)
eq_('27-10-2011-17:38', date)
def test_timeformat(self):
time = timeformat(1319737106)
eq_('17:38', time)
def test_date_to_... | 0.239883 | 0.153296 |
from django.db import connection
from core.libs.cache import setCacheData
from core.libs.sqlcustom import fix_lob
from core.schedresource.utils import get_object_stores
import core.constants as const
def objectstore_summary_data(hours):
sqlRequest = """
SELECT JOBSTATUS, COUNT(JOBSTATUS) as COUNTJOBSINSTAT... | core/pandajob/summary_os.py | from django.db import connection
from core.libs.cache import setCacheData
from core.libs.sqlcustom import fix_lob
from core.schedresource.utils import get_object_stores
import core.constants as const
def objectstore_summary_data(hours):
sqlRequest = """
SELECT JOBSTATUS, COUNT(JOBSTATUS) as COUNTJOBSINSTAT... | 0.19129 | 0.130645 |
def big2little(string):
array = string.split(',')
for i in range(len(array) // 2):
array[2 * i], array[2 * i + 1] = array[2 * i + 1], array[2 * i]
return ','.join(array)
def rgb888to565(r, g, b):
return ((r & 0b11111000) << 8) | ((g & 0b11111100) << 3) | (b >> 3)
def rgb888to565(rgb):... | converter.py | def big2little(string):
array = string.split(',')
for i in range(len(array) // 2):
array[2 * i], array[2 * i + 1] = array[2 * i + 1], array[2 * i]
return ','.join(array)
def rgb888to565(r, g, b):
return ((r & 0b11111000) << 8) | ((g & 0b11111100) << 3) | (b >> 3)
def rgb888to565(rgb):... | 0.296451 | 0.506469 |
from __future__ import absolute_import, division, print_function
from unittest import TestCase
from marshmallow import ValidationError
from tests.utils import assert_equal_dict
from polyaxon_schemas.ops.environments.legacy import TFRunConfig
from polyaxon_schemas.ops.environments.resources import (
K8SResourcesC... | tests/test_ops/test_environments/test_experiments.py | from __future__ import absolute_import, division, print_function
from unittest import TestCase
from marshmallow import ValidationError
from tests.utils import assert_equal_dict
from polyaxon_schemas.ops.environments.legacy import TFRunConfig
from polyaxon_schemas.ops.environments.resources import (
K8SResourcesC... | 0.711531 | 0.376394 |
import subprocess
import signal
import os
class CliHandler:
def __init__(self):
self.process = {}
self.returncode = {}
def call(self, name, cmd, shell=True):
"""
this function is used to spawn new subprocess
if this function is called with same name more tha... | clihandler/clihandler.py | import subprocess
import signal
import os
class CliHandler:
def __init__(self):
self.process = {}
self.returncode = {}
def call(self, name, cmd, shell=True):
"""
this function is used to spawn new subprocess
if this function is called with same name more tha... | 0.416915 | 0.091139 |
import pytest
from astropy import units as u
import numpy as np
from xrtpy.response.channel import Channel
import pkg_resources
import sunpy
import sunpy.map
from sunpy.data import manager
import scipy.io
import sunpy.io.special
channel_names = [
"Al-mesh",
"Al-poly",
"C-poly",
"Ti-poly",
"Be-thin"... | xrtpy/response/tests/test_channel.py | import pytest
from astropy import units as u
import numpy as np
from xrtpy.response.channel import Channel
import pkg_resources
import sunpy
import sunpy.map
from sunpy.data import manager
import scipy.io
import sunpy.io.special
channel_names = [
"Al-mesh",
"Al-poly",
"C-poly",
"Ti-poly",
"Be-thin"... | 0.638159 | 0.447098 |
# template file: justice_py_sdk_codegen/__main__.py
"""Auto-generated package that contains models used by the Justice Matchmaking Service."""
__version__ = "2.15.1"
__author__ = "AccelByte"
__email__ = "<EMAIL>"
# pylint: disable=line-too-long
from ._matchmaking import add_user_into_session_in_channel
from ._matc... | accelbyte_py_sdk/api/matchmaking/wrappers/__init__.py |
# template file: justice_py_sdk_codegen/__main__.py
"""Auto-generated package that contains models used by the Justice Matchmaking Service."""
__version__ = "2.15.1"
__author__ = "AccelByte"
__email__ = "<EMAIL>"
# pylint: disable=line-too-long
from ._matchmaking import add_user_into_session_in_channel
from ._matc... | 0.508788 | 0.037047 |
from unittest import TestCase
from datetime import date
from app.domain.model import (
Currency,
Category,
Account,
Operation
)
class TestAccount(TestCase):
def test_hashes_must_be_identical(self):
account = Account("abc", Currency.EUR, [])
self.assertEqual(hash(account), h... | tirelire-account/tests/unit/tests_account.py | from unittest import TestCase
from datetime import date
from app.domain.model import (
Currency,
Category,
Account,
Operation
)
class TestAccount(TestCase):
def test_hashes_must_be_identical(self):
account = Account("abc", Currency.EUR, [])
self.assertEqual(hash(account), h... | 0.760917 | 0.45944 |
"""Implements user interface."""
import os
import argparse
from six.moves import input, configparser
from . import core
def _exp_path(path):
return os.path.abspath(os.path.expanduser(path))
if __name__ == '__main__':
# check config for hanger
config = configparser.RawConfigParser()
dot = os.path.join... | jetpack/ui.py | """Implements user interface."""
import os
import argparse
from six.moves import input, configparser
from . import core
def _exp_path(path):
return os.path.abspath(os.path.expanduser(path))
if __name__ == '__main__':
# check config for hanger
config = configparser.RawConfigParser()
dot = os.path.join... | 0.452536 | 0.0704 |
__version__ = "0.1.0"
import os
from datetime import date, datetime, timedelta
import connexion
from flask.templating import render_template
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
# @connex_app.route("/api/v1.0/precipitation")
def precipitation():
db.create_all()
pre... | app_refactored.py | __version__ = "0.1.0"
import os
from datetime import date, datetime, timedelta
import connexion
from flask.templating import render_template
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
# @connex_app.route("/api/v1.0/precipitation")
def precipitation():
db.create_all()
pre... | 0.419767 | 0.090494 |
"""Function implementation"""
import datetime
import logging
from resilient_lib import validate_fields, RequestsCommon
from fn_create_webex_meeting.lib.cisco_api import WebexAPI
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
log.addHandler(logging.StreamHandler())
PACKAGE_NAME = "fn_create_webex_meeting... | fn_create_webex_meeting/fn_create_webex_meeting/util/selftest.py | """Function implementation"""
import datetime
import logging
from resilient_lib import validate_fields, RequestsCommon
from fn_create_webex_meeting.lib.cisco_api import WebexAPI
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
log.addHandler(logging.StreamHandler())
PACKAGE_NAME = "fn_create_webex_meeting... | 0.41182 | 0.164047 |
from django.db import models
# Create your models here.
class MainModel(models.Model):
title = models.CharField('title', db_column='title', max_length=32, null=False, blank=False)
subtitle = models.CharField('subtitle', db_column='subtitle', max_length=128, null=False, blank=False)
class Meta:
ma... | demo/models.py | from django.db import models
# Create your models here.
class MainModel(models.Model):
title = models.CharField('title', db_column='title', max_length=32, null=False, blank=False)
subtitle = models.CharField('subtitle', db_column='subtitle', max_length=128, null=False, blank=False)
class Meta:
ma... | 0.605566 | 0.058158 |
from functools import lru_cache
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models.constants import LOOKUP_SEP
from treebeard.mp_tree import MP_Node
from wagtail.core import hooks
from wagtail.core.models import Page
from .field_adapters import adapter_registry
fr... | wagtail_transfer/serializers.py | from functools import lru_cache
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models.constants import LOOKUP_SEP
from treebeard.mp_tree import MP_Node
from wagtail.core import hooks
from wagtail.core.models import Page
from .field_adapters import adapter_registry
fr... | 0.774626 | 0.14682 |
import os, sys
import numpy as np
import cv2
import matplotlib.pyplot as plt
from cv2_custom.marking import cv2_draw_label
from cv2_custom.transformation import scale_image
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLineEdit, QInputDialog)
from config import *
import argparse
parser = argpar... | add_initial_flow_point.py | import os, sys
import numpy as np
import cv2
import matplotlib.pyplot as plt
from cv2_custom.marking import cv2_draw_label
from cv2_custom.transformation import scale_image
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLineEdit, QInputDialog)
from config import *
import argparse
parser = argpar... | 0.292393 | 0.151529 |
import random
import sys
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric import rsa
PEOPLE_FILE = 'people.txt'
KEY_SIZE = 2048
def enc... | secretize.py | import random
import sys
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric import rsa
PEOPLE_FILE = 'people.txt'
KEY_SIZE = 2048
def enc... | 0.191139 | 0.195671 |
from uuid import UUID, uuid4
import anvil.users
from anvil.tables import app_tables, in_transaction, order_by
from anvil_extras import logging
from ..historic.events import Change, Creation
from ..historic.exceptions import (
AuthorizationError,
DuplicationError,
InvalidUIDError,
NonExistentError,
... | server_code/historic_server/persistence.py | from uuid import UUID, uuid4
import anvil.users
from anvil.tables import app_tables, in_transaction, order_by
from anvil_extras import logging
from ..historic.events import Change, Creation
from ..historic.exceptions import (
AuthorizationError,
DuplicationError,
InvalidUIDError,
NonExistentError,
... | 0.692434 | 0.218253 |
from game_states import GameStates
from game_messages import Message
from result_handlers.dead_entity_rh import handle_dead_entity_result
from result_handlers.equip_rh import handle_equip_result
from result_handlers.targeting_rh import handle_targeting_result
from result_handlers.xp_rh import handle_xp_result
from resu... | result_consumer/result_consumer.py | from game_states import GameStates
from game_messages import Message
from result_handlers.dead_entity_rh import handle_dead_entity_result
from result_handlers.equip_rh import handle_equip_result
from result_handlers.targeting_rh import handle_targeting_result
from result_handlers.xp_rh import handle_xp_result
from resu... | 0.378459 | 0.130673 |
import pathlib
import threading
import time
import pyaudio
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.messagebox import showerror, showinfo, showwarning
from classes.scrollimage import ScrollableImage
from classes.audio import AudioHandler
from classes.staffgen import StaffGenerator
from classes.mode... | python/app/app.py | import pathlib
import threading
import time
import pyaudio
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.messagebox import showerror, showinfo, showwarning
from classes.scrollimage import ScrollableImage
from classes.audio import AudioHandler
from classes.staffgen import StaffGenerator
from classes.mode... | 0.433262 | 0.164315 |
from numpy import exp, array, random, dot
#A single neuron, with 3 input connections and 1 output connection.
class NeuralNetwork():
def __init__(self):
random.seed(1)
#A 3 x 1 matrix with random weights, with values in the range -1 to 1
self.synaptic_weights = 2 * random.random((3, 1)) - ... | main.py | from numpy import exp, array, random, dot
#A single neuron, with 3 input connections and 1 output connection.
class NeuralNetwork():
def __init__(self):
random.seed(1)
#A 3 x 1 matrix with random weights, with values in the range -1 to 1
self.synaptic_weights = 2 * random.random((3, 1)) - ... | 0.896312 | 0.743331 |
from typing import List
import bs4
import re
from typing import Iterable
from dataPipelines.gc_crawler.requestors import (
FileBasedPseudoRequestor,
DefaultRequestor,
)
from dataPipelines.gc_crawler.exec_model import Crawler, Parser, Pager
from dataPipelines.gc_crawler.data_model import Document, DownloadableI... | dataPipelines/gc_crawler/example/models.py | from typing import List
import bs4
import re
from typing import Iterable
from dataPipelines.gc_crawler.requestors import (
FileBasedPseudoRequestor,
DefaultRequestor,
)
from dataPipelines.gc_crawler.exec_model import Crawler, Parser, Pager
from dataPipelines.gc_crawler.data_model import Document, DownloadableI... | 0.640973 | 0.227781 |
import requests
import sys
import json
import urllib.parse
server = "172.16.58.3"
# Remeber to change hf_server back to the one above
# when sending a pull request to the public repo
# server = "localhost"
port = "8880"
# Register and enroll new user in organization
def register_user(user_name, organization):
url... | ComputeProvider/HFRequests.py | import requests
import sys
import json
import urllib.parse
server = "172.16.58.3"
# Remeber to change hf_server back to the one above
# when sending a pull request to the public repo
# server = "localhost"
port = "8880"
# Register and enroll new user in organization
def register_user(user_name, organization):
url... | 0.298491 | 0.120724 |
import os
import torch
import numpy as np
import cv2
from torch.utils import data
from ptsemseg.utils import recursive_glob
from ptsemseg.augmentations import *
class larynxLoader(data.Dataset):
def __init__(self, root, split="train", is_transform=False, img_size=(480, 640), augmentations=None, img_norm=True):... | ptsemseg/loader/larynx_loader.py | import os
import torch
import numpy as np
import cv2
from torch.utils import data
from ptsemseg.utils import recursive_glob
from ptsemseg.augmentations import *
class larynxLoader(data.Dataset):
def __init__(self, root, split="train", is_transform=False, img_size=(480, 640), augmentations=None, img_norm=True):... | 0.591959 | 0.236252 |
import argparse
import os
import time
import random
import tqdm
import numpy as np
import imageio
from perlin_noise import fractal2d
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--num-images", "-n", type=int, default=1)
parser.add_ar... | scripts/generate_images.py | import argparse
import os
import time
import random
import tqdm
import numpy as np
import imageio
from perlin_noise import fractal2d
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--num-images", "-n", type=int, default=1)
parser.add_ar... | 0.337094 | 0.0713 |
__author__ = 'ChenyangGao <https://chenyanggao.github.io/>'
__version__ = (0, 0, 1)
__all__ = ['make_highlighter', 'render']
try:
plugin.ensure_import('pygments', 'Pygments') # type: ignore
except:
pass
from html import escape
from typing import Callable, Optional, Union
from pygments import highlight # typ... | script/startup/highlight.py |
__author__ = 'ChenyangGao <https://chenyanggao.github.io/>'
__version__ = (0, 0, 1)
__all__ = ['make_highlighter', 'render']
try:
plugin.ensure_import('pygments', 'Pygments') # type: ignore
except:
pass
from html import escape
from typing import Callable, Optional, Union
from pygments import highlight # typ... | 0.606848 | 0.367299 |
import argparse
import collections
import torch
import torch.nn as nn
import torchvision
from torchvision import datasets, transforms
import numpy as np
import CNNScan.Settings
import CNNScan.utils as utils
import CNNScan.Mark.gan
"""
This class acts as the encodee stage of an auto-encoder.
It can be configured with... | CNNScan/Mark/encoder.py | import argparse
import collections
import torch
import torch.nn as nn
import torchvision
from torchvision import datasets, transforms
import numpy as np
import CNNScan.Settings
import CNNScan.utils as utils
import CNNScan.Mark.gan
"""
This class acts as the encodee stage of an auto-encoder.
It can be configured with... | 0.930648 | 0.517998 |
from __future__ import unicode_literals
from django.test import TestCase
from api.models import Event, Attempt
from django.contrib.auth.models import User
from api import serializers
import datetime
"""
Tests all parameters and fields of AttemptSerializer
"""
def create_event():
return Event.objects.create(
... | fyp/api/tests/serializers/test_attempt_serializer.py | from __future__ import unicode_literals
from django.test import TestCase
from api.models import Event, Attempt
from django.contrib.auth.models import User
from api import serializers
import datetime
"""
Tests all parameters and fields of AttemptSerializer
"""
def create_event():
return Event.objects.create(
... | 0.736969 | 0.327695 |
import configparser
import gettext
import itertools
import pathlib
import subprocess
import threading
import tkinter as tk
import tkinter.messagebox
import tkinter.ttk
import firefox_helper
import nicofox2bookmarks
__title__ = 'NicoFox to Firefox Bookmarks'
__version__ = '0.1.0'
# Private constants.
... | src/nicofox2bookmarks_gui.py | import configparser
import gettext
import itertools
import pathlib
import subprocess
import threading
import tkinter as tk
import tkinter.messagebox
import tkinter.ttk
import firefox_helper
import nicofox2bookmarks
__title__ = 'NicoFox to Firefox Bookmarks'
__version__ = '0.1.0'
# Private constants.
... | 0.368747 | 0.061593 |
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from joblib import Parallel, delayed
import gc
from util import log, checkAndCreateDir, generateLogger, plotClusterPairGrid
from sklearn.decomposition import PCA
from sklearn.decomposition import KernelPCA
fro... | py/prediction/analyzeData.py | import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from joblib import Parallel, delayed
import gc
from util import log, checkAndCreateDir, generateLogger, plotClusterPairGrid
from sklearn.decomposition import PCA
from sklearn.decomposition import KernelPCA
fro... | 0.739516 | 0.430028 |
import simpy
import numpy as np
from numpy.random import RandomState
"""
Simple OB patient flow model 4 - Very simple OO
Details:
- Generate arrivals via Poisson process
- Define an OBUnit class that contains a simpy.Resource object as a member.
Not subclassing Resource, just trying to use it as a m... | obflow_4_oo_1.py | import simpy
import numpy as np
from numpy.random import RandomState
"""
Simple OB patient flow model 4 - Very simple OO
Details:
- Generate arrivals via Poisson process
- Define an OBUnit class that contains a simpy.Resource object as a member.
Not subclassing Resource, just trying to use it as a m... | 0.456894 | 0.176459 |
import os
import numpy as np
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence
from implicit.als import AlternatingLeastSquares
from data import SeqTensor
class ImplicitALS(AlternatingLeastSquares):
""" Simple sub-class for `implicit`s ALS algorithm ""... | model.py | import os
import numpy as np
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence
from implicit.als import AlternatingLeastSquares
from data import SeqTensor
class ImplicitALS(AlternatingLeastSquares):
""" Simple sub-class for `implicit`s ALS algorithm ""... | 0.90335 | 0.358774 |
import subprocess
import textwrap
import socket
import vim
import sys
import os
import imp
from ui import DebugUI
from dbgp import DBGP
def vim_init():
'''put DBG specific keybindings here -- e.g F1, whatever'''
vim.command('ca dbg Dbg')
def vim_quit():
'''remove DBG specific keybindings'''
vim.comma... | vim_debug/new_debugger.py | import subprocess
import textwrap
import socket
import vim
import sys
import os
import imp
from ui import DebugUI
from dbgp import DBGP
def vim_init():
'''put DBG specific keybindings here -- e.g F1, whatever'''
vim.command('ca dbg Dbg')
def vim_quit():
'''remove DBG specific keybindings'''
vim.comma... | 0.18543 | 0.067762 |
import random
from dataclasses import dataclass, Field
from typing import Tuple, List
import numpy as np
from PIL import ImageDraw
from text_renderer.utils.bbox import BBox
from text_renderer.utils.draw_utils import transparent_img
from text_renderer.utils.types import PILImage
from .base_effect import Effect
clas... | text_renderer/text_renderer/effect/line.py | import random
from dataclasses import dataclass, Field
from typing import Tuple, List
import numpy as np
from PIL import ImageDraw
from text_renderer.utils.bbox import BBox
from text_renderer.utils.draw_utils import transparent_img
from text_renderer.utils.types import PILImage
from .base_effect import Effect
clas... | 0.837852 | 0.229913 |
import math
from robofab.objects.objectsRF import RPoint, RSegment
from fontbuild.convertCurves import replaceSegments
def getTangents(contours):
tmap = []
for c in contours:
clen = len(c)
for i in range(clen):
s = c[i]
p = s.points[-1]
ns = c[(i + 1) % clen]... | scripts/lib/fontbuild/mitreGlyph.py | import math
from robofab.objects.objectsRF import RPoint, RSegment
from fontbuild.convertCurves import replaceSegments
def getTangents(contours):
tmap = []
for c in contours:
clen = len(c)
for i in range(clen):
s = c[i]
p = s.points[-1]
ns = c[(i + 1) % clen]... | 0.316475 | 0.394259 |
"""Python binary to train COVID-19 epidemic model with single CPU."""
from typing import Text
from absl import app
from absl import flags
import io_utils
import json
import logging
import numpy as np
import os
import resample
# pylint: disable=import-not-at-top
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import combined_m... | python/code state/run_two_stage_state_cluster.py | """Python binary to train COVID-19 epidemic model with single CPU."""
from typing import Text
from absl import app
from absl import flags
import io_utils
import json
import logging
import numpy as np
import os
import resample
# pylint: disable=import-not-at-top
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import combined_m... | 0.850096 | 0.34403 |
from hydep.constants import SECONDS_PER_DAY
class TimeStep:
"""Class for modifying and storing time step information.
Parameters
----------
coarse : int, optional
Current coarse time step. Defaults to zero
substep : int, optional
Current substep index. Defaults to None
total ... | src/hydep/internal/timestep.py |
from hydep.constants import SECONDS_PER_DAY
class TimeStep:
"""Class for modifying and storing time step information.
Parameters
----------
coarse : int, optional
Current coarse time step. Defaults to zero
substep : int, optional
Current substep index. Defaults to None
total ... | 0.935817 | 0.518668 |
from CTL.causal_tree.nn_pehe.tree import *
from sklearn.model_selection import train_test_split
class ValNode(PEHENode):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# self.obj = obj
# ----------------------------------------------------------------
# Base causal tree (ctl, base ob... | CTL/causal_tree/nn_pehe/val.py | from CTL.causal_tree.nn_pehe.tree import *
from sklearn.model_selection import train_test_split
class ValNode(PEHENode):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# self.obj = obj
# ----------------------------------------------------------------
# Base causal tree (ctl, base ob... | 0.757256 | 0.289252 |
from django.db import models
from django.core.urlresolvers import reverse
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class Resource(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60)
def __unicode__(self): ... | simulation_site/simulation/models.py | from django.db import models
from django.core.urlresolvers import reverse
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class Resource(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60)
def __unicode__(self): ... | 0.466359 | 0.096578 |