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 |
|---|---|---|---|---|
# --- Day 8: Matchsticks ---
# Space on the sleigh is limited this year, and so Santa will be bringing his list as a digital copy. He needs to know how much space it will take up when stored.
# It is common in many programming languages to provide a way to escape special characters in strings. For example, C, JavaSc... | 2015/day8/2015-day8-part1.py |
# --- Day 8: Matchsticks ---
# Space on the sleigh is limited this year, and so Santa will be bringing his list as a digital copy. He needs to know how much space it will take up when stored.
# It is common in many programming languages to provide a way to escape special characters in strings. For example, C, JavaSc... | 0.535827 | 0.757279 |
# %%
from warnings import warn
from .. import SanUnit
from ._decay import Decay
from ..utils.loading import load_data, data_path
__all__ = ('Toilet',)
data_path += 'sanunit_data/_toilet.tsv'
# %%
class Toilet(SanUnit, Decay, isabstract=True):
'''
Abstract class containing common parameters and design algo... | qsdsan/sanunits/_toilet.py | # %%
from warnings import warn
from .. import SanUnit
from ._decay import Decay
from ..utils.loading import load_data, data_path
__all__ = ('Toilet',)
data_path += 'sanunit_data/_toilet.tsv'
# %%
class Toilet(SanUnit, Decay, isabstract=True):
'''
Abstract class containing common parameters and design algo... | 0.658198 | 0.521654 |
import json
import ahocorasick
import pytest
from detect_secrets.core.potential_secret import PotentialSecret
from detect_secrets.plugins.keyword import KeywordDetector
from testing.mocks import mock_file_object
FOLLOWED_BY_COLON_EQUAL_SIGNS_RE = {
'negatives': {
'quotes_required': [
'theapi... | tests/plugins/keyword_test.py | import json
import ahocorasick
import pytest
from detect_secrets.core.potential_secret import PotentialSecret
from detect_secrets.plugins.keyword import KeywordDetector
from testing.mocks import mock_file_object
FOLLOWED_BY_COLON_EQUAL_SIGNS_RE = {
'negatives': {
'quotes_required': [
'theapi... | 0.216757 | 0.160069 |
import argparse
import sys
import numpy as np
import stl
def _argparser():
p = argparse.ArgumentParser(description='Tool for cloning objects in STL')
p.add_argument('-nx', type=int, default=1, help='Number of clones in X direction')
p.add_argument('-ny', type=int, default=1, help='Number of clones in Y di... | stlclone.py | import argparse
import sys
import numpy as np
import stl
def _argparser():
p = argparse.ArgumentParser(description='Tool for cloning objects in STL')
p.add_argument('-nx', type=int, default=1, help='Number of clones in X direction')
p.add_argument('-ny', type=int, default=1, help='Number of clones in Y di... | 0.206734 | 0.125923 |
"""Face attribute train."""
import os
import time
import datetime
import mindspore
import mindspore.nn as nn
from mindspore import context
from mindspore import Tensor
from mindspore.nn.optim import Momentum
from mindspore.communication.management import get_group_size, init, get_rank
from mindspore.nn import TrainOneS... | research/cv/FaceAttribute/train.py | """Face attribute train."""
import os
import time
import datetime
import mindspore
import mindspore.nn as nn
from mindspore import context
from mindspore import Tensor
from mindspore.nn.optim import Momentum
from mindspore.communication.management import get_group_size, init, get_rank
from mindspore.nn import TrainOneS... | 0.69368 | 0.120594 |
import os
import sys
import logging
# third pary librarys
from elevate import elevate
# local modules
import subcmd
class Install(subcmd.SubCmd):
""" Install this application into OS's path library
In Linux, create the symbloic link in the /usr/local/bin
In Windows, append application folder in... | src/install.py |
import os
import sys
import logging
# third pary librarys
from elevate import elevate
# local modules
import subcmd
class Install(subcmd.SubCmd):
""" Install this application into OS's path library
In Linux, create the symbloic link in the /usr/local/bin
In Windows, append application folder in... | 0.220091 | 0.055413 |
# %% IMPORTS
# Built-in imports
from inspect import _VAR_KEYWORD, _VAR_POSITIONAL, _empty, isclass, signature
from os import path
import warnings
# Package imports
import e13tools as e13
from mpi4pyd.MPI import get_HybridComm_obj
import numpy as np
from numpy.random import rand
from sortedcontainers import SortedDict ... | prism/modellink/utils.py | # %% IMPORTS
# Built-in imports
from inspect import _VAR_KEYWORD, _VAR_POSITIONAL, _empty, isclass, signature
from os import path
import warnings
# Package imports
import e13tools as e13
from mpi4pyd.MPI import get_HybridComm_obj
import numpy as np
from numpy.random import rand
from sortedcontainers import SortedDict ... | 0.830113 | 0.466603 |
from mathics.builtin.base import (
Builtin,
Test,
)
from mathics.builtin.lists import list_boxes
from mathics.core.expression import Expression
from mathics.core.atoms import Integer
from mathics.core.symbols import Symbol, SymbolList, SymbolTrue
from mathics.core.systemsymbols import (
SymbolAssociation,... | mathics/builtin/list/associations.py | from mathics.builtin.base import (
Builtin,
Test,
)
from mathics.builtin.lists import list_boxes
from mathics.core.expression import Expression
from mathics.core.atoms import Integer
from mathics.core.symbols import Symbol, SymbolList, SymbolTrue
from mathics.core.systemsymbols import (
SymbolAssociation,... | 0.626467 | 0.555254 |
import re
import requests
import os
import csv
# Fukcije url_to_text, zapisi_csv in zapisi_v_csv so pobrane z repozitorija od predmeta Programiranje 1.
STEVILO_STRANI = 166
mapa = 'zajeti_podatki'
linki = 'linki.txt'
nepremicnine_txt = 'nepremicnine.txt'
nepremicnine_csv = 'nepremicnine.csv'
vzorec_linka = r'<meta it... | zajemi_strani.py | import re
import requests
import os
import csv
# Fukcije url_to_text, zapisi_csv in zapisi_v_csv so pobrane z repozitorija od predmeta Programiranje 1.
STEVILO_STRANI = 166
mapa = 'zajeti_podatki'
linki = 'linki.txt'
nepremicnine_txt = 'nepremicnine.txt'
nepremicnine_csv = 'nepremicnine.csv'
vzorec_linka = r'<meta it... | 0.133105 | 0.191214 |
import argparse
import json
import os
import platform
import subprocess
import prepare_compile_cmd
import prepare_compiler_info
import prepare_analyzer_cmd
def execute(cmd):
print("Executing command: " + ' '.join(cmd))
try:
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIP... | scripts/debug_tools/prepare_all_cmd_for_ctu.py |
import argparse
import json
import os
import platform
import subprocess
import prepare_compile_cmd
import prepare_compiler_info
import prepare_analyzer_cmd
def execute(cmd):
print("Executing command: " + ' '.join(cmd))
try:
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIP... | 0.283385 | 0.062217 |
from .QPro import Gate
from .baseClasses import setAttr
from ..QuantumToolbox import evolution
from ..QuantumToolbox import operators #pylint: disable=relative-beyond-top-level
from ..QuantumToolbox import spinRotations #pylint: disable=relative-beyond-top-level
class SpinRotation(Gate): # pylint: disable=too-many-anc... | src/quanguru/classes/QGates.py | from .QPro import Gate
from .baseClasses import setAttr
from ..QuantumToolbox import evolution
from ..QuantumToolbox import operators #pylint: disable=relative-beyond-top-level
from ..QuantumToolbox import spinRotations #pylint: disable=relative-beyond-top-level
class SpinRotation(Gate): # pylint: disable=too-many-anc... | 0.705176 | 0.15633 |
import asyncio
import json
import logging
import multiprocessing
import time
import contextlib
from django.apps import AppConfig
from django.conf import settings
import glob
from hfc.fabric import Client
from hfc.fabric.peer import Peer
from hfc.fabric.user import create_user
from hfc.util.keyvaluestore import File... | backend/events/apps.py | import asyncio
import json
import logging
import multiprocessing
import time
import contextlib
from django.apps import AppConfig
from django.conf import settings
import glob
from hfc.fabric import Client
from hfc.fabric.peer import Peer
from hfc.fabric.user import create_user
from hfc.util.keyvaluestore import File... | 0.452294 | 0.069732 |
from __future__ import unicode_literals
from snapshottest import Snapshot
snapshots = Snapshot()
snapshots['test_create_execution_plan_with_dep 1'] = '''{
"__class__": "ExecutionPlanSnapshot",
"artifacts_persisted": true,
"executor_name": "in_process",
"initial_known_state": null,
"pipeline_snapshot_id": "... | python_modules/dagster/dagster_tests/core_tests/snap_tests/snapshots/snap_test_execution_plan.py | from __future__ import unicode_literals
from snapshottest import Snapshot
snapshots = Snapshot()
snapshots['test_create_execution_plan_with_dep 1'] = '''{
"__class__": "ExecutionPlanSnapshot",
"artifacts_persisted": true,
"executor_name": "in_process",
"initial_known_state": null,
"pipeline_snapshot_id": "... | 0.649912 | 0.346873 |
import os
from abc import abstractmethod
from pants.backend.jvm.tasks.classpath_entry import ClasspathEntry
from pants.base.build_environment import get_buildroot
from pants.engine.fs import Digest, PathGlobs, PathGlobsAndRoot
from pants.task.task import Task
from pants.util.dirutil import fast_relpath
class Resour... | src/python/pants/backend/jvm/tasks/resources_task.py |
import os
from abc import abstractmethod
from pants.backend.jvm.tasks.classpath_entry import ClasspathEntry
from pants.base.build_environment import get_buildroot
from pants.engine.fs import Digest, PathGlobs, PathGlobsAndRoot
from pants.task.task import Task
from pants.util.dirutil import fast_relpath
class Resour... | 0.566258 | 0.194062 |
from __future__ import absolute_import
from __future__ import division
__all__ = ['plr_osnet']
import torch
from torch import nn
from torch.nn import functional as F
import torchvision
from .osnet_ain import *
import copy
import random
import math
from .attention_module import Attention_Module
from .gen_mean_pool imp... | torchreid/models/plr_osnet_ain.py | from __future__ import absolute_import
from __future__ import division
__all__ = ['plr_osnet']
import torch
from torch import nn
from torch.nn import functional as F
import torchvision
from .osnet_ain import *
import copy
import random
import math
from .attention_module import Attention_Module
from .gen_mean_pool imp... | 0.916405 | 0.252384 |
import argparse
import json
from embers.sat_utils.sat_ephemeris import ephem_batch
def main():
"""
Analyse a batch of TLE files is with the :func:`~embers.sat_utils.sat_ephemeris.ephem_batch` function.
Determine satellite ephemeris data: rise time, set time, alt/az arrays at a given time cadence. This i... | src/embers/kindle/ephem_batch.py | import argparse
import json
from embers.sat_utils.sat_ephemeris import ephem_batch
def main():
"""
Analyse a batch of TLE files is with the :func:`~embers.sat_utils.sat_ephemeris.ephem_batch` function.
Determine satellite ephemeris data: rise time, set time, alt/az arrays at a given time cadence. This i... | 0.795936 | 0.395484 |
__all__ = ['getch']
class _Getch:
"""
Gets a single character from standard input. Does not echo to the screen.
"""
def __init__(self, is_blocking=True):
try:
self.impl = _GetchWindows(is_blocking)
except ImportError:
self.impl = _GetchUnix(is_blocking)
d... | stream2py/utility/getch.py | __all__ = ['getch']
class _Getch:
"""
Gets a single character from standard input. Does not echo to the screen.
"""
def __init__(self, is_blocking=True):
try:
self.impl = _GetchWindows(is_blocking)
except ImportError:
self.impl = _GetchUnix(is_blocking)
d... | 0.444444 | 0.119459 |
import click
import shutil
import os
import re
import subprocess
from collections import defaultdict
from typing import List, Dict, FrozenSet
import networkx as nx
import matplotlib.pyplot as plt
from networkx.drawing.nx_agraph import graphviz_layout
from networkx.algorithms.simple_paths import all_simple_paths
class... | snakemake_workaround.py | import click
import shutil
import os
import re
import subprocess
from collections import defaultdict
from typing import List, Dict, FrozenSet
import networkx as nx
import matplotlib.pyplot as plt
from networkx.drawing.nx_agraph import graphviz_layout
from networkx.algorithms.simple_paths import all_simple_paths
class... | 0.367611 | 0.312882 |
import json
from typing import Any, Dict, List, Optional
from dateutil.relativedelta import relativedelta
from django.contrib.postgres.fields import JSONField
from django.core.exceptions import EmptyResultSet
from django.db import connection, models, transaction
from django.db.models import Q
from django.db.models.exp... | posthog/models/cohort.py | import json
from typing import Any, Dict, List, Optional
from dateutil.relativedelta import relativedelta
from django.contrib.postgres.fields import JSONField
from django.core.exceptions import EmptyResultSet
from django.db import connection, models, transaction
from django.db.models import Q
from django.db.models.exp... | 0.699049 | 0.111676 |
import analyzer_lib.utils.utils as u
import analyzer_lib.data_manipulation.tables as t
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, LongType, DecimalType, DoubleType, FloatType
from pyspark.sql import DataFrame, Row
from pyspark.sql import functions as F
import configparser
import ... | src/main.py | import analyzer_lib.utils.utils as u
import analyzer_lib.data_manipulation.tables as t
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, LongType, DecimalType, DoubleType, FloatType
from pyspark.sql import DataFrame, Row
from pyspark.sql import functions as F
import configparser
import ... | 0.313945 | 0.268654 |
from __future__ import annotations
from collections import UserDict, defaultdict
from typing import (
Callable,
ClassVar,
Dict,
Generic,
Iterable,
Mapping,
Optional,
Sequence,
Set,
Type,
TypeVar,
Union,
)
K = TypeVar("K")
V = TypeVar("V")
class Bag(UserDict, Generic[K... | streamlined/common/data_structures.py | from __future__ import annotations
from collections import UserDict, defaultdict
from typing import (
Callable,
ClassVar,
Dict,
Generic,
Iterable,
Mapping,
Optional,
Sequence,
Set,
Type,
TypeVar,
Union,
)
K = TypeVar("K")
V = TypeVar("V")
class Bag(UserDict, Generic[K... | 0.918279 | 0.363139 |
import numpy as np
from functions.my_LLE import My_LLE
import matplotlib.pyplot as plt
import functions.utils as utils
class My_GLLE_DirectSampling:
def __init__(self, X, n_neighbors=10, n_components=None, path_save="./", verbosity=0):
# X: rows are features and columns are samples
self.n_compone... | functions/my_GLLE_DirectSampling.py | import numpy as np
from functions.my_LLE import My_LLE
import matplotlib.pyplot as plt
import functions.utils as utils
class My_GLLE_DirectSampling:
def __init__(self, X, n_neighbors=10, n_components=None, path_save="./", verbosity=0):
# X: rows are features and columns are samples
self.n_compone... | 0.68056 | 0.521349 |
import sys
sys.path.append("../python")
import numpy as np
import matplotlib.pyplot as plt
import dmfortfactor as dm
dresfile = '../data/C/c12Nmax8chi20hw'
hofrequencies = np.arange(15., 25., 1)
operators = [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for operator in operators:
print("Operator-%i"%operator... | examples/exampleHOFrequency.py | import sys
sys.path.append("../python")
import numpy as np
import matplotlib.pyplot as plt
import dmfortfactor as dm
dresfile = '../data/C/c12Nmax8chi20hw'
hofrequencies = np.arange(15., 25., 1)
operators = [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for operator in operators:
print("Operator-%i"%operator... | 0.173884 | 0.280188 |
import serial
import sys
import time
import serial.tools.list_ports
# declare once
ser = serial.Serial()
def readserial(ser, numlines):
readcount = 0
readmore = True
while readmore:
rcv1 = ""
rcv1 = ser.readline()
words = rcv1.split()
print rcv1
print words
... | eggSearcher06.py |
import serial
import sys
import time
import serial.tools.list_ports
# declare once
ser = serial.Serial()
def readserial(ser, numlines):
readcount = 0
readmore = True
while readmore:
rcv1 = ""
rcv1 = ser.readline()
words = rcv1.split()
print rcv1
print words
... | 0.125923 | 0.086439 |
from __future__ import division
import json
import mailchimp3
from mailchimp3 import MailChimp
from user_login_credentials import user_name
from user_login_credentials import api_key
class single_report:
def __init__(self, report_data):
self.campaign_id = report_data['id']
self.subject_line = report_data['subject... | mailchimp_api_wrapper.py | from __future__ import division
import json
import mailchimp3
from mailchimp3 import MailChimp
from user_login_credentials import user_name
from user_login_credentials import api_key
class single_report:
def __init__(self, report_data):
self.campaign_id = report_data['id']
self.subject_line = report_data['subject... | 0.183703 | 0.042305 |
import json
import time
from django.db.models import F
from django_mysql.models.functions import JSONExtract
from scores.models import Score, Round
from scores.util import convert_ms_to_minutes
def process(score: Score) -> Score:
if score.round.challenge_name == 'countme':
return process_countme(score)
... | scores/score_processor.py | import json
import time
from django.db.models import F
from django_mysql.models.functions import JSONExtract
from scores.models import Score, Round
from scores.util import convert_ms_to_minutes
def process(score: Score) -> Score:
if score.round.challenge_name == 'countme':
return process_countme(score)
... | 0.356671 | 0.173778 |
# coding=utf-8
import os
import sys
from aliyunsdkcore.acs_exception import error_code, error_msg
from aliyunsdkcore.acs_exception.exceptions import ClientException
from xml.dom.minidom import parse
from aliyunsdkcore.profile import location_service
"""
Region&Endpoint provider module.
Created on 6/12/2015
@autho... | aliyunsdkcore/profile/region_provider.py |
# coding=utf-8
import os
import sys
from aliyunsdkcore.acs_exception import error_code, error_msg
from aliyunsdkcore.acs_exception.exceptions import ClientException
from xml.dom.minidom import parse
from aliyunsdkcore.profile import location_service
"""
Region&Endpoint provider module.
Created on 6/12/2015
@autho... | 0.253214 | 0.064418 |
import socket
class NETPowerConnector():
"""Connects to NET Power Control via UDP.
"""
def __init__(self):
self.user = 'admin'
self.password = '<PASSWORD>'
def send_to_power_control(self, message):
"""Send string message to Power Control via UDP.
Input: message as... | WaltzControl/PowerControl/power_connector.py | import socket
class NETPowerConnector():
"""Connects to NET Power Control via UDP.
"""
def __init__(self):
self.user = 'admin'
self.password = '<PASSWORD>'
def send_to_power_control(self, message):
"""Send string message to Power Control via UDP.
Input: message as... | 0.57821 | 0.178938 |
import threading
import logging
import os
import time
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP)
REQUIREMENTS = ['evdev==0.6.1']
_LOGGER = logging.getLogger(__name__)
DEVICE_DESCRIPTOR = 'd... | homeassistant/components/keyboard_remote.py | import threading
import logging
import os
import time
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP)
REQUIREMENTS = ['evdev==0.6.1']
_LOGGER = logging.getLogger(__name__)
DEVICE_DESCRIPTOR = 'd... | 0.466603 | 0.052765 |
import os
import argparse
import torch
import random
import numpy as np
from torch.utils.data import DataLoader
from datasets.dataset_dfc import DFC2020
from networks.propnets import E_Fusion
from utils.util import RandomApply, default, seed_torch
from utils.losses import HardNegtive_loss
from kornia import f... | train_EfusionS1.py | import os
import argparse
import torch
import random
import numpy as np
from torch.utils.data import DataLoader
from datasets.dataset_dfc import DFC2020
from networks.propnets import E_Fusion
from utils.util import RandomApply, default, seed_torch
from utils.losses import HardNegtive_loss
from kornia import f... | 0.644673 | 0.108614 |
# 当前脚本只能在 Windows 下运行
# 可以使用 Python 3 的语法,Windows 下大家约定用 Python 3.7 以上
import os
import shutil
import subprocess
import sys
import hashlib
import socket
import time
import build_linux_yaml_template as template
NOW_TEXT = time.strftime("%Y-%m-%d_%H_%M_%S%z", time.localtime())
# 要保证有 2 位数来表示子游戏类型,只能 2 位,不能多不能少。
DIR_LIS... | build_windows_server.py |
# 当前脚本只能在 Windows 下运行
# 可以使用 Python 3 的语法,Windows 下大家约定用 Python 3.7 以上
import os
import shutil
import subprocess
import sys
import hashlib
import socket
import time
import build_linux_yaml_template as template
NOW_TEXT = time.strftime("%Y-%m-%d_%H_%M_%S%z", time.localtime())
# 要保证有 2 位数来表示子游戏类型,只能 2 位,不能多不能少。
DIR_LIS... | 0.176743 | 0.092074 |
import sys
import torch
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parents[2]
sys.path.append(str(BASE_DIR))
from torch.utils.data import Dataset
from leaf.nlp_utils.tokenizer import Tokenizer
class Sent140Dataset(Dataset):
def __init__(self, client_id: int, client_str: str, data: list, targe... | fedlab_benchmarks/leaf/dataset/sent140_dataset.py | import sys
import torch
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parents[2]
sys.path.append(str(BASE_DIR))
from torch.utils.data import Dataset
from leaf.nlp_utils.tokenizer import Tokenizer
class Sent140Dataset(Dataset):
def __init__(self, client_id: int, client_str: str, data: list, targe... | 0.751283 | 0.380442 |
from gemd.entity.object.base_object import BaseObject
from gemd.entity.object.has_conditions import HasConditions
from gemd.entity.object.has_parameters import HasParameters
from gemd.entity.object.has_source import HasSource
from gemd.entity.setters import validate_list
class ProcessRun(BaseObject, HasConditions, Ha... | gemd/entity/object/process_run.py | from gemd.entity.object.base_object import BaseObject
from gemd.entity.object.has_conditions import HasConditions
from gemd.entity.object.has_parameters import HasParameters
from gemd.entity.object.has_source import HasSource
from gemd.entity.setters import validate_list
class ProcessRun(BaseObject, HasConditions, Ha... | 0.911962 | 0.395718 |
import requests
import os
import locale
import click
import json
from sys import exit
from importlib import import_module
from subprocess import call
from functools import partial
# HELPER FUNCTIONS
def _localization():
'''Returns a module object containing all the help strings according to the
locale of t... | venv/lib/python3.7/site-packages/gitman/gitman.py | import requests
import os
import locale
import click
import json
from sys import exit
from importlib import import_module
from subprocess import call
from functools import partial
# HELPER FUNCTIONS
def _localization():
'''Returns a module object containing all the help strings according to the
locale of t... | 0.396419 | 0.110064 |
import sys
from wordcloud import WordCloud,ImageColorGenerator
from collections import Counter
import jieba.posseg as psg
import matplotlib.pyplot as plt
# 对文本分词并标注词性,并缓存到文件
def cut_and_cache(text):
# 将文本分词,并附带上词性,因为数据量比较大,防止每次运行脚本都花大量时间,所以第一次分词后就将结果存入文件cut_result.txt中
# 相当于做一个缓存,格式为每个词占一行,每一行的内容为:
... | libs/wordcloud/ai/word_cloud.py | import sys
from wordcloud import WordCloud,ImageColorGenerator
from collections import Counter
import jieba.posseg as psg
import matplotlib.pyplot as plt
# 对文本分词并标注词性,并缓存到文件
def cut_and_cache(text):
# 将文本分词,并附带上词性,因为数据量比较大,防止每次运行脚本都花大量时间,所以第一次分词后就将结果存入文件cut_result.txt中
# 相当于做一个缓存,格式为每个词占一行,每一行的内容为:
... | 0.133049 | 0.379953 |
import pytest
from unittest.mock import patch
import logging
from pyvesync_v2 import VeSync, VeSyncAir131
from pyvesync_v2.helpers import Helpers as helpers
from . import call_json
DEV_LIST_DETAIL = call_json.LIST_CONF_AIR
CORRECT_LIST = call_json.DEVLIST_AIR
ENERGY_HISTORY = call_json.ENERGY_HISTORY
CORRECT_DETAI... | src/tests/test_air_pur.py |
import pytest
from unittest.mock import patch
import logging
from pyvesync_v2 import VeSync, VeSyncAir131
from pyvesync_v2.helpers import Helpers as helpers
from . import call_json
DEV_LIST_DETAIL = call_json.LIST_CONF_AIR
CORRECT_LIST = call_json.DEVLIST_AIR
ENERGY_HISTORY = call_json.ENERGY_HISTORY
CORRECT_DETAI... | 0.565299 | 0.268198 |
import uuid
from flask import Blueprint, redirect, request, url_for, flash, abort
from flask_login import login_required, current_user
from flask_babelplus import gettext as _
from flaskbb.extensions import db
from flaskbb.utils.settings import flaskbb_config
from flaskbb.utils.helpers import render_template, format_... | flaskbb/message/views.py | import uuid
from flask import Blueprint, redirect, request, url_for, flash, abort
from flask_login import login_required, current_user
from flask_babelplus import gettext as _
from flaskbb.extensions import db
from flaskbb.utils.settings import flaskbb_config
from flaskbb.utils.helpers import render_template, format_... | 0.361954 | 0.0566 |
import os
import json
from typing import Optional
import torch
import numpy as np
from tqdm import tqdm
from sklearn import metrics
from persia.ctx import TrainCtx, eval_ctx
from persia.distributed import DDPOption
from persia.embedding.optim import Adagrad
from persia.embedding.data import PersiaBatch
from persia.... | e2e/adult_income/train.py | import os
import json
from typing import Optional
import torch
import numpy as np
from tqdm import tqdm
from sklearn import metrics
from persia.ctx import TrainCtx, eval_ctx
from persia.distributed import DDPOption
from persia.embedding.optim import Adagrad
from persia.embedding.data import PersiaBatch
from persia.... | 0.883601 | 0.310054 |
from typing import Dict, List, Tuple
from enum import Enum
import bpy
from bpy.props import (
FloatProperty, IntVectorProperty, FloatVectorProperty,
BoolProperty, CollectionProperty, EnumProperty, IntProperty,
StringProperty)
from .operator_func.common import MeshType, AnimationLoopType
from .common_data ... | mcblend/object_data.py | from typing import Dict, List, Tuple
from enum import Enum
import bpy
from bpy.props import (
FloatProperty, IntVectorProperty, FloatVectorProperty,
BoolProperty, CollectionProperty, EnumProperty, IntProperty,
StringProperty)
from .operator_func.common import MeshType, AnimationLoopType
from .common_data ... | 0.833528 | 0.247601 |
from typing import List, Tuple
import torch
from torch import nn
from equideepdmri.layers.filter.filter_kernel import KernelDefinitionInterface
from equideepdmri.utils.q_space import Q_SamplingSchema
from equideepdmri.utils.spherical_tensor import SphericalTensorType
class SumKernel(nn.Module):
def __init__(sel... | equideepdmri/layers/filter/combined_filter_kernels.py | from typing import List, Tuple
import torch
from torch import nn
from equideepdmri.layers.filter.filter_kernel import KernelDefinitionInterface
from equideepdmri.utils.q_space import Q_SamplingSchema
from equideepdmri.utils.spherical_tensor import SphericalTensorType
class SumKernel(nn.Module):
def __init__(sel... | 0.963179 | 0.601389 |
# Get a permission denied error when running the script in the shell? chmod 755 the script .py file
import sys
import os
import subprocess
import shutil
import http.client, urllib
# COMIC_TAGGER_PATH = 'COMIC_TAGGER_PATH/Applications/ComicTagger.app/Contents/MacOS/ComicTagger'
COMIC_TAGGER_PATH = "C:\\Program Files... | ComicArchiveFiler.py |
# Get a permission denied error when running the script in the shell? chmod 755 the script .py file
import sys
import os
import subprocess
import shutil
import http.client, urllib
# COMIC_TAGGER_PATH = 'COMIC_TAGGER_PATH/Applications/ComicTagger.app/Contents/MacOS/ComicTagger'
COMIC_TAGGER_PATH = "C:\\Program Files... | 0.39712 | 0.14439 |
from __future__ import unicode_literals
from django.db import models, migrations
import fluent_contents.plugins.oembeditem.fields
class Migration(migrations.Migration):
dependencies = [
('fluent_contents', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='OEmbe... | icekit/plugins/oembed_with_caption/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import models, migrations
import fluent_contents.plugins.oembeditem.fields
class Migration(migrations.Migration):
dependencies = [
('fluent_contents', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='OEmbe... | 0.619126 | 0.15374 |
def viterbi(tags, sent, transition, emission):
lower_sent = [word.lower() for word in sent]
# In the Stanford pseudo-code, tag_probs is 'viterbi' and actual_tags is 'backpointer'
tag_probs = [{}]
actual_tags = [{}]
# Initialization step
for tag in tags:
# Multiply the probability that t... | viterbi.py | def viterbi(tags, sent, transition, emission):
lower_sent = [word.lower() for word in sent]
# In the Stanford pseudo-code, tag_probs is 'viterbi' and actual_tags is 'backpointer'
tag_probs = [{}]
actual_tags = [{}]
# Initialization step
for tag in tags:
# Multiply the probability that t... | 0.743634 | 0.560493 |
from datetime import datetime, timedelta
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
import clients.models as clients
import directory.models as directory
from appconf.manager impor... | health/views.py | from datetime import datetime, timedelta
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
import clients.models as clients
import directory.models as directory
from appconf.manager impor... | 0.442637 | 0.073264 |
import logging
from googleads import ad_manager
import settings
from dfp.client import get_client
from dfp.exceptions import (
BadSettingException,
DFPObjectNotFound,
MissingSettingException
)
logger = logging.getLogger(__name__)
def create_advertiser(name):
"""
Creates a DFP advertiser with name `name`... | dfp/get_advertisers.py |
import logging
from googleads import ad_manager
import settings
from dfp.client import get_client
from dfp.exceptions import (
BadSettingException,
DFPObjectNotFound,
MissingSettingException
)
logger = logging.getLogger(__name__)
def create_advertiser(name):
"""
Creates a DFP advertiser with name `name`... | 0.60743 | 0.088662 |
import base64
import json
import pytest
from pytest import fixture
from chalice import app
from chalice import NotFoundError
def create_event(uri, method, path, content_type='application/json'):
return {
'context': {
'http-method': method,
'resource-path': uri,
},
... | tests/unit/test_app.py | import base64
import json
import pytest
from pytest import fixture
from chalice import app
from chalice import NotFoundError
def create_event(uri, method, path, content_type='application/json'):
return {
'context': {
'http-method': method,
'resource-path': uri,
},
... | 0.506836 | 0.198938 |
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class PublishedTrackTestCase(IntegrationTestCase):
def test_fetch_request(self):
self.holodeck.mock(Response(500, ''))
with self.a... | tests/integration/video/v1/room/room_participant/test_room_participant_published_track.py | from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class PublishedTrackTestCase(IntegrationTestCase):
def test_fetch_request(self):
self.holodeck.mock(Response(500, ''))
with self.a... | 0.490236 | 0.402891 |
import os
import argparse
from copy import deepcopy
from pipeline import PipelineObject, PipelineStage, PipelineEngine
class SchemaTypeSlicer:
xpath_ns = {
"xs": "http://www.w3.org/2001/XMLSchema",
"acrn": "https://projectacrn.org",
}
@classmethod
def get_node(cls, element, xpath):
... | misc/config_tools/scenario_config/schema_slicer.py |
import os
import argparse
from copy import deepcopy
from pipeline import PipelineObject, PipelineStage, PipelineEngine
class SchemaTypeSlicer:
xpath_ns = {
"xs": "http://www.w3.org/2001/XMLSchema",
"acrn": "https://projectacrn.org",
}
@classmethod
def get_node(cls, element, xpath):
... | 0.613005 | 0.179028 |
import os
import sys
import time
import json
import os.path
import hashlib
import logging
import threading
from decimal import Decimal
from flask_socketio import SocketIO
from flask import Flask, render_template, url_for, request
from binance_api import api_master_rest_caller
from binance_api import api_master_socket_... | core/botCore.py | import os
import sys
import time
import json
import os.path
import hashlib
import logging
import threading
from decimal import Decimal
from flask_socketio import SocketIO
from flask import Flask, render_template, url_for, request
from binance_api import api_master_rest_caller
from binance_api import api_master_socket_... | 0.267026 | 0.081119 |
import os
import tempfile
import time
from collections import defaultdict
import pytest
from dagster import (
DagsterEventType,
Output,
OutputDefinition,
PipelineRun,
RetryRequested,
execute_pipeline,
execute_pipeline_iterator,
lambda_solid,
pipeline,
reconstructable,
reexec... | python_modules/dagster/dagster_tests/core_tests/execution_tests/test_retries.py | import os
import tempfile
import time
from collections import defaultdict
import pytest
from dagster import (
DagsterEventType,
Output,
OutputDefinition,
PipelineRun,
RetryRequested,
execute_pipeline,
execute_pipeline_iterator,
lambda_solid,
pipeline,
reconstructable,
reexec... | 0.417153 | 0.374905 |
"""End to end tests for TrainRunner."""
import datetime
import os
import shutil
from absl import flags
from dopamine.discrete_domains import train
import tensorflow.compat.v1 as tf
FLAGS = flags.FLAGS
class TrainRunnerIntegrationTest(tf.test.TestCase):
"""Tests for Atari environment with various agents.
""... | tests/dopamine/tests/train_runner_integration_test.py | """End to end tests for TrainRunner."""
import datetime
import os
import shutil
from absl import flags
from dopamine.discrete_domains import train
import tensorflow.compat.v1 as tf
FLAGS = flags.FLAGS
class TrainRunnerIntegrationTest(tf.test.TestCase):
"""Tests for Atari environment with various agents.
""... | 0.554229 | 0.316713 |
import asyncio
import random
import time
from types import SimpleNamespace
from typing import Union, List, Tuple
import aiohttp
from aiohttp import ClientSession, TraceRequestStartParams, TraceRequestEndParams
Number = Union[int, float]
class FlowController(aiohttp.TraceConfig):
def __init__(self,
... | scripts/flow_controller.py | import asyncio
import random
import time
from types import SimpleNamespace
from typing import Union, List, Tuple
import aiohttp
from aiohttp import ClientSession, TraceRequestStartParams, TraceRequestEndParams
Number = Union[int, float]
class FlowController(aiohttp.TraceConfig):
def __init__(self,
... | 0.668556 | 0.073065 |
from typing import Dict, List, Tuple, Set, NamedTuple, Optional
import csv, re, os, operator, sys
import xml.etree.ElementTree as ET
maxsize = sys.maxsize
while True:
try:
csv.field_size_limit(maxsize)
break
except OverflowError:
maxsize //= 2
# TYPES
class Row(NamedTuple):
guid... | ASJobGraphEvents/rebuild.py | from typing import Dict, List, Tuple, Set, NamedTuple, Optional
import csv, re, os, operator, sys
import xml.etree.ElementTree as ET
maxsize = sys.maxsize
while True:
try:
csv.field_size_limit(maxsize)
break
except OverflowError:
maxsize //= 2
# TYPES
class Row(NamedTuple):
guid... | 0.588534 | 0.309376 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import timedelta
import datetime
import csv
import math
from pyecharts.charts import Bar
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_selenium import snapshot
data=pd.read_... | 2021-02-03/code.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import timedelta
import datetime
import csv
import math
from pyecharts.charts import Bar
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_selenium import snapshot
data=pd.read_... | 0.031574 | 0.102574 |
import time
from owlracer.env import Env as Owlracer_Env
from owlracer import owlParser
def calculate_action(step_result, list):
distance_right = step_result.distance.right
distance_front_right = step_result.distance.frontRight
distance_left = step_result.distance.left
distance_front_left = step_resul... | examples/RuleBasedEngine.py | import time
from owlracer.env import Env as Owlracer_Env
from owlracer import owlParser
def calculate_action(step_result, list):
distance_right = step_result.distance.right
distance_front_right = step_result.distance.frontRight
distance_left = step_result.distance.left
distance_front_left = step_resul... | 0.408985 | 0.284806 |
import argparse
import ast
import json
import os
import re
import tqdm
from .simpledicomanonymizer import *
def anonymize(inputPath, outputPath, anonymizationActions):
# Get input arguments
InputFolder = ''
OutputFolder = ''
if os.path.isdir(inputPath):
InputFolder = inputPath
if os.path... | dicomanonymizer/anonymizer.py | import argparse
import ast
import json
import os
import re
import tqdm
from .simpledicomanonymizer import *
def anonymize(inputPath, outputPath, anonymizationActions):
# Get input arguments
InputFolder = ''
OutputFolder = ''
if os.path.isdir(inputPath):
InputFolder = inputPath
if os.path... | 0.162579 | 0.18321 |
from djmodels.core.exceptions import ObjectDoesNotExist
from djmodels.db.models import signals
from djmodels.db.models.aggregates import * # NOQA
from djmodels.db.models.aggregates import __all__ as aggregates_all
from djmodels.db.models.constraints import * # NOQA
from djmodels.db.models.constraints import __all__ a... | djmodels/db/models/__init__.py | from djmodels.core.exceptions import ObjectDoesNotExist
from djmodels.db.models import signals
from djmodels.db.models.aggregates import * # NOQA
from djmodels.db.models.aggregates import __all__ as aggregates_all
from djmodels.db.models.constraints import * # NOQA
from djmodels.db.models.constraints import __all__ a... | 0.638272 | 0.089335 |
import os
import cv2
import sys
import time
import math
import getopt
import numpy as np
import tensorflow as tf
import tensorflow.keras.backend as K
from utils import *
from glob import glob
from parser_test import parser
from TrackNet import ResNet_Track
from focal_loss import BinaryFocalLoss
from collections import ... | predict.py | import os
import cv2
import sys
import time
import math
import getopt
import numpy as np
import tensorflow as tf
import tensorflow.keras.backend as K
from utils import *
from glob import glob
from parser_test import parser
from TrackNet import ResNet_Track
from focal_loss import BinaryFocalLoss
from collections import ... | 0.242206 | 0.139396 |
import os
from sourcefile import SourceFile
import argparse
def main(url):
files = []
for root, directories, filenames in os.walk(url):
for filename in filenames:
file = SourceFile(os.path.join(root, filename))
files.append(file)
try:
print("Parsing ... | swearscan.py | import os
from sourcefile import SourceFile
import argparse
def main(url):
files = []
for root, directories, filenames in os.walk(url):
for filename in filenames:
file = SourceFile(os.path.join(root, filename))
files.append(file)
try:
print("Parsing ... | 0.201342 | 0.096663 |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import os
import functools
from torch.autograd import Variable
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
import math
class Mapping_Model_with_mask(nn.Module):
def __init__(se... | Global/models/NonLocal_feature_mapping_model.py |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import os
import functools
from torch.autograd import Variable
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
import math
class Mapping_Model_with_mask(nn.Module):
def __init__(se... | 0.803212 | 0.310524 |
import six
from flask_sqlalchemy import SQLAlchemy
from flask_inspektor import QueryInspector
from tests.base import FakeAppTestCase
class QueryInspectBasicTest(FakeAppTestCase):
def test_not_initialised_by_default(self):
# Bootstrap the extension.
QueryInspector(self.app)
# Default conf... | tests/test_extension.py | import six
from flask_sqlalchemy import SQLAlchemy
from flask_inspektor import QueryInspector
from tests.base import FakeAppTestCase
class QueryInspectBasicTest(FakeAppTestCase):
def test_not_initialised_by_default(self):
# Bootstrap the extension.
QueryInspector(self.app)
# Default conf... | 0.545165 | 0.287461 |
import os
import numpy as np
import tensorflow as tf
import dataIO as d
from tqdm import *
'''
Global Parameters
'''
n_epochs = 10
batch_size = 64
g_lr = 0.0025
d_lr = 0.00001
beta = 0.5
alpha_d = 0.0015
alpha_g = 0.000025
d_thresh = 0.8
z_size = 100
obj = 'chair'
train_sam... | src/3dgan.py | import os
import numpy as np
import tensorflow as tf
import dataIO as d
from tqdm import *
'''
Global Parameters
'''
n_epochs = 10
batch_size = 64
g_lr = 0.0025
d_lr = 0.00001
beta = 0.5
alpha_d = 0.0015
alpha_g = 0.000025
d_thresh = 0.8
z_size = 100
obj = 'chair'
train_sam... | 0.685002 | 0.361052 |
import os
import sys
import tvm
import argparse
import numpy as np
from tvm import te
from tvm import topi
from tvm import auto_scheduler
parser = argparse.ArgumentParser(description='tvm op test!')
parser.add_argument("--op", type=str, default="normalization", help="[reduce, element_wise, normalization]")
parser.add_... | op_benchmark/tvm_op_autosheduler.py | import os
import sys
import tvm
import argparse
import numpy as np
from tvm import te
from tvm import topi
from tvm import auto_scheduler
parser = argparse.ArgumentParser(description='tvm op test!')
parser.add_argument("--op", type=str, default="normalization", help="[reduce, element_wise, normalization]")
parser.add_... | 0.34798 | 0.215 |
from .algo import Algo
from .algo_code import AlgoCode
from .entity_slot import Slot
from .entity_space import Space
from . import log, show_adding_box_log, find_smallest
from .exception import DistributionException
import time
class AlgoSmallest(Algo):
"""
find the smallest bin
for a given amount of
bins.
... | binner/algo_smallest.py | from .algo import Algo
from .algo_code import AlgoCode
from .entity_slot import Slot
from .entity_space import Space
from . import log, show_adding_box_log, find_smallest
from .exception import DistributionException
import time
class AlgoSmallest(Algo):
"""
find the smallest bin
for a given amount of
bins.
... | 0.53777 | 0.282209 |
import numpy as np
import pandas as pd
import pytest
from typing import Type
from sklearn.datasets import load_wine, load_breast_cancer
from sklearn.ensemble import VotingClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, log_loss
from sklearn.pipeline import Pi... | tests/system/test_gamaclassifier.py | import numpy as np
import pandas as pd
import pytest
from typing import Type
from sklearn.datasets import load_wine, load_breast_cancer
from sklearn.ensemble import VotingClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, log_loss
from sklearn.pipeline import Pi... | 0.910439 | 0.407717 |
import clip
import torch
from PIL import Image
from multiprocessing import cpu_count
device = "cuda" if torch.cuda.is_available() else "cpu"
use_jit = torch.cuda.is_available() and '1.7.1' in torch.__version__
class CLIPDataset(torch.utils.data.Dataset):
def __init__(self, dataframe, preprocess):
self.dat... | clip_filter.py | import clip
import torch
from PIL import Image
from multiprocessing import cpu_count
device = "cuda" if torch.cuda.is_available() else "cpu"
use_jit = torch.cuda.is_available() and '1.7.1' in torch.__version__
class CLIPDataset(torch.utils.data.Dataset):
def __init__(self, dataframe, preprocess):
self.dat... | 0.591605 | 0.275191 |
import warnings
import numpy as np
from ...surface import _normalize_vectors
from ...utils import _import_mlab, _validate_type
class _Projection(object):
"""Class storing projection information.
Attributes
----------
xy : array
Result of 2d projection of 3d data.
pts : Source
May... | mne/viz/backends/_pysurfer_mayavi.py |
import warnings
import numpy as np
from ...surface import _normalize_vectors
from ...utils import _import_mlab, _validate_type
class _Projection(object):
"""Class storing projection information.
Attributes
----------
xy : array
Result of 2d projection of 3d data.
pts : Source
May... | 0.939941 | 0.552992 |
import os
import sys
file_dir = os.path.dirname(__file__)
sys.path.append(file_dir)
from http.server import BaseHTTPRequestHandler, HTTPServer
from intercom.client import Client
import generic
import sys
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import string
import webbrowser
... | src/server.py | import os
import sys
file_dir = os.path.dirname(__file__)
sys.path.append(file_dir)
from http.server import BaseHTTPRequestHandler, HTTPServer
from intercom.client import Client
import generic
import sys
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import string
import webbrowser
... | 0.119395 | 0.116337 |
from __future__ import annotations
import logging
from dataclasses import dataclass
from pathlib import Path
from typing import Any, ClassVar, Iterable, cast
from pants.base.build_environment import get_buildroot
from pants.base.build_root import BuildRoot
from pants.base.exiter import PANTS_SUCCEEDED_EXIT_CODE
from... | src/python/pants/init/engine_initializer.py |
from __future__ import annotations
import logging
from dataclasses import dataclass
from pathlib import Path
from typing import Any, ClassVar, Iterable, cast
from pants.base.build_environment import get_buildroot
from pants.base.build_root import BuildRoot
from pants.base.exiter import PANTS_SUCCEEDED_EXIT_CODE
from... | 0.864825 | 0.119024 |
import configparser
import os
import re
import sys
from contextlib import closing, contextmanager
import yaml
from . import base, utils
SubstituteRegex = re.compile(r"\$\{(?P<var>(\w|:)+)\}")
def load_config_arguments(args):
parser = utils.default_parser("config")
parser.add_argument("option", nargs="?", ... | src/doblib/env.py |
import configparser
import os
import re
import sys
from contextlib import closing, contextmanager
import yaml
from . import base, utils
SubstituteRegex = re.compile(r"\$\{(?P<var>(\w|:)+)\}")
def load_config_arguments(args):
parser = utils.default_parser("config")
parser.add_argument("option", nargs="?", ... | 0.470737 | 0.104706 |
from mathics.builtin.base import Builtin
from mathics.builtin.assignments.internals import get_symbol_values
from mathics.core.attributes import hold_all, protected
class DefaultValues(Builtin):
"""
<dl>
<dt>'DefaultValues[$symbol$]'
<dd>gives the list of default values associated with $symbol$.... | mathics/builtin/assignments/types.py | from mathics.builtin.base import Builtin
from mathics.builtin.assignments.internals import get_symbol_values
from mathics.core.attributes import hold_all, protected
class DefaultValues(Builtin):
"""
<dl>
<dt>'DefaultValues[$symbol$]'
<dd>gives the list of default values associated with $symbol$.... | 0.803328 | 0.425904 |
def to_molsysmt_DataFrame(item, trajectory_item=None, atom_indices='all', structure_indices='all'):
return item.dataframe
def from_molsysmt_DataFrame(item, trajectory_item=None, atom_indices='all', structure_indices='all'):
from molsysmt.native.topology import Topology
from molsysmt.native import element... | molsysmt/native/old/former_topology/io/topology/classes/molsysmt_DataFrame.py | def to_molsysmt_DataFrame(item, trajectory_item=None, atom_indices='all', structure_indices='all'):
return item.dataframe
def from_molsysmt_DataFrame(item, trajectory_item=None, atom_indices='all', structure_indices='all'):
from molsysmt.native.topology import Topology
from molsysmt.native import element... | 0.318803 | 0.448366 |
import sys
if sys.version_info.major >= 3 and sys.version_info.minor >= 5: # pragma: no cover
from typing import Union, List, Any
import troposphere.policies
from troposphere import Template, AWSHelperFn
from troposphere_mate.core.mate import preprocess_init_kwargs, Mixin
from troposphere_mate.core.sentiel impo... | troposphere_mate/policies.py | import sys
if sys.version_info.major >= 3 and sys.version_info.minor >= 5: # pragma: no cover
from typing import Union, List, Any
import troposphere.policies
from troposphere import Template, AWSHelperFn
from troposphere_mate.core.mate import preprocess_init_kwargs, Mixin
from troposphere_mate.core.sentiel impo... | 0.362179 | 0.21916 |
import cgi
import cgitb
import urllib
from oauth2client.client import OAuth2WebServerFlow
cgitb.enable()
SCOPE = 'https://www.googleapis.com/auth/drive.file'
AUTHORIZED_REDIRECT = "https://philosophyofpen.com/login/backup.py"
CLIENT_ID = 'TODO'
CLIENT_SECRET = 'TODO'
args = cgi.FieldStorage()
if 'redirectbacktoken' ... | server/www/html/backup.py | import cgi
import cgitb
import urllib
from oauth2client.client import OAuth2WebServerFlow
cgitb.enable()
SCOPE = 'https://www.googleapis.com/auth/drive.file'
AUTHORIZED_REDIRECT = "https://philosophyofpen.com/login/backup.py"
CLIENT_ID = 'TODO'
CLIENT_SECRET = 'TODO'
args = cgi.FieldStorage()
if 'redirectbacktoken' ... | 0.179279 | 0.062331 |
import tempfile
import shutil
import os
import logging
try:
import unittest2 as unittest
except ImportError:
import unittest
from repoman.depot_manager import DepotManager
from repoman.roster import Clone
FIXTURE_PATH = 'fixtures'
SELF_DIRECTORY_PATH = os.path.dirname(__file__)
logging.basicConfig()
class ... | tests/test_clonemanager.py |
import tempfile
import shutil
import os
import logging
try:
import unittest2 as unittest
except ImportError:
import unittest
from repoman.depot_manager import DepotManager
from repoman.roster import Clone
FIXTURE_PATH = 'fixtures'
SELF_DIRECTORY_PATH = os.path.dirname(__file__)
logging.basicConfig()
class ... | 0.488039 | 0.21307 |
import sys
import os
import json
current_dir = os.path.dirname(os.path.abspath(__file__))
U_JOIN = 0x200d
U_VARIATION_SELECTOR_16 = 0xfe0f
U_EXTRA = (U_JOIN, U_VARIATION_SELECTOR_16)
if sys.maxunicode == 0xFFFF:
# For ease of supporting, just require uniseq for both narrow and wide PY27.
def get_code_points(... | 3rdparty/pymdown-extensions/tools/gen_gemoji.py | import sys
import os
import json
current_dir = os.path.dirname(os.path.abspath(__file__))
U_JOIN = 0x200d
U_VARIATION_SELECTOR_16 = 0xfe0f
U_EXTRA = (U_JOIN, U_VARIATION_SELECTOR_16)
if sys.maxunicode == 0xFFFF:
# For ease of supporting, just require uniseq for both narrow and wide PY27.
def get_code_points(... | 0.444324 | 0.158858 |
from django.db import models
import uuid
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.utils.text import slugify
# Create your models here.
class DesignBaseClass(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False... | src/project/models.py | from django.db import models
import uuid
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.utils.text import slugify
# Create your models here.
class DesignBaseClass(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False... | 0.511229 | 0.103976 |
from pyrogram import Client, filters
from pyrogram.types import ReplyKeyboardMarkup
from pyrogram.types import ChatPermissions
import time
import asyncio
import os
app = Client(
"my_bot",
bot_token = "1940303458:<KEY>"
api_hash = "eb06d4abfb49dc3eeb1aeb98ae0f581e", ... | InfoKGbotBot.py | from pyrogram import Client, filters
from pyrogram.types import ReplyKeyboardMarkup
from pyrogram.types import ChatPermissions
import time
import asyncio
import os
app = Client(
"my_bot",
bot_token = "1940303458:<KEY>"
api_hash = "eb06d4abfb49dc3eeb1aeb98ae0f581e", ... | 0.215351 | 0.106784 |
import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data')
def model_inputs(real_dim, z_dim):
inputs_real = tf.placeholder(tf.float32, (None, real_dim), name='input_real')... | Chapter08/GAN.py | import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data')
def model_inputs(real_dim, z_dim):
inputs_real = tf.placeholder(tf.float32, (None, real_dim), name='input_real')... | 0.846594 | 0.438966 |
from abc import ABC, abstractmethod
import numpy as np
class Variable(ABC):
"""Variable class
"""
@abstractmethod
def validate(self):
"""Client must define it self"""
raise NotImplementedError("Client must define it self")
@abstractmethod
def get(self):
"""Client mus... | pyJaya/variables.py | from abc import ABC, abstractmethod
import numpy as np
class Variable(ABC):
"""Variable class
"""
@abstractmethod
def validate(self):
"""Client must define it self"""
raise NotImplementedError("Client must define it self")
@abstractmethod
def get(self):
"""Client mus... | 0.941801 | 0.44354 |
__author__ = 'yasensim'
import requests, time
try:
from com.vmware.nsx.model_client import Tag
from com.vmware.nsx.model_client import LogicalRouter
from com.vmware.nsx_client import LogicalRouters
from com.vmware.nsx.logical_routers.routing_client import StaticRoutes
from com.vmware.nsx.model_... | library/nsxt_static_route.py |
__author__ = 'yasensim'
import requests, time
try:
from com.vmware.nsx.model_client import Tag
from com.vmware.nsx.model_client import LogicalRouter
from com.vmware.nsx_client import LogicalRouters
from com.vmware.nsx.logical_routers.routing_client import StaticRoutes
from com.vmware.nsx.model_... | 0.288669 | 0.048994 |
import os, time
from flask import Flask, request, redirect, url_for, render_template, send_from_directory
from werkzeug.utils import secure_filename
import pandas as pd
import sqlite3
from datetime import datetime
UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'
DOWNLOAD_FOLDER = os... | flask_app.py | import os, time
from flask import Flask, request, redirect, url_for, render_template, send_from_directory
from werkzeug.utils import secure_filename
import pandas as pd
import sqlite3
from datetime import datetime
UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'
DOWNLOAD_FOLDER = os... | 0.135461 | 0.051893 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys, os, six, time, collections
from six.moves.urllib.error import HTTPError, URLError
from six.moves.urllib.request import urlopen, urlretrieve
import tarfile
from pathlib import Path
try:
import ... | phyaat/dataset.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys, os, six, time, collections
from six.moves.urllib.error import HTTPError, URLError
from six.moves.urllib.request import urlopen, urlretrieve
import tarfile
from pathlib import Path
try:
import ... | 0.26218 | 0.162845 |
import nltk
import json
import numpy as np
from collections import defaultdict
from nltk.probability import FreqDist
import getopt
import sys
class Search:
def __init__(self):
self.vector_sqr_sum = None
self.inverted_index = None
pass
def get_idf(self, total_documents, doc_freq):
... | src/Search.py | import nltk
import json
import numpy as np
from collections import defaultdict
from nltk.probability import FreqDist
import getopt
import sys
class Search:
def __init__(self):
self.vector_sqr_sum = None
self.inverted_index = None
pass
def get_idf(self, total_documents, doc_freq):
... | 0.278061 | 0.241176 |
import torch
from torch.optim.lr_scheduler import LambdaLR, _LRScheduler
import torchvision.utils as vutils
import torch.distributed as dist
import errno
import os
import re
import sys
import numpy as np
from bisect import bisect_right
num_gpus = int(os.environ["WORLD_SIZE"]) if "WORLD_SIZE" in os.environ else 1
is_... | utils/utils.py | import torch
from torch.optim.lr_scheduler import LambdaLR, _LRScheduler
import torchvision.utils as vutils
import torch.distributed as dist
import errno
import os
import re
import sys
import numpy as np
from bisect import bisect_right
num_gpus = int(os.environ["WORLD_SIZE"]) if "WORLD_SIZE" in os.environ else 1
is_... | 0.479991 | 0.403214 |
# 1.0 import modules
# data I/O
import sys
import os
# scientific
import numpy as np
# Image processing
import cv2 as cv
# skimage
from skimage import io
from skimage.morphology import disk, white_tophat
from skimage.filters import median, gaussian
from skimage.restoration import denoise_wavelet
from skimage.exposure... | tests/test_CurlypivPIV_onImages.py | # 1.0 import modules
# data I/O
import sys
import os
# scientific
import numpy as np
# Image processing
import cv2 as cv
# skimage
from skimage import io
from skimage.morphology import disk, white_tophat
from skimage.filters import median, gaussian
from skimage.restoration import denoise_wavelet
from skimage.exposure... | 0.226527 | 0.300816 |
from collections import OrderedDict
from typing import Dict, List, Optional, Set
import casbin
from graphql.execution.base import ResolveInfo
from graphql.language.ast import Field, FragmentDefinition, FragmentSpread
from graphql.type.definition import GraphQLList, GraphQLNonNull
from graphql.type.schema import GraphQL... | server/api_graphql/crud.py | from collections import OrderedDict
from typing import Dict, List, Optional, Set
import casbin
from graphql.execution.base import ResolveInfo
from graphql.language.ast import Field, FragmentDefinition, FragmentSpread
from graphql.type.definition import GraphQLList, GraphQLNonNull
from graphql.type.schema import GraphQL... | 0.74382 | 0.14262 |
from abc import abstractmethod
from sqlalchemy import Column, event, ForeignKey, Integer, String, VARBINARY
from sqlalchemy import Boolean
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm import relationship
import binascii
import six
from kmip.core import enums
from kmip.pie import ... | kmip/pie/objects.py |
from abc import abstractmethod
from sqlalchemy import Column, event, ForeignKey, Integer, String, VARBINARY
from sqlalchemy import Boolean
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm import relationship
import binascii
import six
from kmip.core import enums
from kmip.pie import ... | 0.866048 | 0.347842 |
from bigml.tree_utils import INDENT
from bigml.generators.model import PYTHON_OPERATOR, missing_branch, \
none_value
from bigml.predict_utils.common import mintree_split, get_predicate, get_node
from bigml.predict_utils.common import OPERATION_OFFSET, FIELD_OFFSET, \
VALUE_OFFSET, MISSING_OFFSET
from bigml.gene... | bigmler/export/out_tree/mysqltree.py | from bigml.tree_utils import INDENT
from bigml.generators.model import PYTHON_OPERATOR, missing_branch, \
none_value
from bigml.predict_utils.common import mintree_split, get_predicate, get_node
from bigml.predict_utils.common import OPERATION_OFFSET, FIELD_OFFSET, \
VALUE_OFFSET, MISSING_OFFSET
from bigml.gene... | 0.588298 | 0.265577 |
import random
import pygame,sys
from pygame.locals import *
import constant as const
#Declaring a key press inventory
key = {
const.DIRT : K_1,
const.GRASS : K_2,
const.WATER : K_3,
const.COAL : K_4,
const.ROCK : K_5,
const.LAVA : K_6
}
#Declaring an inventory
inventory = {
const.DIRT : 0,
const.GRASS : 0,
... | mineython.py | import random
import pygame,sys
from pygame.locals import *
import constant as const
#Declaring a key press inventory
key = {
const.DIRT : K_1,
const.GRASS : K_2,
const.WATER : K_3,
const.COAL : K_4,
const.ROCK : K_5,
const.LAVA : K_6
}
#Declaring an inventory
inventory = {
const.DIRT : 0,
const.GRASS : 0,
... | 0.156975 | 0.293848 |
from .Compatibility import Compatibility as c
from ftplib import FTP
import ftplib, time
class FtpObject():
def __init__(self, log = True, ftp_config = None):
self.log = log
self.ftp_config = ftp_config
# FTP connect
self.ftp = FTP(self.ftp_config.hostname, self.ftp_config.userna... | bebackup/FtpObject.py | from .Compatibility import Compatibility as c
from ftplib import FTP
import ftplib, time
class FtpObject():
def __init__(self, log = True, ftp_config = None):
self.log = log
self.ftp_config = ftp_config
# FTP connect
self.ftp = FTP(self.ftp_config.hostname, self.ftp_config.userna... | 0.200636 | 0.071689 |
from openstack import proxy
from otcextensions.sdk.auto_scaling.v1 import activity as _activity
from otcextensions.sdk.auto_scaling.v1 import config as _config
from otcextensions.sdk.auto_scaling.v1 import group as _group
from otcextensions.sdk.auto_scaling.v1 import instance as _instance
from otcextensions.sdk.auto_sc... | otcextensions/sdk/auto_scaling/v1/_proxy.py | from openstack import proxy
from otcextensions.sdk.auto_scaling.v1 import activity as _activity
from otcextensions.sdk.auto_scaling.v1 import config as _config
from otcextensions.sdk.auto_scaling.v1 import group as _group
from otcextensions.sdk.auto_scaling.v1 import instance as _instance
from otcextensions.sdk.auto_sc... | 0.868158 | 0.30551 |
def mined_sentences(alignments, scores, src_file, tgt_file, src_file_lines, tgt_file_lines):
with open(src_file, encoding='utf-8-sig') as source:
source_lines_prep = source.readlines()
with open(tgt_file, encoding='utf-8-sig') as target:
target_lines_prep = target.readlines()
with open(src_f... | extract_sentences.py | def mined_sentences(alignments, scores, src_file, tgt_file, src_file_lines, tgt_file_lines):
with open(src_file, encoding='utf-8-sig') as source:
source_lines_prep = source.readlines()
with open(tgt_file, encoding='utf-8-sig') as target:
target_lines_prep = target.readlines()
with open(src_f... | 0.071607 | 0.279232 |
from json import JSONDecodeError
from queue import Queue
from random import choice
from re import fullmatch
from string import ascii_lowercase
from threading import Thread
from time import sleep, time
from thingsboard_gateway.tb_utility.tb_loader import TBModuleLoader
from thingsboard_gateway.tb_utility.tb_utility im... | thingsboard_gateway/connectors/request/request_connector.py |
from json import JSONDecodeError
from queue import Queue
from random import choice
from re import fullmatch
from string import ascii_lowercase
from threading import Thread
from time import sleep, time
from thingsboard_gateway.tb_utility.tb_loader import TBModuleLoader
from thingsboard_gateway.tb_utility.tb_utility im... | 0.288068 | 0.049543 |
# standard library
import json
from typing import Optional, Union
# first-party
from tcex.api.tc.v3.api_endpoints import ApiEndpoints
from tcex.api.tc.v3.object_abc import ObjectABC
from tcex.api.tc.v3.object_collection_abc import ObjectCollectionABC
from tcex.api.tc.v3.tags.tag_filter import TagFilter
from tcex.api.t... | tcex/api/tc/v3/tags/tag.py | # standard library
import json
from typing import Optional, Union
# first-party
from tcex.api.tc.v3.api_endpoints import ApiEndpoints
from tcex.api.tc.v3.object_abc import ObjectABC
from tcex.api.tc.v3.object_collection_abc import ObjectCollectionABC
from tcex.api.tc.v3.tags.tag_filter import TagFilter
from tcex.api.t... | 0.91602 | 0.225833 |
import sys, numpy
from numpy import sin, cos, log10, log2, sqrt, pi
from scipy.special import jv as besselj
sys.path.insert(0,'../Stage_0/')
from conversions import *
#====================================================================
# aux thruster information
#=====================================================... | src/Python/Stage_1/component_classes.py | import sys, numpy
from numpy import sin, cos, log10, log2, sqrt, pi
from scipy.special import jv as besselj
sys.path.insert(0,'../Stage_0/')
from conversions import *
#====================================================================
# aux thruster information
#=====================================================... | 0.231354 | 0.11474 |
from sklearn.base import TransformerMixin, BaseEstimator
from docplex.mp.constants import ObjectiveSense
from docplex.mp.advmodel import AdvModel
from docplex.mp.utils import *
import numpy as np
from pandas import DataFrame
class CplexTransformerBase(BaseEstimator, TransformerMixin):
""" Root cl... | ukpsummarizer-be/cplex/python/docplex/docplex/mp/sktrans/transformers.py |
from sklearn.base import TransformerMixin, BaseEstimator
from docplex.mp.constants import ObjectiveSense
from docplex.mp.advmodel import AdvModel
from docplex.mp.utils import *
import numpy as np
from pandas import DataFrame
class CplexTransformerBase(BaseEstimator, TransformerMixin):
""" Root cl... | 0.865452 | 0.330188 |
import logging
from ops.framework import (
StoredState,
EventBase,
ObjectEvents,
EventSource,
Object)
class HasPeersEvent(EventBase):
pass
class ReadyPeersEvent(EventBase):
pass
class CephBenchmarkingPeerEvents(ObjectEvents):
has_peers = EventSource(HasPeersEvent)
ready_peers... | src/interface_ceph_benchmarking_peers.py |
import logging
from ops.framework import (
StoredState,
EventBase,
ObjectEvents,
EventSource,
Object)
class HasPeersEvent(EventBase):
pass
class ReadyPeersEvent(EventBase):
pass
class CephBenchmarkingPeerEvents(ObjectEvents):
has_peers = EventSource(HasPeersEvent)
ready_peers... | 0.71721 | 0.090133 |
from Jumpscale import j
import binascii
from io import BytesIO
import json
import os
from JumpscaleLibs.servers.mail.smtp import app
from JumpscaleLibs.servers.mail.imap.bcdbmailbox import BCDBMailboxdir
class mail(j.baseclasses.threebot_actor):
def _init(self, **kwargs):
models = j.servers.imap.get_mode... | ThreeBotPackages/threebot/mail/actors/mail.py | from Jumpscale import j
import binascii
from io import BytesIO
import json
import os
from JumpscaleLibs.servers.mail.smtp import app
from JumpscaleLibs.servers.mail.imap.bcdbmailbox import BCDBMailboxdir
class mail(j.baseclasses.threebot_actor):
def _init(self, **kwargs):
models = j.servers.imap.get_mode... | 0.52756 | 0.540257 |
from errno import EEXIST
import os
from os.path import exists, expanduser, join
import pandas as pd
def hidden(path):
"""Check if a path is hidden.
Parameters
----------
path : str
A filepath.
"""
return os.path.split(path)[1].startswith('.')
def ensure_directory(path):
"""
... | zipline/utils/paths.py | from errno import EEXIST
import os
from os.path import exists, expanduser, join
import pandas as pd
def hidden(path):
"""Check if a path is hidden.
Parameters
----------
path : str
A filepath.
"""
return os.path.split(path)[1].startswith('.')
def ensure_directory(path):
"""
... | 0.827515 | 0.444384 |