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 random import choice, randint
from discord.ext import commands
import discord
from utils.classes import HimejiBot
class Fun(commands.Cog):
def __init__(self, bot: HimejiBot):
self.bot = bot
@commands.command(name="8ball")
@commands.cooldown(1, 5, commands.BucketType.user)
async def _8b... | cogs/fun.py | from random import choice, randint
from discord.ext import commands
import discord
from utils.classes import HimejiBot
class Fun(commands.Cog):
def __init__(self, bot: HimejiBot):
self.bot = bot
@commands.command(name="8ball")
@commands.cooldown(1, 5, commands.BucketType.user)
async def _8b... | 0.422505 | 0.188828 |
from PIL import Image,ImageDraw
import numpy as np
from collections import OrderedDict,defaultdict
import random
#Path of the Image whose components are to be found
IMG_PATH = "sample images/shapes.png"
#Opening the img and converting it into Black and white
img = Image.open(IMG_PATH)
thresh = 220
fn = lambda x : 255... | main.py | from PIL import Image,ImageDraw
import numpy as np
from collections import OrderedDict,defaultdict
import random
#Path of the Image whose components are to be found
IMG_PATH = "sample images/shapes.png"
#Opening the img and converting it into Black and white
img = Image.open(IMG_PATH)
thresh = 220
fn = lambda x : 255... | 0.215764 | 0.5144 |
import argparse
from ...app import NDNApp
from ...encoding import Name, Component
from ...app_support.nfd_mgmt import FaceStatusMsg, FaceQueryFilter, FaceQueryFilterValue, parse_response, \
make_command
from .utils import express_interest
def add_parser(subparsers):
parser = subparsers.add_parser('Remove-Face... | src/ndn/bin/nfdc/cmd_remove_face.py | import argparse
from ...app import NDNApp
from ...encoding import Name, Component
from ...app_support.nfd_mgmt import FaceStatusMsg, FaceQueryFilter, FaceQueryFilterValue, parse_response, \
make_command
from .utils import express_interest
def add_parser(subparsers):
parser = subparsers.add_parser('Remove-Face... | 0.268845 | 0.090776 |
import numpy
from datetime import datetime
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.style.use('classic')
from matplotlib.ticker import FormatStrFormatter
from visuallib import candlestick2_ohlc
def volume_analysis(client,market,num_hours):
candles=numpy.array(client.get_historic... | tradelib.py | import numpy
from datetime import datetime
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.style.use('classic')
from matplotlib.ticker import FormatStrFormatter
from visuallib import candlestick2_ohlc
def volume_analysis(client,market,num_hours):
candles=numpy.array(client.get_historic... | 0.144783 | 0.309206 |
from concurrent import futures
import functools
import json
import os
from typing import Any, Callable, Mapping, Sequence
import chex
import jax.numpy as jnp
from learned_optimization import filesystem
from learned_optimization import jax_utils
from learned_optimization.baselines import utils
import numpy as onp
impor... | learned_optimization/baselines/normalizers.py | from concurrent import futures
import functools
import json
import os
from typing import Any, Callable, Mapping, Sequence
import chex
import jax.numpy as jnp
from learned_optimization import filesystem
from learned_optimization import jax_utils
from learned_optimization.baselines import utils
import numpy as onp
impor... | 0.63477 | 0.34762 |
import pytest
from pg13 import sqparse2
import ply.lex
TOK_ATTRS = ('type','value','lineno','lexpos')
def mktok(tpname,tokval,a,b):
tok = ply.lex.LexToken()
for attr,val in zip(TOK_ATTRS,(tpname,tokval,a,b)): setattr(tok,attr,val)
return tok
def eqtok(self,other):
"here's hoping I don't break something by monk... | test_pg13/test_sqparse2.py | import pytest
from pg13 import sqparse2
import ply.lex
TOK_ATTRS = ('type','value','lineno','lexpos')
def mktok(tpname,tokval,a,b):
tok = ply.lex.LexToken()
for attr,val in zip(TOK_ATTRS,(tpname,tokval,a,b)): setattr(tok,attr,val)
return tok
def eqtok(self,other):
"here's hoping I don't break something by monk... | 0.298696 | 0.478773 |
from logging import CRITICAL, getLevelName
from functools import wraps
from django.utils.decorators import available_attrs
from celery import states
from celery.utils.log import get_task_logger
from api.decorators import catch_exception
from api.task.utils import task_log
logger = get_task_logger(__name__)
class De... | api/mon/log.py | from logging import CRITICAL, getLevelName
from functools import wraps
from django.utils.decorators import available_attrs
from celery import states
from celery.utils.log import get_task_logger
from api.decorators import catch_exception
from api.task.utils import task_log
logger = get_task_logger(__name__)
class De... | 0.452536 | 0.077239 |
import os
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 650
SCREEN_TITLE = "Godzilla Flies"
CAUTION_BACKGROUND = (181, 93, 69)
SAFE_BACKGROUND = (200, 200, 200)
DANGER_BACKGROUND = (189, 32, 32)
MARGIN = 65
SCALING = .15
PLAYER_MOVEMENT_SPEED = 5
ENEMY_MOVEMENT_SPEED = 2
PREDATOR = 1
PREY = 0
TIMER_TIM... | Godzilla_Flies/game/constants.py | import os
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 650
SCREEN_TITLE = "Godzilla Flies"
CAUTION_BACKGROUND = (181, 93, 69)
SAFE_BACKGROUND = (200, 200, 200)
DANGER_BACKGROUND = (189, 32, 32)
MARGIN = 65
SCALING = .15
PLAYER_MOVEMENT_SPEED = 5
ENEMY_MOVEMENT_SPEED = 2
PREDATOR = 1
PREY = 0
TIMER_TIM... | 0.255808 | 0.064713 |
from unittest import TestCase, mock
from django.conf import settings
from lupa.db_connectors import (
bda_access,
execute as db_execute,
execute_sample,
execute_geospatial,
oracle_access,
postgres_access,
generate_query,
generate_query_sample,
generate_geospatial_query,
BDA_Err... | lupa/tests/test_db_connectors.py | from unittest import TestCase, mock
from django.conf import settings
from lupa.db_connectors import (
bda_access,
execute as db_execute,
execute_sample,
execute_geospatial,
oracle_access,
postgres_access,
generate_query,
generate_query_sample,
generate_geospatial_query,
BDA_Err... | 0.536313 | 0.227587 |
from maya.api import OpenMaya
from mango.fields import generic
__all__ = [
"IntegerArrayField",
"FloatArrayField",
]
class IntegerArrayField(generic.IntegerField):
"""
The IntegerArrayField can be used to set and retrieve int multi values. If the
provided value is not a list containing integer ... | scripts/mango/fields/arrays.py | from maya.api import OpenMaya
from mango.fields import generic
__all__ = [
"IntegerArrayField",
"FloatArrayField",
]
class IntegerArrayField(generic.IntegerField):
"""
The IntegerArrayField can be used to set and retrieve int multi values. If the
provided value is not a list containing integer ... | 0.747892 | 0.311597 |
import torch
import torch.nn as nn
from utils import batch_transform, square_dists
def fps(xyz, M):
'''
Sample M points from points according to farthest point sampling (FPS) algorithm.
:param xyz: shape=(B, N, 3)
:return: inds: shape=(B, M)
'''
device = xyz.device
B, N, C = xyz.shape
... | src/models/model_utils.py | import torch
import torch.nn as nn
from utils import batch_transform, square_dists
def fps(xyz, M):
'''
Sample M points from points according to farthest point sampling (FPS) algorithm.
:param xyz: shape=(B, N, 3)
:return: inds: shape=(B, M)
'''
device = xyz.device
B, N, C = xyz.shape
... | 0.913206 | 0.789437 |
from setuptools.extension import Extension
from setuptools import setup
# Read in requirements.txt and populate the python readme with the
# non-comment, non-environment-specifier contents.
_REQUIREMENTS = [req.split(';')[0].split('#')[0].strip() for req in
open('requirements.txt').readlines()
... | setup.py | from setuptools.extension import Extension
from setuptools import setup
# Read in requirements.txt and populate the python readme with the
# non-comment, non-environment-specifier contents.
_REQUIREMENTS = [req.split(';')[0].split('#')[0].strip() for req in
open('requirements.txt').readlines()
... | 0.359926 | 0.131201 |
def fileMayus(pFileName):
#Read each line of pFile parameter to save in mayus to mayus file
with open('./src/fuente.txt', 'w') as mayus:
with open(pFileName, 'r') as lFile:
line = lFile.readline()
while line != '':
mayus.write(line.upper())
line =... | morse.py |
def fileMayus(pFileName):
#Read each line of pFile parameter to save in mayus to mayus file
with open('./src/fuente.txt', 'w') as mayus:
with open(pFileName, 'r') as lFile:
line = lFile.readline()
while line != '':
mayus.write(line.upper())
line =... | 0.076887 | 0.246329 |
import argparse as argparse
import csv
import sys
import pytator
if __name__=="__main__":
parser = argparse.ArgumentParser(
description='Import Fathom-style Species CSV')
parser.add_argument('-i', '--input',
help='Path csv file.',
required=True)
pa... | scripts/csvToTree.py | import argparse as argparse
import csv
import sys
import pytator
if __name__=="__main__":
parser = argparse.ArgumentParser(
description='Import Fathom-style Species CSV')
parser.add_argument('-i', '--input',
help='Path csv file.',
required=True)
pa... | 0.214445 | 0.075007 |
import socket
from collections import OrderedDict
from ipaddress import IPv4Network, IPv6Network, ip_network
from typing import Set, Union
import psutil
def interface_subnets(interface: str) -> Set[Union[IPv4Network, IPv6Network]]:
"""Given a network interface, retrieve the associated IP subnets.
Args:
... | src/turret/core/util.py | import socket
from collections import OrderedDict
from ipaddress import IPv4Network, IPv6Network, ip_network
from typing import Set, Union
import psutil
def interface_subnets(interface: str) -> Set[Union[IPv4Network, IPv6Network]]:
"""Given a network interface, retrieve the associated IP subnets.
Args:
... | 0.751739 | 0.358213 |
import torch
import torch as T
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import random
from utils_pg import *
class WordProbLayer(nn.Module):
def __init__(self, hidden_size, ctx_size, dim_y, dict_size, device, copy, coverage):
super(WordProbLayer, self).__in... | word_prob_layer.py | import torch
import torch as T
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import random
from utils_pg import *
class WordProbLayer(nn.Module):
def __init__(self, hidden_size, ctx_size, dim_y, dict_size, device, copy, coverage):
super(WordProbLayer, self).__in... | 0.919638 | 0.340513 |
from subprocess import (Popen, PIPE)
import os
import csv
import json
from .ts import (convert_datetime, date_index)
import pandas as pd
from sensible.loginit import logger
log = logger(__name__)
#Git Globals
GIT_COMMIT_FIELDS = ['id', 'author_name', 'author_email', 'date', 'message']
GIT_LOG_FORMAT = ['%H', '%an',... | devml/mkdata.py | from subprocess import (Popen, PIPE)
import os
import csv
import json
from .ts import (convert_datetime, date_index)
import pandas as pd
from sensible.loginit import logger
log = logger(__name__)
#Git Globals
GIT_COMMIT_FIELDS = ['id', 'author_name', 'author_email', 'date', 'message']
GIT_LOG_FORMAT = ['%H', '%an',... | 0.4206 | 0.108756 |
import numpy as np
import os
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def get_stats(df):
df_means = df.groupby(['timestep']).mean()
df_std = df.groupby(['timestep']).std()
lower_band = df_means - df_std
upper_band = df_means + df_std
lower_band[lower_band < 0] = 0... | visualization/generate_plots_2.py |
import numpy as np
import os
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def get_stats(df):
df_means = df.groupby(['timestep']).mean()
df_std = df.groupby(['timestep']).std()
lower_band = df_means - df_std
upper_band = df_means + df_std
lower_band[lower_band < 0] = 0... | 0.248808 | 0.258986 |
import telebot
import random as r
from requests import get
from telebot import types
from loguru import logger as log
# LOCAL FILES
import libvirt_api as virt
import sign_api
from codec_smiles import smile_dict
from config import TOKEN, vip
from sql_api import *
from ssh_api import send_keys_with_password
# INIT
bo... | bot/main.py | import telebot
import random as r
from requests import get
from telebot import types
from loguru import logger as log
# LOCAL FILES
import libvirt_api as virt
import sign_api
from codec_smiles import smile_dict
from config import TOKEN, vip
from sql_api import *
from ssh_api import send_keys_with_password
# INIT
bo... | 0.091753 | 0.080574 |
import abc
#CLASE ABSTRACTA
class Page(metaclass=abc.ABCMeta):
@abc.abstractmethod
def url(self):
pass
def folder(self):
pass
def link(self):
pass
def titulo(self):
pass
def desc(self):
pass
def fromato(self):
pass
#CLASE BASE IMPLEMENTAMOS C... | Ene-Jun-2020/alvarado-lara-luz-deorela-sabas/PrimerParcial/Ejercicio2/Page_Decorator.py | import abc
#CLASE ABSTRACTA
class Page(metaclass=abc.ABCMeta):
@abc.abstractmethod
def url(self):
pass
def folder(self):
pass
def link(self):
pass
def titulo(self):
pass
def desc(self):
pass
def fromato(self):
pass
#CLASE BASE IMPLEMENTAMOS C... | 0.296654 | 0.081813 |
import os
import shutil
import subprocess
import sys
import unittest
try:
import six
except ImportError:
class six(object):
PY3 = False
if six.PY3:
import urllib.request as urllib_request
else:
import urllib2 as urllib_request
# Make it possible to run out of the working copy.
sys.path.insert... | src/test/test_hash.py | import os
import shutil
import subprocess
import sys
import unittest
try:
import six
except ImportError:
class six(object):
PY3 = False
if six.PY3:
import urllib.request as urllib_request
else:
import urllib2 as urllib_request
# Make it possible to run out of the working copy.
sys.path.insert... | 0.429669 | 0.240306 |
from . import forms
from . import models
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.urls import reverse_lazy
from django.views import generic
import os
import hashlib
from datetime import datetime
class RouteListView(generic.ListView):
model = models.Route
form... | myapp/views.py | from . import forms
from . import models
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.urls import reverse_lazy
from django.views import generic
import os
import hashlib
from datetime import datetime
class RouteListView(generic.ListView):
model = models.Route
form... | 0.430866 | 0.064742 |
import torch
import torch.nn as nn
from load import normalizeString
from prepare_data import indexesFromSentence
MAX_LENGTH = 10
SOS_token = 1
USE_CUDA = torch.cuda.is_available()
device = torch.device("cuda" if USE_CUDA else "cpu")
def evaluate(searcher, voc, sentence, max_length=MAX_LENGTH):
indexes_batch = [... | Chatbot/evaluate.py | import torch
import torch.nn as nn
from load import normalizeString
from prepare_data import indexesFromSentence
MAX_LENGTH = 10
SOS_token = 1
USE_CUDA = torch.cuda.is_available()
device = torch.device("cuda" if USE_CUDA else "cpu")
def evaluate(searcher, voc, sentence, max_length=MAX_LENGTH):
indexes_batch = [... | 0.765681 | 0.399782 |
import collections
import copy
import csv
import json
import logging
import os
import pathlib
import shlex
import shutil
import subprocess
import sys
import uuid
import par_upload
import validate
import nanopore
cfg = None
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s.%(msecs)03d %(levelname)... | catsup.py | import collections
import copy
import csv
import json
import logging
import os
import pathlib
import shlex
import shutil
import subprocess
import sys
import uuid
import par_upload
import validate
import nanopore
cfg = None
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s.%(msecs)03d %(levelname)... | 0.245718 | 0.101189 |
import os
import bpy
from bpy.props import *
from bpy_extras.io_utils import ImportHelper, ExportHelper
from . import globvars as G
#-------------------------------------------------------------
# animation.py
#-------------------------------------------------------------
class ConvertOptions:
convertPoses = ... | buttons27.py |
import os
import bpy
from bpy.props import *
from bpy_extras.io_utils import ImportHelper, ExportHelper
from . import globvars as G
#-------------------------------------------------------------
# animation.py
#-------------------------------------------------------------
class ConvertOptions:
convertPoses = ... | 0.509764 | 0.166879 |
import copy
import sys
from btrfs_diff.tests.render_subvols import render_sendstream
from btrfs_diff.tests.demo_sendstreams_expected import render_demo_subvols
from fs_image.fs_utils import Path
from tests.temp_subvolumes import TempSubvolumes
from ..common import PhaseOrder
from ..make_dirs import MakeDirsItem
from ... | fs_image/compiler/items/tests/test_make_subvol.py | import copy
import sys
from btrfs_diff.tests.render_subvols import render_sendstream
from btrfs_diff.tests.demo_sendstreams_expected import render_demo_subvols
from fs_image.fs_utils import Path
from tests.temp_subvolumes import TempSubvolumes
from ..common import PhaseOrder
from ..make_dirs import MakeDirsItem
from ... | 0.352425 | 0.189334 |
import re
import pytz
import datetime
import stringcase
def convert_to_snakecase(data, delete_empty_values=True):
"""
stringcase.snakecase('fooBarBaz') # => "_foo_bar_baz"
"""
EXCEPTIONS_CHILD = ['dockerLabels']
if isinstance(data, dict):
_data = {}
for key, value in data.items():... | ecsctl/template.py | import re
import pytz
import datetime
import stringcase
def convert_to_snakecase(data, delete_empty_values=True):
"""
stringcase.snakecase('fooBarBaz') # => "_foo_bar_baz"
"""
EXCEPTIONS_CHILD = ['dockerLabels']
if isinstance(data, dict):
_data = {}
for key, value in data.items():... | 0.253861 | 0.162247 |
import numpy
import nlcpy
import functools
def numpy_wrap(func):
@functools.wraps(func)
def wrap_func(*args, **kwargs):
is_out = False
try:
return func(*args, **kwargs)
except NotImplementedError:
f = getattr(numpy, func.__name__)
# retrieve input n... | nlcpy/wrapper/numpy_wrap.py |
import numpy
import nlcpy
import functools
def numpy_wrap(func):
@functools.wraps(func)
def wrap_func(*args, **kwargs):
is_out = False
try:
return func(*args, **kwargs)
except NotImplementedError:
f = getattr(numpy, func.__name__)
# retrieve input n... | 0.339828 | 0.128799 |
def load_airport_list():
# Import standard modules ...
import csv
import os
# Create the empty list ...
airports = []
# Make database path ...
dbpath = f"{os.path.dirname(__file__)}/../openflights/data/airports.dat"
# Check that database is there ...
if not os.path.exists(dbpath):... | fmc/load_airport_list.py | def load_airport_list():
# Import standard modules ...
import csv
import os
# Create the empty list ...
airports = []
# Make database path ...
dbpath = f"{os.path.dirname(__file__)}/../openflights/data/airports.dat"
# Check that database is there ...
if not os.path.exists(dbpath):... | 0.385953 | 0.225672 |
import filecmp
import os
from collections import OrderedDict
import pytest
from mock import MagicMock, Mock, call, patch
import paths
from AndroidRunner.Devices import Devices
from AndroidRunner.Experiment import Experiment
from AndroidRunner.ExperimentFactory import ExperimentFactory
from AndroidRunner.NativeExperim... | android-runner/tests/unit/test_experiment.py | import filecmp
import os
from collections import OrderedDict
import pytest
from mock import MagicMock, Mock, call, patch
import paths
from AndroidRunner.Devices import Devices
from AndroidRunner.Experiment import Experiment
from AndroidRunner.ExperimentFactory import ExperimentFactory
from AndroidRunner.NativeExperim... | 0.544317 | 0.227942 |
from twitter_api_client import twitter_api, twitter_auth, variables
from twitter_api_client import twitter_error as te
from flask_api import exceptions as fa_exc
from .util import strftime, strptime
import logging
class TwitterBackService(object):
"""This class is used to control the Twitter API Client integra... | api/back_service.py |
from twitter_api_client import twitter_api, twitter_auth, variables
from twitter_api_client import twitter_error as te
from flask_api import exceptions as fa_exc
from .util import strftime, strptime
import logging
class TwitterBackService(object):
"""This class is used to control the Twitter API Client integra... | 0.533641 | 0.061509 |
import subprocess
import os
import json
from jsonpath_rw import jsonpath, parse
DATA_DIR = './data/'
FORCE_ALIGNED_DIRECTORY = './force_aligned_json/'
PAIRS_DIRECTORY = './minimal_pairs/'
jsonpath_expr = parse('words[*].alignedWord')
if not os.path.exists(DATA_DIR):
os.mkdir(DATA_DIR)
json_files = os.listdir(PA... | module/create_audio_files.py | import subprocess
import os
import json
from jsonpath_rw import jsonpath, parse
DATA_DIR = './data/'
FORCE_ALIGNED_DIRECTORY = './force_aligned_json/'
PAIRS_DIRECTORY = './minimal_pairs/'
jsonpath_expr = parse('words[*].alignedWord')
if not os.path.exists(DATA_DIR):
os.mkdir(DATA_DIR)
json_files = os.listdir(PA... | 0.145146 | 0.141815 |
from collections.abc import Sequence
import numpy as np
from mmcv.utils import build_from_cfg
from ..registry import PIPELINES
@PIPELINES.register_module()
class Compose(object):
"""Compose a data pipeline with a sequence of transforms.
Args:
transforms (list[dict | callable]):
Either c... | mmaction/datasets/pipelines/compose.py | from collections.abc import Sequence
import numpy as np
from mmcv.utils import build_from_cfg
from ..registry import PIPELINES
@PIPELINES.register_module()
class Compose(object):
"""Compose a data pipeline with a sequence of transforms.
Args:
transforms (list[dict | callable]):
Either c... | 0.934932 | 0.567098 |
from flask import session, redirect, url_for, render_template, request
from .forms import LoginForm
from flask import Flask, jsonify, request, send_file, render_template, redirect, url_for, make_response
from flask_socketio import SocketIO, send
import numpy as np
from . import main
import matplotlib.pyplot as plt
imp... | app/main/routes.py | from flask import session, redirect, url_for, render_template, request
from .forms import LoginForm
from flask import Flask, jsonify, request, send_file, render_template, redirect, url_for, make_response
from flask_socketio import SocketIO, send
import numpy as np
from . import main
import matplotlib.pyplot as plt
imp... | 0.329392 | 0.149625 |
import datetime
import logging
from pysmartweatherio.const import (
UNIT_DISTANCE_KM,
UNIT_DISTANCE_MI,
UNIT_PRECIP_IN,
UNIT_PRECIP_MM,
UNIT_PRESSURE_HPA,
UNIT_PRESSURE_INHG,
UNIT_PRESSURE_MB,
UNIT_TEMP_CELCIUS,
UNIT_TEMP_FAHRENHEIT,
UNIT_WIND_KMH,
UNIT_WIND_MPH,
UNIT_WI... | pysmartweatherio/helper_functions.py | import datetime
import logging
from pysmartweatherio.const import (
UNIT_DISTANCE_KM,
UNIT_DISTANCE_MI,
UNIT_PRECIP_IN,
UNIT_PRECIP_MM,
UNIT_PRESSURE_HPA,
UNIT_PRESSURE_INHG,
UNIT_PRESSURE_MB,
UNIT_TEMP_CELCIUS,
UNIT_TEMP_FAHRENHEIT,
UNIT_WIND_KMH,
UNIT_WIND_MPH,
UNIT_WI... | 0.695545 | 0.282178 |
import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import k as kB, u
from latexplot import latexplot
import matplotlib as mpl
from pathlib import Path
import json
import cmocean as cmo
pgf_with_latex = { # setup matplotlib
"pgf.texsystem": "pdflatex",
"font.family": "s... | TexContents/Figures/Evap/BoxTrapEvaporation/sketch.py | import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import k as kB, u
from latexplot import latexplot
import matplotlib as mpl
from pathlib import Path
import json
import cmocean as cmo
pgf_with_latex = { # setup matplotlib
"pgf.texsystem": "pdflatex",
"font.family": "s... | 0.322633 | 0.417093 |
import time
from urllib.parse import urljoin
import pytest
import requests
import responses
from _repobee import http
_ARBITRARY_BASE_URL = "https://repobee.org"
_ARBITRARY_NUMBER = 1
class TestRateLimitModifyRequests:
"""Tests for the rate_limit_modify_requests function."""
def test_replaces_requests_mo... | tests/unit_tests/repobee/test_http.py | import time
from urllib.parse import urljoin
import pytest
import requests
import responses
from _repobee import http
_ARBITRARY_BASE_URL = "https://repobee.org"
_ARBITRARY_NUMBER = 1
class TestRateLimitModifyRequests:
"""Tests for the rate_limit_modify_requests function."""
def test_replaces_requests_mo... | 0.697506 | 0.228436 |
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sensitivity as sst
import visualize as vs
import calculate as cc
import sys
import matplotlib.pyplot as plt
class MainWindow(QMainWindow):
def __init__(self):
# constructor call of super class
super().__init__()
# creates u... | gui.py | from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sensitivity as sst
import visualize as vs
import calculate as cc
import sys
import matplotlib.pyplot as plt
class MainWindow(QMainWindow):
def __init__(self):
# constructor call of super class
super().__init__()
# creates u... | 0.425844 | 0.100746 |
from copy import deepcopy
from typing import List, Dict, Optional, Union
import jsonpickle
from ethtx.utils.pickable import JsonObject
class TransformationSemantics:
transformed_name: Optional[str]
transformed_type: Optional[str]
transformation: Optional[str]
def __init__(
self,
tr... | ethtx/models/semantics_model.py |
from copy import deepcopy
from typing import List, Dict, Optional, Union
import jsonpickle
from ethtx.utils.pickable import JsonObject
class TransformationSemantics:
transformed_name: Optional[str]
transformed_type: Optional[str]
transformation: Optional[str]
def __init__(
self,
tr... | 0.929288 | 0.343479 |
import ply.lex as lex
import ply.yacc as yacc
import sqlite3 as lite
import logging
logging.basicConfig(
level = logging.DEBUG,
filename = "parselog.txt",
filemode = "w",
format = "%(filename)10s:%(lineno)4d:%(message)s"
)
log = logging.getLogger()
TABLE_NAME = "bibtex"
# connect to database
conn = l... | BibTex-Parser/bibtext-parser.py | import ply.lex as lex
import ply.yacc as yacc
import sqlite3 as lite
import logging
logging.basicConfig(
level = logging.DEBUG,
filename = "parselog.txt",
filemode = "w",
format = "%(filename)10s:%(lineno)4d:%(message)s"
)
log = logging.getLogger()
TABLE_NAME = "bibtex"
# connect to database
conn = l... | 0.286968 | 0.103794 |
import numpy as np
from sklearn.cluster import KMeans
from features.spectral_features import istft
from features.data_preprocessing import make_stft_features, \
undo_preemphasis
def preprocess_signal(signal, sample_rate):
"""
Preprocess a signal for input into ... | magnolia/sandbox/demo/app/clustering_utils.py | import numpy as np
from sklearn.cluster import KMeans
from features.spectral_features import istft
from features.data_preprocessing import make_stft_features, \
undo_preemphasis
def preprocess_signal(signal, sample_rate):
"""
Preprocess a signal for input into ... | 0.87982 | 0.923627 |
import numpy as np
from prettyprint import pp
queryRootPath = 'Data/Queries/Q'
relevanceFile = 'Data/RelevancyJudgments/relevance'
def queryRelevance():
"""
this method will parse the query relevance judgement file and
corresponding queries and will return a list of dictionaries
containing the query a... | util.py | import numpy as np
from prettyprint import pp
queryRootPath = 'Data/Queries/Q'
relevanceFile = 'Data/RelevancyJudgments/relevance'
def queryRelevance():
"""
this method will parse the query relevance judgement file and
corresponding queries and will return a list of dictionaries
containing the query a... | 0.751739 | 0.685135 |
import sys
sys.path.append('Utils/')
import Smipar
import torch
import pandas as pd
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as data_utils
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
from sklearn.preprocessing import label... | Model/train_model.py | import sys
sys.path.append('Utils/')
import Smipar
import torch
import pandas as pd
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as data_utils
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
from sklearn.preprocessing import label... | 0.753467 | 0.30935 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['AppServiceArgs', 'AppService']
@pulumi.input_type
class AppServiceArgs:
def __init__(__self__, *,
... | sdk/python/pulumi_azure/appservice/app_service.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['AppServiceArgs', 'AppService']
@pulumi.input_type
class AppServiceArgs:
def __init__(__self__, *,
... | 0.828454 | 0.055566 |
import os
import json
import pandas as pd
mappings = {
"English": "eng",
"Japanese": "jpn",
"French": "fra",
"Italian": "ita",
"German": "deu",
"Spanish": "spa",
"Russian": "rus",
"Polish": "pol",
"Korean": "kor",
"traditional Chinese": "chi_tra",
"Simplified Chinese": "chi... | scripts/build_skill_files.py | import os
import json
import pandas as pd
mappings = {
"English": "eng",
"Japanese": "jpn",
"French": "fra",
"Italian": "ita",
"German": "deu",
"Spanish": "spa",
"Russian": "rus",
"Polish": "pol",
"Korean": "kor",
"traditional Chinese": "chi_tra",
"Simplified Chinese": "chi... | 0.270577 | 0.236439 |
# pylint: disable = line-too-long, invalid-name, missing-docstring
# standard imports
import json
import typing
from typing import Union, Optional, List, Tuple, Set, FrozenSet, Mapping, Dict, NamedTuple, Deque
from decimal import Decimal
from collections import deque, OrderedDict
# external dependencies
from typing_e... | test/test_12_to_json_obj.py | # pylint: disable = line-too-long, invalid-name, missing-docstring
# standard imports
import json
import typing
from typing import Union, Optional, List, Tuple, Set, FrozenSet, Mapping, Dict, NamedTuple, Deque
from decimal import Decimal
from collections import deque, OrderedDict
# external dependencies
from typing_e... | 0.766162 | 0.61806 |
from pymongo import MongoClient
from pymongo.errors import BulkWriteError
import json
import requests
def get_blogs(keywords, client_id, client_secret):
"""
Naver 검색-블로그 api를 사용해서 특정 키워드에 대한 Blog 정보 수집
:Params list keywords : 키워드 리스
:Params str client_id : Api 사용 아이디
:Params str client_pw : Api ... | save_naver_blogs.py |
from pymongo import MongoClient
from pymongo.errors import BulkWriteError
import json
import requests
def get_blogs(keywords, client_id, client_secret):
"""
Naver 검색-블로그 api를 사용해서 특정 키워드에 대한 Blog 정보 수집
:Params list keywords : 키워드 리스
:Params str client_id : Api 사용 아이디
:Params str client_pw : Api ... | 0.307774 | 0.273745 |
import datetime
import aiohttp
import pytest
import pytz
from aio_geojson_geonetnz_quakes.feed_manager import GeonetnzQuakesFeedManager
from tests.utils import load_fixture
@pytest.mark.asyncio
async def test_feed_manager(aresponses, event_loop):
"""Test the feed manager."""
home_coordinates = (-41.2, 174.7... | tests/test_feed_manager.py | import datetime
import aiohttp
import pytest
import pytz
from aio_geojson_geonetnz_quakes.feed_manager import GeonetnzQuakesFeedManager
from tests.utils import load_fixture
@pytest.mark.asyncio
async def test_feed_manager(aresponses, event_loop):
"""Test the feed manager."""
home_coordinates = (-41.2, 174.7... | 0.551332 | 0.288826 |
import tornado.web
import logging
import time
import sys
import os
import json as JSON # 启用别名,不会跟方法里的局部变量混淆
from comm import *
from global_const import *
from base_handler import *
from tornado.escape import json_encode, json_decode
from tornado.httpclient import *
from tornado.httputil import url_concat
from torna... | foo/api_qrcode.py |
import tornado.web
import logging
import time
import sys
import os
import json as JSON # 启用别名,不会跟方法里的局部变量混淆
from comm import *
from global_const import *
from base_handler import *
from tornado.escape import json_encode, json_decode
from tornado.httpclient import *
from tornado.httputil import url_concat
from torna... | 0.201381 | 0.071754 |
import random
import copy
from graph import canvas
from search import a_star as a_path_search, dfs as dfs_path_search, tools
from search.queue import PriorityQueue
TOTAL = canvas.WIDTH * canvas.HEIGHT
HALF = int(TOTAL / 2)
def valid_coord(coord, coords):
"""
验证坐标是否可用
:param coord: 待验证的坐标
:param co... | src/snake_ai.py | import random
import copy
from graph import canvas
from search import a_star as a_path_search, dfs as dfs_path_search, tools
from search.queue import PriorityQueue
TOTAL = canvas.WIDTH * canvas.HEIGHT
HALF = int(TOTAL / 2)
def valid_coord(coord, coords):
"""
验证坐标是否可用
:param coord: 待验证的坐标
:param co... | 0.402627 | 0.413122 |
from __future__ import division
from builtins import range
import sys
sys.path.insert(1, "../../../")
import h2o
from tests import pyunit_utils, assert_equals
from h2o.estimators.random_forest import H2ORandomForestEstimator
def rf_predict_contributions_sorting_smoke():
fr = h2o.import_file(path=pyunit_utils.loc... | h2o-py/tests/testdir_algos/rf/pyunit_rf_predict_contributions_sorting_smoke.py | from __future__ import division
from builtins import range
import sys
sys.path.insert(1, "../../../")
import h2o
from tests import pyunit_utils, assert_equals
from h2o.estimators.random_forest import H2ORandomForestEstimator
def rf_predict_contributions_sorting_smoke():
fr = h2o.import_file(path=pyunit_utils.loc... | 0.690872 | 0.549943 |
import datetime
import logging
import os
import sys
import pandas as pd
import numpy as np
import pickle
import pprint
import gzip
import random
import time
from market_gym.config import DEBUG, root, s_log_file
sys.path.append('../../')
'''
Begin help functions
'''
def save_q_table(e, i_trial):
'''
Log the f... | market_gym/envs/simulator.py | import datetime
import logging
import os
import sys
import pandas as pd
import numpy as np
import pickle
import pprint
import gzip
import random
import time
from market_gym.config import DEBUG, root, s_log_file
sys.path.append('../../')
'''
Begin help functions
'''
def save_q_table(e, i_trial):
'''
Log the f... | 0.256832 | 0.179495 |
import logging
from braindump.models import CardPlacement
from cards.models import Card
from categories.models import Category
logger = logging.getLogger(__name__)
def create_card_placements_for_shared_category(share_contract):
"""Creates card placements for a recently accepted share contract
"""
for c... | braindump/tasks.py | import logging
from braindump.models import CardPlacement
from cards.models import Card
from categories.models import Category
logger = logging.getLogger(__name__)
def create_card_placements_for_shared_category(share_contract):
"""Creates card placements for a recently accepted share contract
"""
for c... | 0.45423 | 0.072014 |
from __future__ import annotations
from typing import Union
from numpy import ndarray
from pandas import DataFrame
from sklearn.pipeline import FeatureUnion
from ....representation import FData
class FDAFeatureUnion(FeatureUnion): # type: ignore
"""Concatenates results of multiple functional transformer objec... | skfda/preprocessing/dim_reduction/feature_extraction/_fda_feature_union.py | from __future__ import annotations
from typing import Union
from numpy import ndarray
from pandas import DataFrame
from sklearn.pipeline import FeatureUnion
from ....representation import FData
class FDAFeatureUnion(FeatureUnion): # type: ignore
"""Concatenates results of multiple functional transformer objec... | 0.966379 | 0.600891 |
from __future__ import unicode_literals
import os.path, shutil
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from require.conf import settings as require_settings
def default_staticfiles_dir():
staticfiles_dirs = getattr(settings, "STATICFILES_DIRS", ())
... | require/management/commands/require_init.py | from __future__ import unicode_literals
import os.path, shutil
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from require.conf import settings as require_settings
def default_staticfiles_dir():
staticfiles_dirs = getattr(settings, "STATICFILES_DIRS", ())
... | 0.47244 | 0.071526 |
import math
from scipy.stats import laplace, kstest
from probtorch.distributions.laplace import Laplace
import torch
from common import TestCase, run_tests, SAMPLE_COUNT
from torch.autograd import Variable
class TestLaplace(TestCase):
def test_logprob(self):
mu = Variable(torch.randn(100))
b = tor... | test/test_laplace.py | import math
from scipy.stats import laplace, kstest
from probtorch.distributions.laplace import Laplace
import torch
from common import TestCase, run_tests, SAMPLE_COUNT
from torch.autograd import Variable
class TestLaplace(TestCase):
def test_logprob(self):
mu = Variable(torch.randn(100))
b = tor... | 0.383641 | 0.60903 |
from resources.libraries.python.topology import Topology
def get_variables(node, interface):
"""Create and return a dictionary of test variables.
:param node: Honeycomb node.
:param interface: Name, link name or sw_if_index of an interface.
:type node: dict
:type interface: str or int
:retur... | resources/test_data/honeycomb/nat.py | from resources.libraries.python.topology import Topology
def get_variables(node, interface):
"""Create and return a dictionary of test variables.
:param node: Honeycomb node.
:param interface: Name, link name or sw_if_index of an interface.
:type node: dict
:type interface: str or int
:retur... | 0.776029 | 0.50531 |
import json
import os
import re
import torch
import warnings
def init_models(
device=torch.device("cuda"),
speaker_list: list = ["dina", "mila", "tisha", "pasha", "tina", "nika"],
):
models = {
speaker: fetch_model(speaker=speaker).to(device) for speaker in speaker_list
}
return models
d... | utils.py | import json
import os
import re
import torch
import warnings
def init_models(
device=torch.device("cuda"),
speaker_list: list = ["dina", "mila", "tisha", "pasha", "tina", "nika"],
):
models = {
speaker: fetch_model(speaker=speaker).to(device) for speaker in speaker_list
}
return models
d... | 0.506103 | 0.251157 |
import wx
import ScrolledWindow
#----------------------------------------------------------------------
class MyPrintout(wx.Printout):
def __init__(self, canvas, log):
wx.Printout.__init__(self)
self.canvas = canvas
self.log = log
def OnBeginDocument(self, start, end):
self.... | widgets/PrintFramework.py |
import wx
import ScrolledWindow
#----------------------------------------------------------------------
class MyPrintout(wx.Printout):
def __init__(self, canvas, log):
wx.Printout.__init__(self)
self.canvas = canvas
self.log = log
def OnBeginDocument(self, start, end):
self.... | 0.564459 | 0.092237 |
import dpath.util
def test_search_paths_with_separator():
dict = {
"a": {
"b": {
"c": {
"d": 0,
"e": 1,
"f": 2,
},
},
},
}
paths = [
'a',
'a;b',
'a;b;... | tests/test_util_search.py | import dpath.util
def test_search_paths_with_separator():
dict = {
"a": {
"b": {
"c": {
"d": 0,
"e": 1,
"f": 2,
},
},
},
}
paths = [
'a',
'a;b',
'a;b;... | 0.628749 | 0.586108 |
import tensorflow as tf
import scipy
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W, stride):
return tf.nn.conv2d(x, W, stride... | ConvModel.py | import tensorflow as tf
import scipy
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W, stride):
return tf.nn.conv2d(x, W, stride... | 0.83622 | 0.402803 |
import sys
sys.path.append("")
from micropython import const
import time, machine
import uasyncio as asyncio
import aioble
import bluetooth
TIMEOUT_MS = 5000
SERVICE_UUID = bluetooth.UUID("A5A5A5A5-FFFF-9999-1111-5A5A5A5A5A5A")
CHAR_UUID = bluetooth.UUID("00000000-1111-2222-3333-444444444444")
_L2CAP_PSN = const... | micropython/bluetooth/aioble/multitests/ble_shutdown.py |
import sys
sys.path.append("")
from micropython import const
import time, machine
import uasyncio as asyncio
import aioble
import bluetooth
TIMEOUT_MS = 5000
SERVICE_UUID = bluetooth.UUID("A5A5A5A5-FFFF-9999-1111-5A5A5A5A5A5A")
CHAR_UUID = bluetooth.UUID("00000000-1111-2222-3333-444444444444")
_L2CAP_PSN = const... | 0.237841 | 0.09556 |
from .device import Device
from .. import config as c
# Unsigned 2 signed
def us2s(unsigned):
signed = unsigned - 65536 if unsigned > 32767 else unsigned
return signed
# Retreives continuous time-of-flight distance measurement in millimeters.
class Imu(Device):
DEVICE_CODE = c.devices.imu.code
READ_C... | tamproxy/devices/imu.py | from .device import Device
from .. import config as c
# Unsigned 2 signed
def us2s(unsigned):
signed = unsigned - 65536 if unsigned > 32767 else unsigned
return signed
# Retreives continuous time-of-flight distance measurement in millimeters.
class Imu(Device):
DEVICE_CODE = c.devices.imu.code
READ_C... | 0.586049 | 0.383728 |
import pytest
from structurizr.model import Component, Container, Model, Person, SoftwareSystem
@pytest.fixture(scope="function")
def empty_model() -> Model:
"""Provide an empty Model on demand for test cases to use."""
return Model()
def test_model_get_relationship_by_id(empty_model: Model):
"""Test r... | tests/unit/model/test_model.py | import pytest
from structurizr.model import Component, Container, Model, Person, SoftwareSystem
@pytest.fixture(scope="function")
def empty_model() -> Model:
"""Provide an empty Model on demand for test cases to use."""
return Model()
def test_model_get_relationship_by_id(empty_model: Model):
"""Test r... | 0.677154 | 0.625781 |
import ast
import io
import os
import pathlib
import pickle
import time
from typing import List, Union
import click
import pydantic
import yaml
from respo import core, settings
def save_respo_model(model: core.RespoModel) -> None:
"""Dumps respo model into bin and yml format files.
Pickle file is generated... | respo/cli.py | import ast
import io
import os
import pathlib
import pickle
import time
from typing import List, Union
import click
import pydantic
import yaml
from respo import core, settings
def save_respo_model(model: core.RespoModel) -> None:
"""Dumps respo model into bin and yml format files.
Pickle file is generated... | 0.553747 | 0.086671 |
import pandas as pd
def clean_know_2020(data: pd.DataFrame) -> tuple[pd.Series, pd.DataFrame]:
data = data.copy()
# Convert the data type to integer and fill the missing values.
for i in range(1, 45):
data[f"saq{i}_1"] = data[f"saq{i}_1"].astype(int)
data[f"saq{i}_2"] = data[f"saq{i}_2"].... | preprocessing/cleaning/clean_know_2020.py | import pandas as pd
def clean_know_2020(data: pd.DataFrame) -> tuple[pd.Series, pd.DataFrame]:
data = data.copy()
# Convert the data type to integer and fill the missing values.
for i in range(1, 45):
data[f"saq{i}_1"] = data[f"saq{i}_1"].astype(int)
data[f"saq{i}_2"] = data[f"saq{i}_2"].... | 0.442757 | 0.479565 |
"""Constants used in the IPHAS Data Release modules."""
import os
from astropy.io import fits
DEBUGMODE = False
# What is the data release version name?
VERSION = 'iphas-dr2-rc6'
# Where are the CASU pipeline-produced images and detection tables?
RAWDATADIR = '/car-data/gb/iphas'
# Where to write the output data prod... | dr2/constants.py | """Constants used in the IPHAS Data Release modules."""
import os
from astropy.io import fits
DEBUGMODE = False
# What is the data release version name?
VERSION = 'iphas-dr2-rc6'
# Where are the CASU pipeline-produced images and detection tables?
RAWDATADIR = '/car-data/gb/iphas'
# Where to write the output data prod... | 0.558809 | 0.134037 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensor2tensor.layers import common_attention
from tensor2tensor.layers import common_hparams
from tensor2tensor.layers import common_layers
from tensor2tensor.layers import discretization
from tensor2tenso... | galaxy2galaxy/models/autoencoders_utils.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensor2tensor.layers import common_attention
from tensor2tensor.layers import common_hparams
from tensor2tensor.layers import common_layers
from tensor2tensor.layers import discretization
from tensor2tenso... | 0.760206 | 0.452415 |
from decimal import Decimal, ROUND_UP
import os
import random
import json
import time, datetime
import crcmod
import serial
import subprocess
import multiprocessing
import numpy as np
import pytz
from werkzeug.wrappers.response import Response
class DSMR_Emulator():
def __init__(
self,
with_gas=... | endpoints/tests/emulators.py | from decimal import Decimal, ROUND_UP
import os
import random
import json
import time, datetime
import crcmod
import serial
import subprocess
import multiprocessing
import numpy as np
import pytz
from werkzeug.wrappers.response import Response
class DSMR_Emulator():
def __init__(
self,
with_gas=... | 0.318909 | 0.1532 |
import os
import urllib2
import json
import signal
import time
gExit = False
def Load(filename):
if os.path.isfile(filename) is True:
file = open(filename, "r")
data = file.read()
file.close()
return data
return ""
def Save(filename, data):
file = open(filename, "w")
file.write(data)
file.close()
def ... | fund_parser.py | import os
import urllib2
import json
import signal
import time
gExit = False
def Load(filename):
if os.path.isfile(filename) is True:
file = open(filename, "r")
data = file.read()
file.close()
return data
return ""
def Save(filename, data):
file = open(filename, "w")
file.write(data)
file.close()
def ... | 0.079429 | 0.10711 |
import collections
import random
import re
import brave
import networkx as nx
from IPython.display import display as jupyter_display
import matplotlib.pyplot as plt
import scipy.spatial.distance as ssd
import scipy.cluster.hierarchy as sch
DETOKENIZE_RULES = (
(r' ([.,!?;:»%)\]\'])( ?)', r'\1\2'),
(r'( ?)(... | narratex/visualization.py | import collections
import random
import re
import brave
import networkx as nx
from IPython.display import display as jupyter_display
import matplotlib.pyplot as plt
import scipy.spatial.distance as ssd
import scipy.cluster.hierarchy as sch
DETOKENIZE_RULES = (
(r' ([.,!?;:»%)\]\'])( ?)', r'\1\2'),
(r'( ?)(... | 0.362969 | 0.396652 |
# In[210]:
#Read in data and just keep the first two classes so as to create a binary problem
get_ipython().magic('matplotlib inline')
import numpy as np
from sklearn.datasets import load_wine
data, labels = load_wine(True)
data = data[:(59 + 71)]
labels = np.expand_dims(labels[:(59 + 71)], axis = 1)
# # Logistic ... | PA2-Coordinate descent/CSE250B PA2 Pin Tian.py |
# In[210]:
#Read in data and just keep the first two classes so as to create a binary problem
get_ipython().magic('matplotlib inline')
import numpy as np
from sklearn.datasets import load_wine
data, labels = load_wine(True)
data = data[:(59 + 71)]
labels = np.expand_dims(labels[:(59 + 71)], axis = 1)
# # Logistic ... | 0.73782 | 0.758645 |
from ete3 import Tree,TreeStyle
from math import factorial
from ete3 import Tree,TreeStyle
from itertools import combinations
def calculate_combinations(n, r):
if(n-r)>=0:return factorial(n) // factorial(r) // factorial(n-r)
else: return 0
def prepostorder(self):
_leaf = self.__class__.is_leaf
t... | Code/Q_dist.py | from ete3 import Tree,TreeStyle
from math import factorial
from ete3 import Tree,TreeStyle
from itertools import combinations
def calculate_combinations(n, r):
if(n-r)>=0:return factorial(n) // factorial(r) // factorial(n-r)
else: return 0
def prepostorder(self):
_leaf = self.__class__.is_leaf
t... | 0.10346 | 0.261276 |
import argparse
import sys
from biocode import utils
'''
Description:
There are many genome files in GenBank with abnormally-long homopolymeric repeats of non-N
bases. For example:
>gi|257136525|ref|NZ_GG699286.1| Xanthomonas campestris pv. vasculorum NCPPB702 genomic scaffold scf_7293_715, whole genome shotgun s... | fasta/replace_homopolymeric_repeats_with_Ns.py |
import argparse
import sys
from biocode import utils
'''
Description:
There are many genome files in GenBank with abnormally-long homopolymeric repeats of non-N
bases. For example:
>gi|257136525|ref|NZ_GG699286.1| Xanthomonas campestris pv. vasculorum NCPPB702 genomic scaffold scf_7293_715, whole genome shotgun s... | 0.35209 | 0.516291 |
from itertools import combinations
from math import gcd, sqrt
from fractions import Fraction
from Source import Source
from SamplesXY import SamplesXY
from CountAlgorithm import CountAlgorithm
from CombinedSample import CombinedSample
from Distribution import Distribution
class TestStatisticDistribution:
def __i... | TestStatisticDistribution.py | from itertools import combinations
from math import gcd, sqrt
from fractions import Fraction
from Source import Source
from SamplesXY import SamplesXY
from CountAlgorithm import CountAlgorithm
from CombinedSample import CombinedSample
from Distribution import Distribution
class TestStatisticDistribution:
def __i... | 0.804636 | 0.322819 |
import sqlite3, os, random, time, sys, hashlib, shutil, readchar, pyperclip
from .funcs import *
from .userClass import userInterface
from datetime import datetime, timedelta
from getpass import getpass
global colors
# Assign colors to colors --> Default is true
colors = buildColors(True)
random.seed(time.time())
def... | src/exec/pwd.py | import sqlite3, os, random, time, sys, hashlib, shutil, readchar, pyperclip
from .funcs import *
from .userClass import userInterface
from datetime import datetime, timedelta
from getpass import getpass
global colors
# Assign colors to colors --> Default is true
colors = buildColors(True)
random.seed(time.time())
def... | 0.213951 | 0.048541 |
import requests
import time
import asyncio
import sys
from itertools import cycle
import fproxy
dat = True
jsonheaders = {"Content-Type": "application/json", 'Pragma': 'no-cache'}
auth = 'https://authserver.mojang.com/authenticate'
nfa = 0
hits = 0
bad = 0
skips = 0
checks = 0
results = open("results.txt", "a")
... | checker.py | import requests
import time
import asyncio
import sys
from itertools import cycle
import fproxy
dat = True
jsonheaders = {"Content-Type": "application/json", 'Pragma': 'no-cache'}
auth = 'https://authserver.mojang.com/authenticate'
nfa = 0
hits = 0
bad = 0
skips = 0
checks = 0
results = open("results.txt", "a")
... | 0.141994 | 0.128279 |
import rospy
import math
import time
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
class WallAvoid(object):
def __init__(self, timeout=None):
rospy.init_node("WallAvoid")
self.turnCoef = [(x ** 2 - 8100) / 10000000.0 for x in range(-90, 0)] + [(-x ** 2 + 8100) / 100000... | catkin_ws/src/building_mapper/scripts/wall_avoid.py | import rospy
import math
import time
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
class WallAvoid(object):
def __init__(self, timeout=None):
rospy.init_node("WallAvoid")
self.turnCoef = [(x ** 2 - 8100) / 10000000.0 for x in range(-90, 0)] + [(-x ** 2 + 8100) / 100000... | 0.398289 | 0.253503 |
import tensorflow as tf
from tensorflow.keras.layers import *
from tensorflow.keras import initializers
from tensorflow.keras import activations
# Embedding有关的层如各种PositionEmbedding等
class Embedding(tf.keras.layers.Embedding):
"""为call添加一个参数,可以当做unbias Dense使用,
用在语言模型的输出计算上。"""
def call(self, inputs, mode... | tf2bert/layers/embeddings.py | import tensorflow as tf
from tensorflow.keras.layers import *
from tensorflow.keras import initializers
from tensorflow.keras import activations
# Embedding有关的层如各种PositionEmbedding等
class Embedding(tf.keras.layers.Embedding):
"""为call添加一个参数,可以当做unbias Dense使用,
用在语言模型的输出计算上。"""
def call(self, inputs, mode... | 0.740925 | 0.553505 |
class TethysAppBase(object):
"""
Base class used to define the app class for Tethys apps.
Attributes:
name (string): Name of the app.
index (string): Lookup term for the index URL of the app.
icon (string): Location of the image to use for the app icon.
package (string): Name of the... | tethys_apps/base/app_base.py | class TethysAppBase(object):
"""
Base class used to define the app class for Tethys apps.
Attributes:
name (string): Name of the app.
index (string): Lookup term for the index URL of the app.
icon (string): Location of the image to use for the app icon.
package (string): Name of the... | 0.917266 | 0.3805 |
# This file is subject to the terms and conditions defined in file 'LICENSE',
# which is part of this repository.
import os
import shutil
from subprocess import call
from urlparse import urlparse
from oslo_config import cfg
from oslo_log import log
import requests
import shade
import yaml
NAME = 'image-manager'
CON... | imagemanager/imagemanager.py |
# This file is subject to the terms and conditions defined in file 'LICENSE',
# which is part of this repository.
import os
import shutil
from subprocess import call
from urlparse import urlparse
from oslo_config import cfg
from oslo_log import log
import requests
import shade
import yaml
NAME = 'image-manager'
CON... | 0.354098 | 0.101723 |
import os
class ParamsParserSig(object):
def __init__(self,ContFile):
self.ContFile=ContFile
self.Method2TMP={'QP':'QP-run.r'}
# self.Method2TMP['SA']='SA-run.r'
self.Method2TMP['MutCon']='MutCon-run.r'
self.Method2TMP['MutPat']='MutPat-run.r'
#self.Metho... | parsers/ParamsParserSig.py | import os
class ParamsParserSig(object):
def __init__(self,ContFile):
self.ContFile=ContFile
self.Method2TMP={'QP':'QP-run.r'}
# self.Method2TMP['SA']='SA-run.r'
self.Method2TMP['MutCon']='MutCon-run.r'
self.Method2TMP['MutPat']='MutPat-run.r'
#self.Metho... | 0.053132 | 0.085442 |
from __future__ import annotations
from typing import Dict, Union, cast
from deprecation import deprecated
from httpx import Response, Timeout
from .. import __version__
from ..base_client import (
DEFAULT_POSTGREST_CLIENT_HEADERS,
DEFAULT_POSTGREST_CLIENT_TIMEOUT,
BasePostgrestClient,
)
from ..utils imp... | venv/Lib/site-packages/postgrest_py/_async/client.py | from __future__ import annotations
from typing import Dict, Union, cast
from deprecation import deprecated
from httpx import Response, Timeout
from .. import __version__
from ..base_client import (
DEFAULT_POSTGREST_CLIENT_HEADERS,
DEFAULT_POSTGREST_CLIENT_TIMEOUT,
BasePostgrestClient,
)
from ..utils imp... | 0.883713 | 0.060668 |
from threading import Thread
import pat
import patl
import logging
import argparse
import time
from patutils import SEPARATOR, BOX_LENGTH, BASE, USE_SEPARATOR
""" A chat protocol based loosely off IRC
The whole thing works with ASCII256 text
"""
standard_ascii = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0... | chat_protocol.py | from threading import Thread
import pat
import patl
import logging
import argparse
import time
from patutils import SEPARATOR, BOX_LENGTH, BASE, USE_SEPARATOR
""" A chat protocol based loosely off IRC
The whole thing works with ASCII256 text
"""
standard_ascii = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0... | 0.442877 | 0.14259 |
from django.db import transaction as db_transaction
from rest_framework import serializers, fields
from credit.models import Credit
from credit.signals import credit_created
from payment.models import Batch
from prison.serializers import PrisonSerializer
from transaction.constants import TRANSACTION_CATEGORY, TRANSAC... | mtp_api/apps/transaction/serializers.py | from django.db import transaction as db_transaction
from rest_framework import serializers, fields
from credit.models import Credit
from credit.signals import credit_created
from payment.models import Batch
from prison.serializers import PrisonSerializer
from transaction.constants import TRANSACTION_CATEGORY, TRANSAC... | 0.710327 | 0.167763 |
from .domain import Domain
from .basictypes import Set, compare
from .cnf import canonical_builder
from .utils import ncr
import random
class Subsets(Domain):
"""Domain of subsets of a domain
When a single argument is provided, the resulting domain contains all
subsets:
Args:
domain (Domain)... | src/haydi/base/subsets.py | from .domain import Domain
from .basictypes import Set, compare
from .cnf import canonical_builder
from .utils import ncr
import random
class Subsets(Domain):
"""Domain of subsets of a domain
When a single argument is provided, the resulting domain contains all
subsets:
Args:
domain (Domain)... | 0.862091 | 0.537163 |
from flask import make_response
import json
from bson import json_util
def json_response(data, code):
"""Return a :class:`flask.Response` with a JSON encoded object ``data`` in
the body.
:param dict data: The data to be put in the response body.
:param int code: The HTTP status code for the response.... | app/lib/json_response.py | from flask import make_response
import json
from bson import json_util
def json_response(data, code):
"""Return a :class:`flask.Response` with a JSON encoded object ``data`` in
the body.
:param dict data: The data to be put in the response body.
:param int code: The HTTP status code for the response.... | 0.793826 | 0.390069 |
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
import numpy as np
import glob
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
import torch.optim as optim
from matplotlib import pyplot as plt
from tool... | MPAtt/train_net.py | import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
import numpy as np
import glob
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
import torch.optim as optim
from matplotlib import pyplot as plt
from tool... | 0.514888 | 0.285879 |
import csv, os, json, argparse, sys, rdflib
"""
For all EC statements with obsolete EC: deprecate deleted entries,
change transferred entries by deleting and creating new without mapping.
Needs the current ftp://ftp.ebi.ac.uk/pub/databases/intenz/enzyme/enzyme.rdf
"""
# Initiate the parser
parser = argparse.ArgumentPa... | old-code/all-depr-obsolete-ec.py | import csv, os, json, argparse, sys, rdflib
"""
For all EC statements with obsolete EC: deprecate deleted entries,
change transferred entries by deleting and creating new without mapping.
Needs the current ftp://ftp.ebi.ac.uk/pub/databases/intenz/enzyme/enzyme.rdf
"""
# Initiate the parser
parser = argparse.ArgumentPa... | 0.232397 | 0.221014 |
import torch
import mmcv
import numpy as np
import pycocotools.mask as maskUtils
import cv2
from mmdet.core import get_classes, tensor2imgs
from mmdet.core import bbox2result, bbox_mapping_back, multiclass_nms
from ..registry import DETECTORS
from .single_stage import SingleStageDetector
from mmdet.patches i... | mmdet/models/detectors/reppoints_detector.py | import torch
import mmcv
import numpy as np
import pycocotools.mask as maskUtils
import cv2
from mmdet.core import get_classes, tensor2imgs
from mmdet.core import bbox2result, bbox_mapping_back, multiclass_nms
from ..registry import DETECTORS
from .single_stage import SingleStageDetector
from mmdet.patches i... | 0.770853 | 0.253255 |
import unittest
from mock import patch, Mock, call, PropertyMock
from munch import Munch
from pysvc import errors as svc_errors
from pysvc.unified.response import CLIFailureError, SVCResponse
import controller.array_action.config as config
import controller.array_action.errors as array_errors
from controller.array_ac... | controller/tests/array_action/svc/array_mediator_svc_test.py | import unittest
from mock import patch, Mock, call, PropertyMock
from munch import Munch
from pysvc import errors as svc_errors
from pysvc.unified.response import CLIFailureError, SVCResponse
import controller.array_action.config as config
import controller.array_action.errors as array_errors
from controller.array_ac... | 0.547464 | 0.22114 |
"""Helper for conducting code reviews."""
from __future__ import print_function
from __future__ import unicode_literals
import os
import re
import subprocess
import sys
from l2tdevtools.helpers import project
from l2tdevtools.lib import errors
from l2tdevtools.lib import netrcfile
from l2tdevtools.review_helpers imp... | l2tdevtools/review_helpers/review.py | """Helper for conducting code reviews."""
from __future__ import print_function
from __future__ import unicode_literals
import os
import re
import subprocess
import sys
from l2tdevtools.helpers import project
from l2tdevtools.lib import errors
from l2tdevtools.lib import netrcfile
from l2tdevtools.review_helpers imp... | 0.612426 | 0.205117 |
import sys, csv, os
import numpy as np
try:
matrix = open(sys.argv[1])
outmatrix = sys.argv[2]
if len(sys.argv) > 3:
method = sys.argv[3].lower()
else:
method = 'cpm'
if len(sys.argv) > 4:
gtf = sys.argv[4]
else:
gtf = ''
except:
sys.stderr.write('usage: script.py matrix outmatrix [cpm/uq/median] [gtf]\... | bin/normalize_counts_matrix.py | import sys, csv, os
import numpy as np
try:
matrix = open(sys.argv[1])
outmatrix = sys.argv[2]
if len(sys.argv) > 3:
method = sys.argv[3].lower()
else:
method = 'cpm'
if len(sys.argv) > 4:
gtf = sys.argv[4]
else:
gtf = ''
except:
sys.stderr.write('usage: script.py matrix outmatrix [cpm/uq/median] [gtf]\... | 0.041647 | 0.249744 |
from tqdm import tqdm, trange
from transformers import DataCollator
from .trainer_base import *
from .trainer_config import TrainerConfig
from .trainer_metrics import TaskTrainerMetrics
from .trainer_scheduler import TaskTrainedScheduler
from .trainer_logger import TaskTrainerLogger
from .trainer_optimizers import Tas... | transformersx/train/trainer.py | from tqdm import tqdm, trange
from transformers import DataCollator
from .trainer_base import *
from .trainer_config import TrainerConfig
from .trainer_metrics import TaskTrainerMetrics
from .trainer_scheduler import TaskTrainedScheduler
from .trainer_logger import TaskTrainerLogger
from .trainer_optimizers import Tas... | 0.690872 | 0.089415 |
# CHANGELOG:
# Added/Changed Slot D, 1c.0 for secondary M.2 Slot, changed the other slot names to match
# Changed Run functions to be Subprocess.Popen (was Subprocess.call) due to issues where one drive would fail and cause the script to stop all drives,
# this opens an individual process for each window.
#
# Ch... | NVME Frankenstein Script.py |
# CHANGELOG:
# Added/Changed Slot D, 1c.0 for secondary M.2 Slot, changed the other slot names to match
# Changed Run functions to be Subprocess.Popen (was Subprocess.call) due to issues where one drive would fail and cause the script to stop all drives,
# this opens an individual process for each window.
#
# Ch... | 0.175361 | 0.170473 |
import os, sys, random
import argparse
import numpy as np
import toml
import asteval
from pbpl import compton
import Geant4 as g4
from Geant4.hepunit import *
import h5py
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plot
import matplotlib as mpl
from matplotlib.backends.backend_pdf import PdfPage... | pbpl/compton/plot_deposition.py | import os, sys, random
import argparse
import numpy as np
import toml
import asteval
from pbpl import compton
import Geant4 as g4
from Geant4.hepunit import *
import h5py
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plot
import matplotlib as mpl
from matplotlib.backends.backend_pdf import PdfPage... | 0.403332 | 0.295611 |
import math
import numpy as np
_curves = dict()
def is_power_of_2(num):
return ((num & (num - 1)) == 0) and num != 0
def hilbert_curve(n):
"""
Generate Hilbert curve indexing for (n, n) array. 'n' must be a power of two.
Taken from http://znah.net/hilbert-curve-indexing.html. Thanks to <NAME>.
... | acoustic_sight/hilbert_curve.py | import math
import numpy as np
_curves = dict()
def is_power_of_2(num):
return ((num & (num - 1)) == 0) and num != 0
def hilbert_curve(n):
"""
Generate Hilbert curve indexing for (n, n) array. 'n' must be a power of two.
Taken from http://znah.net/hilbert-curve-indexing.html. Thanks to <NAME>.
... | 0.658966 | 0.530236 |
import cv2
import numpy as np
from table_detect import table_detect
from table_line import table_line
from table_build import tableBuid,to_excel
from utils import minAreaRectbox, measure, eval_angle, draw_lines
class table:
def __init__(self, img, tableSize=(416, 416), tableLineSize=(1024, 1024), isTableDetect=Fal... | table_ceil.py | import cv2
import numpy as np
from table_detect import table_detect
from table_line import table_line
from table_build import tableBuid,to_excel
from utils import minAreaRectbox, measure, eval_angle, draw_lines
class table:
def __init__(self, img, tableSize=(416, 416), tableLineSize=(1024, 1024), isTableDetect=Fal... | 0.23118 | 0.186391 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('createuser', '0005_remove_userprofile_lastname'),
]
operations = [
migrations.CreateModel(
name='loginprofile',
fields=[
('id', models.AutoField(aut... | ADAS-BACKEND-STDCODE-main/createuser/migrations/0006_auto_20210628_1259.py |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('createuser', '0005_remove_userprofile_lastname'),
]
operations = [
migrations.CreateModel(
name='loginprofile',
fields=[
('id', models.AutoField(aut... | 0.579281 | 0.24858 |
from rest_framework.schemas.openapi import AutoSchema
from rest_framework import serializers
from surf.vendor.elasticsearch.serializers import RelationSerializer
from surf.apps.materials.serializers import KeywordsRequestSerializer
class SearchSchema(AutoSchema):
def _map_field(self, field):
if field.fi... | service/surf/apps/core/schema.py | from rest_framework.schemas.openapi import AutoSchema
from rest_framework import serializers
from surf.vendor.elasticsearch.serializers import RelationSerializer
from surf.apps.materials.serializers import KeywordsRequestSerializer
class SearchSchema(AutoSchema):
def _map_field(self, field):
if field.fi... | 0.720172 | 0.211478 |