code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import argparse import logging import typing from dataclasses import dataclass import telegram import telegram.ext import cotd.storage @dataclass class Options(argparse.Namespace): log_level: str version: str group: int mode: str db: int @dataclass class Flags(argparse.Namespace): feature_...
cotd/service.py
import argparse import logging import typing from dataclasses import dataclass import telegram import telegram.ext import cotd.storage @dataclass class Options(argparse.Namespace): log_level: str version: str group: int mode: str db: int @dataclass class Flags(argparse.Namespace): feature_...
0.668556
0.144209
from pathlib import Path from vectorseq.pipeline.stages import ExpressionPlots from vectorseq.pipeline import ExpressionPlotsPipeline from vectorseq.utils import create_dir from vectorseq.marker_constants import VentralMidbrainGenes data_dir = Path("/spare_volume/vectorseq-data") experiment_id = "3382" brain_region = ...
scripts/figures/3382_snr_expression_plots.py
from pathlib import Path from vectorseq.pipeline.stages import ExpressionPlots from vectorseq.pipeline import ExpressionPlotsPipeline from vectorseq.utils import create_dir from vectorseq.marker_constants import VentralMidbrainGenes data_dir = Path("/spare_volume/vectorseq-data") experiment_id = "3382" brain_region = ...
0.749912
0.26011
import argparse import fcntl import logging import os from contextlib import contextmanager import torch import torch.nn.functional as F import torchvision import poptorch import popdist import popdist.poptorch import horovod.torch as hvd class ModelWithLoss(torch.nn.Module): def __init__(self): super()....
feature_examples/pytorch/popdist/popdist_training.py
import argparse import fcntl import logging import os from contextlib import contextmanager import torch import torch.nn.functional as F import torchvision import poptorch import popdist import popdist.poptorch import horovod.torch as hvd class ModelWithLoss(torch.nn.Module): def __init__(self): super()....
0.789477
0.32168
import precis_i18n.baseclass as _base import precis_i18n.profile as _profile import precis_i18n.unicode as _unicode def _factory(profile, **kwds): def _construct(ucd): return profile(ucd, **kwds) return _construct _PROFILES = { 'identifierclass': _factory(_base.IdentifierClass, name='Ident...
precis_i18n/factory.py
import precis_i18n.baseclass as _base import precis_i18n.profile as _profile import precis_i18n.unicode as _unicode def _factory(profile, **kwds): def _construct(ucd): return profile(ucd, **kwds) return _construct _PROFILES = { 'identifierclass': _factory(_base.IdentifierClass, name='Ident...
0.715821
0.076167
import re import jax.numpy as jnp import numpy as np import pytest from pgmax import fgroup, vgroup def test_single_factor(): with pytest.raises(ValueError, match="Cannot create a FactorGroup with no Factor."): fgroup.ORFactorGroup(variables_for_factors=[]) A = vgroup.NDVarArray(num_states=2, shape...
tests/fgroup/test_fgroup.py
import re import jax.numpy as jnp import numpy as np import pytest from pgmax import fgroup, vgroup def test_single_factor(): with pytest.raises(ValueError, match="Cannot create a FactorGroup with no Factor."): fgroup.ORFactorGroup(variables_for_factors=[]) A = vgroup.NDVarArray(num_states=2, shape...
0.660939
0.500183
import datetime from typing import Iterator, Tuple import os import secrets import numpy as np import tensorflow as tf import tree from slippi_ai import data, utils, embed from slippi_ai.learner import Learner def get_experiment_tag(): today = datetime.date.today() return f'{today.year}-{today.month}-{today.day}...
slippi_ai/train_lib.py
import datetime from typing import Iterator, Tuple import os import secrets import numpy as np import tensorflow as tf import tree from slippi_ai import data, utils, embed from slippi_ai.learner import Learner def get_experiment_tag(): today = datetime.date.today() return f'{today.year}-{today.month}-{today.day}...
0.801042
0.224427
__author__ = '<EMAIL> (<NAME>)' import sys import os from CoreGraphics import * def Usage (): print """ Usage: splitPDF.py inputFN splitPageNum1 splitPageNum2 ... - inputFN: the path to the input pdf file. - splitPageNum1, ...: each one is a positive integer; the numbers must not exceed the number ...
Python/files/splitPDF.py
__author__ = '<EMAIL> (<NAME>)' import sys import os from CoreGraphics import * def Usage (): print """ Usage: splitPDF.py inputFN splitPageNum1 splitPageNum2 ... - inputFN: the path to the input pdf file. - splitPageNum1, ...: each one is a positive integer; the numbers must not exceed the number ...
0.164752
0.261393
import re import time from deoplete.source.base import Base LSP_KINDS = [ 'Text', 'Method', 'Function', 'Constructor', 'Field', 'Variable', 'Class', 'Interface', 'Module', 'Property', 'Unit', 'Value', 'Enum', 'Keyword', 'Snippet', 'Color', 'File', ...
rplugin/python3/deoplete/sources/vim_lsp.py
import re import time from deoplete.source.base import Base LSP_KINDS = [ 'Text', 'Method', 'Function', 'Constructor', 'Field', 'Variable', 'Class', 'Interface', 'Module', 'Property', 'Unit', 'Value', 'Enum', 'Keyword', 'Snippet', 'Color', 'File', ...
0.264833
0.063308
import json import os import subprocess from typing import Dict, List, Optional, Tuple from .util import download_file class Trombone: def __init__(self, jar_path: Optional[str] = None): if jar_path is None: jar_path = '/tmp/trombone.jar' if not os.path.exists(jar_path): ...
pytrombone/wrapper.py
import json import os import subprocess from typing import Dict, List, Optional, Tuple from .util import download_file class Trombone: def __init__(self, jar_path: Optional[str] = None): if jar_path is None: jar_path = '/tmp/trombone.jar' if not os.path.exists(jar_path): ...
0.68458
0.180576
from transformers import GPT2Tokenizer, GPT2LMHeadModel import random import os import argparse def parse_arguments(): """ Parser. """ parser = argparse.ArgumentParser() parser.add_argument("--model_path", type=str, default="belgpt2", ...
scripts/tools/generate_text.py
from transformers import GPT2Tokenizer, GPT2LMHeadModel import random import os import argparse def parse_arguments(): """ Parser. """ parser = argparse.ArgumentParser() parser.add_argument("--model_path", type=str, default="belgpt2", ...
0.703142
0.252303
import pandas as pd import numpy as np import math import scipy.stats as stats import statsmodels.stats.api as sms def inter_p_value(p_value): # interpretation if p_value >= 0 and p_value < 0.01: inter_p = 'Overwhelming Evidence' elif p_value >= 0.01 and p_value < 0.05: inter_p = 'Strong E...
mgt2001/hyp/ind.py
import pandas as pd import numpy as np import math import scipy.stats as stats import statsmodels.stats.api as sms def inter_p_value(p_value): # interpretation if p_value >= 0 and p_value < 0.01: inter_p = 'Overwhelming Evidence' elif p_value >= 0.01 and p_value < 0.05: inter_p = 'Strong E...
0.436622
0.471284
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import io import sys import glob import argparse from datetime import datetime from collections import OrderedDict import numpy as np import pandas as pd import scipy.io as sio import tensorflow as t...
train/embeddings.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import io import sys import glob import argparse from datetime import datetime from collections import OrderedDict import numpy as np import pandas as pd import scipy.io as sio import tensorflow as t...
0.718594
0.425725
import asyncio import shlex import subprocess import sys import weakref from typing import Mapping, Sequence from .. import utils from ..core.formatter import FormattedEntity from .base import Worker class Subprocess(FormattedEntity, Worker): """ config: cmd: str - shell command with mask python form...
aioworkers/worker/subprocess.py
import asyncio import shlex import subprocess import sys import weakref from typing import Mapping, Sequence from .. import utils from ..core.formatter import FormattedEntity from .base import Worker class Subprocess(FormattedEntity, Worker): """ config: cmd: str - shell command with mask python form...
0.359252
0.074064
import torch from torch import nn class Model(nn.Module): def __init__(self): super().__init__() self._conv_part = nn.Sequential( nn.Conv2d(3, 6, 5, padding=2), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(6, 16, 5), nn.ReLU(), nn.Ma...
model.py
import torch from torch import nn class Model(nn.Module): def __init__(self): super().__init__() self._conv_part = nn.Sequential( nn.Conv2d(3, 6, 5, padding=2), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(6, 16, 5), nn.ReLU(), nn.Ma...
0.939102
0.416441
import numpy class Dummy(): def __init__(self): '''nothing to do here''' def calc_pm1(self, exp_vars): return self.__sum_exp_vars(exp_vars) def calc_pm2(self, exp_vars): return self.__sum_exp_vars(exp_vars) * 2 def calc_pm10(self, exp_vars): return self.__sum_e...
emat/model/core_python/core_python_examples.py
import numpy class Dummy(): def __init__(self): '''nothing to do here''' def calc_pm1(self, exp_vars): return self.__sum_exp_vars(exp_vars) def calc_pm2(self, exp_vars): return self.__sum_exp_vars(exp_vars) * 2 def calc_pm10(self, exp_vars): return self.__sum_e...
0.776369
0.421135
import abc import typing class Query(abc.ABC): __slots__ = ["token", "token_type"] def __init__(self, token: str, token_type: str): self.token = token self.token_type = token_type @abc.abstractmethod def channel(self, snonwflake: int) -> typing.Dict: """Interface for the REST...
zenora/base/query.py
import abc import typing class Query(abc.ABC): __slots__ = ["token", "token_type"] def __init__(self, token: str, token_type: str): self.token = token self.token_type = token_type @abc.abstractmethod def channel(self, snonwflake: int) -> typing.Dict: """Interface for the REST...
0.805326
0.405743
"""ASGI server.""" import argparse import os import sys import uvicorn from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, PlainTextResponse, Response from projects import __version__, api from projects.database import init_db from projects.exceptions import ( BadRequest, Forbidde...
projects/api/main.py
"""ASGI server.""" import argparse import os import sys import uvicorn from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, PlainTextResponse, Response from projects import __version__, api from projects.database import init_db from projects.exceptions import ( BadRequest, Forbidde...
0.560012
0.069605
import os import subprocess import sys import tempfile import uuid import zipfile from collections import Iterable import requests from defusedxml.lxml import fromstring from lxml import etree from pypandoc import get_pandoc_path from docmaker.hooks import Hook THEME_COLORS = ( "dk1", "lt1", "dk2", ...
docmaker/features/theme.py
import os import subprocess import sys import tempfile import uuid import zipfile from collections import Iterable import requests from defusedxml.lxml import fromstring from lxml import etree from pypandoc import get_pandoc_path from docmaker.hooks import Hook THEME_COLORS = ( "dk1", "lt1", "dk2", ...
0.149904
0.061537
import numpy as np import pandas as pd import hashlib CHUNK_SIZE = 4096 # Required metadata fields - everything else goes into a json META_NAMES = ["ChannelIndex", "Slice", "FrameIndex", "Channel", "FileName", "PositionIndex"] DF_NAMES = ["channe...
imaging_db/utils/meta_utils.py
import numpy as np import pandas as pd import hashlib CHUNK_SIZE = 4096 # Required metadata fields - everything else goes into a json META_NAMES = ["ChannelIndex", "Slice", "FrameIndex", "Channel", "FileName", "PositionIndex"] DF_NAMES = ["channe...
0.698844
0.536556
STATE_SYSTEM = { 'UNAVAILABLE': 0x00000001, # ะ•ัะปะธ ัั‚ะพั‚ ะฑะธั‚ ะฒ ะฟะพะปะต state ะบะฝะพะฟะบะธ 0, ั‚ะพ ั‚ะตะบัั‚ ะบะฝะพะฟะบะธ ะบั€ะฐัะฝั‹ะน (ะบ ะฟั€ะธะผะตั€ัƒ, ั€ะตั‡ัŒ ะพ ะบะฝะพะฟะบะต Applay) 'SELECTED': 0x00000002, 'FOCUSED': 0x00000004, 'PRESSED': 0x00000008, 'CHECKED': 0x00000010, 'MIXED': 0x00000...
pikuli/uia/adapter/oleacc_h.py
STATE_SYSTEM = { 'UNAVAILABLE': 0x00000001, # ะ•ัะปะธ ัั‚ะพั‚ ะฑะธั‚ ะฒ ะฟะพะปะต state ะบะฝะพะฟะบะธ 0, ั‚ะพ ั‚ะตะบัั‚ ะบะฝะพะฟะบะธ ะบั€ะฐัะฝั‹ะน (ะบ ะฟั€ะธะผะตั€ัƒ, ั€ะตั‡ัŒ ะพ ะบะฝะพะฟะบะต Applay) 'SELECTED': 0x00000002, 'FOCUSED': 0x00000004, 'PRESSED': 0x00000008, 'CHECKED': 0x00000010, 'MIXED': 0x00000...
0.198996
0.134151
from typing import Any, Dict, List, Union from unittest.mock import patch from sqlmodel import create_engine from tests.conftest import get_testing_print_function def check_calls(calls: List[List[Union[str, Dict[str, Any]]]]): assert calls[0] == ["Before interacting with the database"] assert calls[1] == [ ...
tests/test_tutorial/test_automatic_id_none_refresh/test_tutorial001_tutorial002.py
from typing import Any, Dict, List, Union from unittest.mock import patch from sqlmodel import create_engine from tests.conftest import get_testing_print_function def check_calls(calls: List[List[Union[str, Dict[str, Any]]]]): assert calls[0] == ["Before interacting with the database"] assert calls[1] == [ ...
0.77569
0.584093
import itertools import numpy import networkx as nx from Queue import Queue def graph_symmetries(graph): """ Finds all symmetries of a graph. This is computationally very expensive O(N!) where N is the number of nodes in graph. """ permutations = [dict(zip(graph.nodes_iter(), perm)) for perm in ...
meb/utils/network/algorithms.py
import itertools import numpy import networkx as nx from Queue import Queue def graph_symmetries(graph): """ Finds all symmetries of a graph. This is computationally very expensive O(N!) where N is the number of nodes in graph. """ permutations = [dict(zip(graph.nodes_iter(), perm)) for perm in ...
0.598782
0.525491
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Creat...
django_server/holvi_orders/migrations/0001_initial.py
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Creat...
0.533641
0.120698
from app.setup import db, msmlw from datetime import datetime class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) password = db.Column(db.String(255), nullable=False) created_at = db.Column(db.DateTime, nullable=False, ...
docker/flask/app/app/model/users.py
from app.setup import db, msmlw from datetime import datetime class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) password = db.Column(db.String(255), nullable=False) created_at = db.Column(db.DateTime, nullable=False, ...
0.437103
0.071397
import os import logger from utils import dict_from_file def state_helper(def_state: dict, path: dict, log) -> tuple: no_ini = not os.path.isfile(path['settings']) no_state = not os.path.isfile(path['state']) if no_state and no_ini: return def_state, True, True ini_version, merge, state_save...
src/lib/state_helper.py
import os import logger from utils import dict_from_file def state_helper(def_state: dict, path: dict, log) -> tuple: no_ini = not os.path.isfile(path['settings']) no_state = not os.path.isfile(path['state']) if no_state and no_ini: return def_state, True, True ini_version, merge, state_save...
0.210604
0.175432
import logging import os from abc import ABC from dataclasses import dataclass from typing import List import numpy as np import onnx import pyeddl.eddl as eddl import stringcase from pyeddl.tensor import Tensor from slaid.commons.base import ImageInfo from slaid.models import Factory as BaseFactory from slaid.models...
slaid/models/eddl.py
import logging import os from abc import ABC from dataclasses import dataclass from typing import List import numpy as np import onnx import pyeddl.eddl as eddl import stringcase from pyeddl.tensor import Tensor from slaid.commons.base import ImageInfo from slaid.models import Factory as BaseFactory from slaid.models...
0.745954
0.364495
import numpy as np from kalman_estimation import (Kalman4ARX, Kalman4FROLS, Selector, get_mat_data, get_terms_matrix, get_txt_data, make_func4K4FROLS, make_linear_func, plot_term_ERR, save_3Darray, torch4FROLS, update_condidate_terms, save_2Darray) def update_terms(data_root='data/', d...
tools/core_tools1.py
import numpy as np from kalman_estimation import (Kalman4ARX, Kalman4FROLS, Selector, get_mat_data, get_terms_matrix, get_txt_data, make_func4K4FROLS, make_linear_func, plot_term_ERR, save_3Darray, torch4FROLS, update_condidate_terms, save_2Darray) def update_terms(data_root='data/', d...
0.414425
0.399402
from django.shortcuts import render # Create your views here. def view_signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() current_site = get_current_site(request) ...
ehelp/accounts/views.py
from django.shortcuts import render # Create your views here. def view_signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() current_site = get_current_site(request) ...
0.387459
0.078713
from simframe.frame.abstractgroup import AbstractGroup from simframe.frame.field import Field from simframe.frame.group import Group from simframe.io.reader import Reader from simframe.io.writer import Writer from simframe.utils.color import colorize from collections import deque import copy import numbers import nump...
simframe/io/writers/namespacewriter.py
from simframe.frame.abstractgroup import AbstractGroup from simframe.frame.field import Field from simframe.frame.group import Group from simframe.io.reader import Reader from simframe.io.writer import Writer from simframe.utils.color import colorize from collections import deque import copy import numbers import nump...
0.810479
0.259591
from .rule import Antecedent from ..betha_node import BethaNode from ..alpha_node import AlphaNode from ..rete import Rete from abc import abstractmethod from .run_agenda_action import RunAgendaAction from .add_fact_agenda_action import AddFactAgendaAction from .assert_fact_action import AssertFactAction from .retract_...
pbesa/engine/ps/psagent/psagent.py
from .rule import Antecedent from ..betha_node import BethaNode from ..alpha_node import AlphaNode from ..rete import Rete from abc import abstractmethod from .run_agenda_action import RunAgendaAction from .add_fact_agenda_action import AddFactAgendaAction from .assert_fact_action import AssertFactAction from .retract_...
0.433981
0.201558
from model.knowledgegraph import kg_derive_facts def load_lg_facts(conn, query): """ loads triple-based facts from a SemMedDB and builds the corresponding idx_pmid idx_pmid stores a idx_subject and a idx_object for each pmid from the query result the indices store which (subject -> [object1, ..., obje...
model/librarygraph.py
from model.knowledgegraph import kg_derive_facts def load_lg_facts(conn, query): """ loads triple-based facts from a SemMedDB and builds the corresponding idx_pmid idx_pmid stores a idx_subject and a idx_object for each pmid from the query result the indices store which (subject -> [object1, ..., obje...
0.806929
0.500244
import argparse import pickle import random from copy import copy from typing import List import numpy as np from hfo import GOAL, IN_GAME, CAPTURED_BY_DEFENSE, OUT_OF_TIME, OUT_OF_BOUNDS import settings from agents.utils import ServerDownError, get_vertices_around_ball from agents.plastic_v1.base.hfo_attacking_playe...
agents/plastic_v1/train_offline.py
import argparse import pickle import random from copy import copy from typing import List import numpy as np from hfo import GOAL, IN_GAME, CAPTURED_BY_DEFENSE, OUT_OF_TIME, OUT_OF_BOUNDS import settings from agents.utils import ServerDownError, get_vertices_around_ball from agents.plastic_v1.base.hfo_attacking_playe...
0.605333
0.134435
import numpy from numba import autojit @autojit(nopython=True) def poisson1d_GS_SingleItr(nx, dx, p, b): ''' Gauss-Seidel method for 1D Poisson eq. with Dirichlet BCs at both ends. Only a single iteration is executed. **blitz** is used. Parameters: ---------- nx: int, number of grid point...
lessons/05_relax/multigrid_helper.py
import numpy from numba import autojit @autojit(nopython=True) def poisson1d_GS_SingleItr(nx, dx, p, b): ''' Gauss-Seidel method for 1D Poisson eq. with Dirichlet BCs at both ends. Only a single iteration is executed. **blitz** is used. Parameters: ---------- nx: int, number of grid point...
0.84869
0.749294
import requests import logging class kotsms: def __init__(self): self.API_URL = "https://api2.kotsms.com.tw/kotsmsapi-2.php" self.API_POINT_URL = "https://api.kotsms.com.tw/memberpoint.php" def login(self, username, passwd): self.USERNAME = username self.PASSWORD = <PASSWORD> ...
kotsms.py
import requests import logging class kotsms: def __init__(self): self.API_URL = "https://api2.kotsms.com.tw/kotsmsapi-2.php" self.API_POINT_URL = "https://api.kotsms.com.tw/memberpoint.php" def login(self, username, passwd): self.USERNAME = username self.PASSWORD = <PASSWORD> ...
0.283285
0.147187
import base64 import os import random import re import string import time import xml.sax.saxutils import requests.exceptions as req_exc from libs import jenkinslib, quik from .BasePlugin import BasePlugin, HijackStdOut class NonCriticalException(Exception): pass def xmlescape(data): return xml.sax.saxuti...
libs/JAF/plugin_DumpCredsViaJob.py
import base64 import os import random import re import string import time import xml.sax.saxutils import requests.exceptions as req_exc from libs import jenkinslib, quik from .BasePlugin import BasePlugin, HijackStdOut class NonCriticalException(Exception): pass def xmlescape(data): return xml.sax.saxuti...
0.294925
0.215258
import os import json import torch import torch.nn as nn import torch.nn.functional as F from .modules import ( TextEncoder, DurationPredictor, RangeParameterPredictor, GaussianUpsampling, SamplingWindow, ) from wavegrad import WaveGrad from utils.tools import get_mask_from_lengths ...
model/WaveGrad2.py
import os import json import torch import torch.nn as nn import torch.nn.functional as F from .modules import ( TextEncoder, DurationPredictor, RangeParameterPredictor, GaussianUpsampling, SamplingWindow, ) from wavegrad import WaveGrad from utils.tools import get_mask_from_lengths ...
0.824603
0.114023
import ipaddress import json import logging import math import os import socket import urllib.request from typing import Optional, Tuple, Dict, Set import plotly.graph_objects as go from scapy.layers.inet import traceroute from scapy.layers.inet6 import traceroute6 marker_size = 10 max_ttl_traceroute = 32 cache_name...
sniff_and_trace/trace.py
import ipaddress import json import logging import math import os import socket import urllib.request from typing import Optional, Tuple, Dict, Set import plotly.graph_objects as go from scapy.layers.inet import traceroute from scapy.layers.inet6 import traceroute6 marker_size = 10 max_ttl_traceroute = 32 cache_name...
0.70619
0.160266
from ..runtimetool import RuntimeTool from .bashtoolmixin import BashToolMixIn from .rvmtool import rvmTool class rubyTool(BashToolMixIn, RuntimeTool): """Ruby is a dynamic, open source programming language. Home: https://www.ruby-lang.org/en/ By default the latest available Ruby binary is used for the followi...
futoin/cid/tool/rubytool.py
from ..runtimetool import RuntimeTool from .bashtoolmixin import BashToolMixIn from .rvmtool import rvmTool class rubyTool(BashToolMixIn, RuntimeTool): """Ruby is a dynamic, open source programming language. Home: https://www.ruby-lang.org/en/ By default the latest available Ruby binary is used for the followi...
0.458834
0.123339
from collections import OrderedDict from math import inf from typing import Dict, List, Optional from typing import OrderedDict as OrderedDictType from typing import Set from ordered_set import OrderedSet from text_selection.greedy_kld_applied import ( greedy_kld_uniform_count, greedy_kld_uniform_default, gre...
src/text_selection/greedy_kld_export.py
from collections import OrderedDict from math import inf from typing import Dict, List, Optional from typing import OrderedDict as OrderedDictType from typing import Set from ordered_set import OrderedSet from text_selection.greedy_kld_applied import ( greedy_kld_uniform_count, greedy_kld_uniform_default, gre...
0.899022
0.313302
import abc from collections import namedtuple from django.conf import settings from django.template.loader import render_to_string from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode import core.tasks from notifications import constants, helpers, models, tokens Recipient...
notifications/email.py
import abc from collections import namedtuple from django.conf import settings from django.template.loader import render_to_string from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode import core.tasks from notifications import constants, helpers, models, tokens Recipient...
0.565899
0.077343
import tvm from functools import reduce from tvm import auto_scheduler from tvm.auto_scheduler.cost_model import RandomModel, XGBModel from tvm.auto_scheduler.search_policy import SketchPolicy def establish_task_ansor( schedule_gen, schedule_app, measure_opt, task_name): target_dag = schedule_app.targ...
python/tvm/auto_tensorize/search/ansor_integrate.py
import tvm from functools import reduce from tvm import auto_scheduler from tvm.auto_scheduler.cost_model import RandomModel, XGBModel from tvm.auto_scheduler.search_policy import SketchPolicy def establish_task_ansor( schedule_gen, schedule_app, measure_opt, task_name): target_dag = schedule_app.targ...
0.442637
0.153676
from django.http import JsonResponse from collections import Counter import pandas as pd import json from datetime import date, timedelta from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.urls import reverse from django.db.models import Avg, Sum, ...
analyze/views.py
from django.http import JsonResponse from collections import Counter import pandas as pd import json from datetime import date, timedelta from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.urls import reverse from django.db.models import Avg, Sum, ...
0.580828
0.14448
from django.db import models from django.contrib.auth.models import User """ UserWrapper for user account """ class UserWrapper(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.user.username """ Tag for contact (e.g. work contact, e...
accounts/models.py
from django.db import models from django.contrib.auth.models import User """ UserWrapper for user account """ class UserWrapper(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.user.username """ Tag for contact (e.g. work contact, e...
0.594551
0.095265
from __future__ import annotations import typing from .signed_transaction import SignedTransaction from ..account.address import Address from ..blockchain.network_type import OptionalNetworkType from ... import util __all__ = ['SyncAnnounce'] @util.dataclass(frozen=True) class SyncAnnounce(util.DTO): """ Si...
xpxchain/models/transaction/sync_announce.py
from __future__ import annotations import typing from .signed_transaction import SignedTransaction from ..account.address import Address from ..blockchain.network_type import OptionalNetworkType from ... import util __all__ = ['SyncAnnounce'] @util.dataclass(frozen=True) class SyncAnnounce(util.DTO): """ Si...
0.930726
0.254631
import numpy as np import matplotlib.pyplot as plt from scipy.special import comb import draw def calc_4points_bezier_path(sx, sy, syaw, gx, gy, gyaw, offset): dist = np.hypot(sx - gx, sy - gy) / offset control_points = np.array( [[sx, sy], [sx + dist * np.cos(syaw), sy + dist * np.sin(syaw)...
CurvesGenerator/bezier_path.py
import numpy as np import matplotlib.pyplot as plt from scipy.special import comb import draw def calc_4points_bezier_path(sx, sy, syaw, gx, gy, gyaw, offset): dist = np.hypot(sx - gx, sy - gy) / offset control_points = np.array( [[sx, sy], [sx + dist * np.cos(syaw), sy + dist * np.sin(syaw)...
0.690142
0.618147
import os import torch import tensorflow as tf import numpy as np from tqdm import tqdm from tabulate import tabulate from utils import check_dir from models.losses import prototype_loss, knn_loss, lr_loss, scm_loss, svm_loss from models.model_utils import CheckPointer from models.model_helpers import get_model from m...
test_extractor_pa.py
import os import torch import tensorflow as tf import numpy as np from tqdm import tqdm from tabulate import tabulate from utils import check_dir from models.losses import prototype_loss, knn_loss, lr_loss, scm_loss, svm_loss from models.model_utils import CheckPointer from models.model_helpers import get_model from m...
0.609524
0.276086
import json from nltk.tokenize import RegexpTokenizer def read_raw_data(filename): with open(filename, "r", encoding="utf8") as data_file: data_file_lines = data_file.readlines() recipe_list = [] for line in data_file_lines: recipe_list.append(json.loads(line)) return recipe_list def...
py-data-preprocess.py
import json from nltk.tokenize import RegexpTokenizer def read_raw_data(filename): with open(filename, "r", encoding="utf8") as data_file: data_file_lines = data_file.readlines() recipe_list = [] for line in data_file_lines: recipe_list.append(json.loads(line)) return recipe_list def...
0.186428
0.163212
from scipy.integrate import odeint import numpy import matplotlib.pyplot as plt # constantes de vitesse k1 = 10**8 km1 = 10**2 k2 = 10**10 km2 = 10**2 k3 = 10**3 km3 = 10**16 k5 = 1.47*(10**6) k6 = 1.4*(10**9) k7 = 4.4*(10**9) k8 = 10**7 # autres constantes Iabs = 10**(-7) # variable phi_T ...
Ebbesen.py
from scipy.integrate import odeint import numpy import matplotlib.pyplot as plt # constantes de vitesse k1 = 10**8 km1 = 10**2 k2 = 10**10 km2 = 10**2 k3 = 10**3 km3 = 10**16 k5 = 1.47*(10**6) k6 = 1.4*(10**9) k7 = 4.4*(10**9) k8 = 10**7 # autres constantes Iabs = 10**(-7) # variable phi_T ...
0.376852
0.485295
import os import re import requests import subprocess from ga4gh.drs.exceptions.drs_exceptions import DownloadSubmethodException from ga4gh.drs.util.method_types.method_type import DownloadSubmethod from ga4gh.drs.util.method_types.method_type import MethodType class GS(MethodType): """Download DRS object bytes ac...
ga4gh/drs/util/method_types/gs.py
import os import re import requests import subprocess from ga4gh.drs.exceptions.drs_exceptions import DownloadSubmethodException from ga4gh.drs.util.method_types.method_type import DownloadSubmethod from ga4gh.drs.util.method_types.method_type import MethodType class GS(MethodType): """Download DRS object bytes ac...
0.635109
0.244397
import asyncio from datetime import timedelta from unittest.mock import patch from bond_api import BPUPSubscriptions, DeviceType from openpeerpower import core from openpeerpower.components import fan from openpeerpower.components.fan import DOMAIN as FAN_DOMAIN from openpeerpower.const import EVENT_OPENPEERPOWER_STO...
tests/components/bond/test_entity.py
import asyncio from datetime import timedelta from unittest.mock import patch from bond_api import BPUPSubscriptions, DeviceType from openpeerpower import core from openpeerpower.components import fan from openpeerpower.components.fan import DOMAIN as FAN_DOMAIN from openpeerpower.const import EVENT_OPENPEERPOWER_STO...
0.78016
0.41561
class ServiceDebugger(object): __enable_debug = True @classmethod def set_debug(cls, enable=True): cls.__enable_debug = enable @classmethod def debug(cls, show_form=True, show_param=True, show_response=True, count_time=True, content_limit=100, disable=False): from flask import requ...
FactorKeeper/Util/ServiceUtil/Debug.py
class ServiceDebugger(object): __enable_debug = True @classmethod def set_debug(cls, enable=True): cls.__enable_debug = enable @classmethod def debug(cls, show_form=True, show_param=True, show_response=True, count_time=True, content_limit=100, disable=False): from flask import requ...
0.359027
0.07658
from typing import Generator from ..models import ( ClassRoom, Subject, Teacher, Student, Group, Service, Source, EventLocation, ) from django import forms from functools import partial DateInput = partial( forms.DateInput, {'class': 'datepicker datepicker_now form-control'} ) DateInputEmpty = par...
day_ok/schedule/forms/utils.py
from typing import Generator from ..models import ( ClassRoom, Subject, Teacher, Student, Group, Service, Source, EventLocation, ) from django import forms from functools import partial DateInput = partial( forms.DateInput, {'class': 'datepicker datepicker_now form-control'} ) DateInputEmpty = par...
0.507324
0.120646
import random import string from model.manage_projects_m import Project def test_create_project(app): app.session.login("administrator", "root") # ั„ัƒะฝั†ะธั ะดะปั ัะพะทะดะฐะฝะธั ัะปัƒั‡ะฐะนะฝะพะน ะฟะพัะปะตะดะพะฒะฐั‚ะตะปัŒะฝะพัั‚ะธ ะทะฝะฐั‡ะตะฝะธะน def random_string(prefix, maxlen): symbols = string.ascii_letters + string.digits re...
test/test_manage_projects.py
import random import string from model.manage_projects_m import Project def test_create_project(app): app.session.login("administrator", "root") # ั„ัƒะฝั†ะธั ะดะปั ัะพะทะดะฐะฝะธั ัะปัƒั‡ะฐะนะฝะพะน ะฟะพัะปะตะดะพะฒะฐั‚ะตะปัŒะฝะพัั‚ะธ ะทะฝะฐั‡ะตะฝะธะน def random_string(prefix, maxlen): symbols = string.ascii_letters + string.digits re...
0.264928
0.358185
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from django.views import generic from .models import Question, Choice from django.utils import timezone from .forms import SearchForm from django.forms.models i...
polls/views.py
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from django.views import generic from .models import Question, Choice from django.utils import timezone from .forms import SearchForm from django.forms.models i...
0.33546
0.083217
import sys from os.path import exists sys.path.append('../..') import numpy as np from loguru import logger from stable_baselines3 import DQN from stable_baselines3.common.vec_env import DummyVecEnv from stable_baselines3.common.monitor import Monitor from vimms.Common import POSITIVE, load_obj, save_obj from vimms...
vimms_gym/debug_training.py
import sys from os.path import exists sys.path.append('../..') import numpy as np from loguru import logger from stable_baselines3 import DQN from stable_baselines3.common.vec_env import DummyVecEnv from stable_baselines3.common.monitor import Monitor from vimms.Common import POSITIVE, load_obj, save_obj from vimms...
0.311113
0.234177
from __future__ import absolute_import # development system imports import os import random import uuid from datetime import date, datetime, timedelta from decimal import Decimal from django.conf import settings from django.contrib.auth.models import AbstractUser from django.contrib.humanize.templatetags import human...
afriproperty/property/models.py
from __future__ import absolute_import # development system imports import os import random import uuid from datetime import date, datetime, timedelta from decimal import Decimal from django.conf import settings from django.contrib.auth.models import AbstractUser from django.contrib.humanize.templatetags import human...
0.499512
0.101545
from culture import Culture import random class Character(): def __init__(self, models, culture, residence, age): self.culture = culture self.models = models self.place = residence # Fullname will later always be set to highest title self.age = age self.state = "ali...
characters.py
from culture import Culture import random class Character(): def __init__(self, models, culture, residence, age): self.culture = culture self.models = models self.place = residence # Fullname will later always be set to highest title self.age = age self.state = "ali...
0.35869
0.168207
try: import tkinter from tkinter.filedialog import askopenfilename except ImportError: import Tkinter as tkinter from tkFileDialog import askopenfilename import os import webbrowser from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg class Gui(object): """ The class for the Graphi...
pygem/gui.py
try: import tkinter from tkinter.filedialog import askopenfilename except ImportError: import Tkinter as tkinter from tkFileDialog import askopenfilename import os import webbrowser from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg class Gui(object): """ The class for the Graphi...
0.50293
0.220248
from __future__ import absolute_import from django.utils import timezone from crispy_forms.layout import \ HTML, Layout, Field, Fieldset, MultiField, Div from crispy_forms.bootstrap import PrependedText from django.contrib.auth import authenticate, get_user_model, login from django.contrib.auth.models import User...
leonardo_module_kkadavy/forms.py
from __future__ import absolute_import from django.utils import timezone from crispy_forms.layout import \ HTML, Layout, Field, Fieldset, MultiField, Div from crispy_forms.bootstrap import PrependedText from django.contrib.auth import authenticate, get_user_model, login from django.contrib.auth.models import User...
0.451568
0.083628
import os import sys import signal from math import ceil from wlauto import ExtensionLoader, Command, settings from wlauto.common.resources import Executable from wlauto.core.resource import NO_ONE from wlauto.core.resolver import ResourceResolver from wlauto.core.configuration import RunConfiguration from wlauto.cor...
wlauto/commands/record.py
import os import sys import signal from math import ceil from wlauto import ExtensionLoader, Command, settings from wlauto.common.resources import Executable from wlauto.core.resource import NO_ONE from wlauto.core.resolver import ResourceResolver from wlauto.core.configuration import RunConfiguration from wlauto.cor...
0.440951
0.115836
from .fhirbase import fhirbase class Task(fhirbase): """ A task to be performed. Attributes: resourceType: This is a Task resource identifier: The business identifier for this task. definitionUri: A reference to a formal or informal definition of the task. For example...
cardea/fhir/Task.py
from .fhirbase import fhirbase class Task(fhirbase): """ A task to be performed. Attributes: resourceType: This is a Task resource identifier: The business identifier for this task. definitionUri: A reference to a formal or informal definition of the task. For example...
0.770465
0.451266
import torch.nn.functional as F import torch import torchvision from util.unnormalise import UnNormalize import numpy as np from PIL import Image from util.params import Opion import os unnorm = UnNormalize(mean=[0.5] * 3, std=[0.5] * 3) opt = Opion() def img2photo(imgs): return ((imgs+1)*127.5).tr...
final/csa/util/generate_images.py
import torch.nn.functional as F import torch import torchvision from util.unnormalise import UnNormalize import numpy as np from PIL import Image from util.params import Opion import os unnorm = UnNormalize(mean=[0.5] * 3, std=[0.5] * 3) opt = Opion() def img2photo(imgs): return ((imgs+1)*127.5).tr...
0.235548
0.257546
# Copyright: (c) 2020, <NAME> <<EMAIL>> # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by":...
intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/cisco/mso/plugins/modules/mso_dhcp_relay_policy_provider.py
# Copyright: (c) 2020, <NAME> <<EMAIL>> # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by":...
0.772874
0.236373
import logging from kazoo.client import KazooClient from full_incidents.hive_to_dwh.hive_connector import create_hive_connector logger = logging.getLogger('hive_to_dwh') def extract(hive_settings, zookeeper_settings, extraction_start_date): zk = KazooClient( hosts=zookeeper_settings) ...
full_incidents/hive_to_dwh/extract.py
import logging from kazoo.client import KazooClient from full_incidents.hive_to_dwh.hive_connector import create_hive_connector logger = logging.getLogger('hive_to_dwh') def extract(hive_settings, zookeeper_settings, extraction_start_date): zk = KazooClient( hosts=zookeeper_settings) ...
0.24899
0.05621
from .pepper import * from .pepper_launch import * from .pepper_quit import * from .pepper_autocomplete import * class PepperMainMenuCommand(sublime_plugin.ApplicationCommand): def run(self): main_menu_commands = [ PepperLaunchCommand, PepperAutocomplete, PepperQuitComm...
pepper_main_menu.py
from .pepper import * from .pepper_launch import * from .pepper_quit import * from .pepper_autocomplete import * class PepperMainMenuCommand(sublime_plugin.ApplicationCommand): def run(self): main_menu_commands = [ PepperLaunchCommand, PepperAutocomplete, PepperQuitComm...
0.308607
0.04703
import pandas as pd import numpy as np import matplotlib.pyplot as plt def split( df, cmpframe=0, distfactor=1.5, show=False, add_start=False, add_end=False ): if cmpframe == -1: start = df[-2:-1] else: start = df[cmpframe : cmpframe + 1] d = dist(start, df).sum(axis=1) valleys = f...
src/data/split.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt def split( df, cmpframe=0, distfactor=1.5, show=False, add_start=False, add_end=False ): if cmpframe == -1: start = df[-2:-1] else: start = df[cmpframe : cmpframe + 1] d = dist(start, df).sum(axis=1) valleys = f...
0.513912
0.597197
import os import re import numpy as np class DebattenAnnotatedDatacleaner: """ Takes the annotated programs, ... """ # Initialises class and input, output locations def __init__(self, loc_ann=None, loc_out=None): self.loc_ann_subtitles = loc_ann if loc_ann is not None else [] s...
util/DebattenAnnotatedDatacleaner.py
import os import re import numpy as np class DebattenAnnotatedDatacleaner: """ Takes the annotated programs, ... """ # Initialises class and input, output locations def __init__(self, loc_ann=None, loc_out=None): self.loc_ann_subtitles = loc_ann if loc_ann is not None else [] s...
0.248079
0.196209
import unittest import struct from uefi_firmware import efi_compressor class CompressionTest(unittest.TestCase): def _test_compress(self, compress_algorithm): default_buffer = b"AAAAAAAA" * 90 compressed_buffer = compress_algorithm( default_buffer, len(default_buffer)) self....
tests/test_compression.py
import unittest import struct from uefi_firmware import efi_compressor class CompressionTest(unittest.TestCase): def _test_compress(self, compress_algorithm): default_buffer = b"AAAAAAAA" * 90 compressed_buffer = compress_algorithm( default_buffer, len(default_buffer)) self....
0.451085
0.455804
import sys sys.path.append("../..") from lfortran.asr import asr from lfortran.asr.asr_check import verify_asr from lfortran.asr.asr_to_ast import asr_to_ast from lfortran.ast.ast_to_src import ast_to_src from lfortran.adapters.gfortran.mod import mod_to_asr from lfortran.asr.builder import (make_translation_unit, ...
integration_tests/interop/wrap2.py
import sys sys.path.append("../..") from lfortran.asr import asr from lfortran.asr.asr_check import verify_asr from lfortran.asr.asr_to_ast import asr_to_ast from lfortran.ast.ast_to_src import ast_to_src from lfortran.adapters.gfortran.mod import mod_to_asr from lfortran.asr.builder import (make_translation_unit, ...
0.251188
0.201165
๏ปฟimport time import csv import codecs import HTML from zabbix.api import ZabbixAPI from datetime import timedelta from datetime import datetime from itertools import repeat def zabbix_dane_tabelka(IP): hID = [] dane_z_zabbix = {'hostname':{}, 'lan':{}, 'loop':{}, 'last_clock_loop':{}} _ = {} zapi = Za...
trzeci.py
๏ปฟimport time import csv import codecs import HTML from zabbix.api import ZabbixAPI from datetime import timedelta from datetime import datetime from itertools import repeat def zabbix_dane_tabelka(IP): hID = [] dane_z_zabbix = {'hostname':{}, 'lan':{}, 'loop':{}, 'last_clock_loop':{}} _ = {} zapi = Za...
0.136522
0.19112
import abc import math from generala import Category class Number(Category): def __init__(self, n): self._n = n def score(self, counts, roll, open_categories): return self._n * counts[self._n-1] def __str__(self): return "{}s".format(self._n) class MajorHand(Category): de...
generala/categories.py
import abc import math from generala import Category class Number(Category): def __init__(self, n): self._n = n def score(self, counts, roll, open_categories): return self._n * counts[self._n-1] def __str__(self): return "{}s".format(self._n) class MajorHand(Category): de...
0.718496
0.243991
from pandas import DataFrame, read_csv from thermo.utils import ROOT def to_type(df: DataFrame, dtype: str = "float32") -> DataFrame: """Convert all non-string columns to a different data type. E.g. float64 and int to float32. """ df_not_str = df.select_dtypes(exclude=[object]).astype(dtype) df_s...
thermo/data/load.py
from pandas import DataFrame, read_csv from thermo.utils import ROOT def to_type(df: DataFrame, dtype: str = "float32") -> DataFrame: """Convert all non-string columns to a different data type. E.g. float64 and int to float32. """ df_not_str = df.select_dtypes(exclude=[object]).astype(dtype) df_s...
0.90904
0.613989
import sys import argparse import logging from . import CLI, VERSION, DESCRIPTION from . import common, exceptions, commands log = logging.getLogger(__name__) def main(args=None, function=None): # pylint: disable=too-many-statements """Process command-line arguments and run the program.""" # Shared option...
gitman/cli.py
import sys import argparse import logging from . import CLI, VERSION, DESCRIPTION from . import common, exceptions, commands log = logging.getLogger(__name__) def main(args=None, function=None): # pylint: disable=too-many-statements """Process command-line arguments and run the program.""" # Shared option...
0.389314
0.073364
import pandas as pd import numpy as np def compute_portvals(market, orders, commission=0.00, impact=0.000, start_val=100000): """ market : Market_DataFrame returned by actions.get_stock_data orders : Dataframe of format { 'date': trading day, <TICKER>: <ORDER> } ...
quantea/marketsim/portvals.py
import pandas as pd import numpy as np def compute_portvals(market, orders, commission=0.00, impact=0.000, start_val=100000): """ market : Market_DataFrame returned by actions.get_stock_data orders : Dataframe of format { 'date': trading day, <TICKER>: <ORDER> } ...
0.305386
0.383064
from flask import request, render_template, jsonify from flask_jwt_extended import jwt_required, create_access_token, get_jwt_identity, get_raw_jwt from app import app, db, jwt from app.models import User, Asset from sqlalchemy.exc import IntegrityError from assets import stocks, cryptocurrency, fiat, stocks_options, c...
backend/app/endpoints.py
from flask import request, render_template, jsonify from flask_jwt_extended import jwt_required, create_access_token, get_jwt_identity, get_raw_jwt from app import app, db, jwt from app.models import User, Asset from sqlalchemy.exc import IntegrityError from assets import stocks, cryptocurrency, fiat, stocks_options, c...
0.404743
0.074131
from __future__ import absolute_import import re # noqa: F401 import sys # noqa: F401 import six # noqa: F401 import nulltype # noqa: F401 from onshape_client.oas.model_utils import ( # noqa: F401 ModelComposed, ModelNormal, ModelSimple, date, datetime, file_type, int, none_type, ...
python/onshape_client/oas/models/bt_revision_info.py
from __future__ import absolute_import import re # noqa: F401 import sys # noqa: F401 import six # noqa: F401 import nulltype # noqa: F401 from onshape_client.oas.model_utils import ( # noqa: F401 ModelComposed, ModelNormal, ModelSimple, date, datetime, file_type, int, none_type, ...
0.474388
0.153613
from __future__ import absolute_import, unicode_literals, division import subprocess import gulpless import logging import shutil import re import os UGLIFY = "uglifyjs" TSC = "tsc" LESSC = "lessc" AUTOPREFIXER = "autoprefixer" IMAGEMIN = "imagemin" if os.name != "posix": UGLIFY += ".cmd" TSC += ".cmd" ...
examples/build.py
from __future__ import absolute_import, unicode_literals, division import subprocess import gulpless import logging import shutil import re import os UGLIFY = "uglifyjs" TSC = "tsc" LESSC = "lessc" AUTOPREFIXER = "autoprefixer" IMAGEMIN = "imagemin" if os.name != "posix": UGLIFY += ".cmd" TSC += ".cmd" ...
0.401101
0.113432
from unittest.mock import patch from django.contrib.auth.models import User from django.http import HttpRequest from django.test import Client, TestCase from django.urls import resolve, reverse from model_bakery import baker as mommy import responses from pyjobs.core.models import Job, Profile, JobApplication ...
pyjobs/core/tests/test_job_challenge.py
from unittest.mock import patch from django.contrib.auth.models import User from django.http import HttpRequest from django.test import Client, TestCase from django.urls import resolve, reverse from model_bakery import baker as mommy import responses from pyjobs.core.models import Job, Profile, JobApplication ...
0.400632
0.195729
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.utils.translation import ugettext_lazy as _ from accounts.models import User, UserSetting, UserProfile, UserSchool, UserLicense, UserEmployer, UserCertification class CustomUserAdmin(UserAdmin): list_display = ("id", "em...
backend/accounts/admin.py
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.utils.translation import ugettext_lazy as _ from accounts.models import User, UserSetting, UserProfile, UserSchool, UserLicense, UserEmployer, UserCertification class CustomUserAdmin(UserAdmin): list_display = ("id", "em...
0.289372
0.1273
import json import pytest from von_anchor.a2a.diddoc import DIDDoc from von_anchor.error import AbsentDIDDocItem from von_anchor.frill import Ink, ppjson @pytest.mark.asyncio async def test_a2a(): print(Ink.YELLOW('\n\n== Testing DID Doc wranglers ==')) # One authn key by reference dd_in = { '@c...
test/test_a2a.py
import json import pytest from von_anchor.a2a.diddoc import DIDDoc from von_anchor.error import AbsentDIDDocItem from von_anchor.frill import Ink, ppjson @pytest.mark.asyncio async def test_a2a(): print(Ink.YELLOW('\n\n== Testing DID Doc wranglers ==')) # One authn key by reference dd_in = { '@c...
0.345989
0.29088
import json from . import consts from collections import OrderedDict from identitykeys import is_valid_idpub, PublicIdentityKey class IdentityNotFoundException(Exception): pass class Identity: def __init__(self, did, chain_id): self.did = did self.chain_id = chain_id self.active_key...
src/models.py
import json from . import consts from collections import OrderedDict from identitykeys import is_valid_idpub, PublicIdentityKey class IdentityNotFoundException(Exception): pass class Identity: def __init__(self, did, chain_id): self.did = did self.chain_id = chain_id self.active_key...
0.625552
0.135518
from enum import IntEnum from typing import TYPE_CHECKING from ooo.oenv.env_const import UNO_ENVIRONMENT, UNO_RUNTIME _DYNAMIC = False if (not TYPE_CHECKING) and UNO_RUNTIME and UNO_ENVIRONMENT: _DYNAMIC = True if not TYPE_CHECKING and _DYNAMIC: from com.sun.star.animations import AnimationFill as AnimationFil...
ooobuild/dyn/animations/animation_fill.py
from enum import IntEnum from typing import TYPE_CHECKING from ooo.oenv.env_const import UNO_ENVIRONMENT, UNO_RUNTIME _DYNAMIC = False if (not TYPE_CHECKING) and UNO_RUNTIME and UNO_ENVIRONMENT: _DYNAMIC = True if not TYPE_CHECKING and _DYNAMIC: from com.sun.star.animations import AnimationFill as AnimationFil...
0.667473
0.194081
from corpuscula import CorpusDict from junky import get_func_params from mordl.base_tagger import BaseTagger from mordl.defaults import BATCH_SIZE, CDICT_COEF_THRESH ,LOG_FILE, \ TRAIN_BATCH_SIZE from mordl.upos_tagger_model import UposTaggerModel import time _CDICT_COEF_THRESH = .99 class...
mordl/upos_tagger.py
from corpuscula import CorpusDict from junky import get_func_params from mordl.base_tagger import BaseTagger from mordl.defaults import BATCH_SIZE, CDICT_COEF_THRESH ,LOG_FILE, \ TRAIN_BATCH_SIZE from mordl.upos_tagger_model import UposTaggerModel import time _CDICT_COEF_THRESH = .99 class...
0.866683
0.341143
import os import time from random import randint from urllib.parse import urlparse from bs4 import BeautifulSoup from urllib3 import ProxyManager, make_headers, PoolManager, disable_warnings from selenium import webdriver class InfinityRequester: def __init__(self, url,parent_element, parent_element_classes, chi...
Requests/InfinityRequester.py
import os import time from random import randint from urllib.parse import urlparse from bs4 import BeautifulSoup from urllib3 import ProxyManager, make_headers, PoolManager, disable_warnings from selenium import webdriver class InfinityRequester: def __init__(self, url,parent_element, parent_element_classes, chi...
0.214445
0.086671
import operator import re import sys import time def get_word_counts(words, ignored_words): word_counts = {} ignored_words_dict = {} # optimal to make a dictionary from the ignored words list for ignored_word in ignored_words: ignored_words_dict[ignored_word] = ignored_word for word in w...
word_frequency/word_frequency.py
import operator import re import sys import time def get_word_counts(words, ignored_words): word_counts = {} ignored_words_dict = {} # optimal to make a dictionary from the ignored words list for ignored_word in ignored_words: ignored_words_dict[ignored_word] = ignored_word for word in w...
0.192009
0.116814
import time import random import click from pynput.keyboard import Key, Listener from click import echo class Trigger: def __init__(self, key_list, verbose=False) -> None: self.index = 0 self.keys = key_list self.list = [] self.verbose = verbose def return_key(self, key): ...
scripted_demos/utilities.py
import time import random import click from pynput.keyboard import Key, Listener from click import echo class Trigger: def __init__(self, key_list, verbose=False) -> None: self.index = 0 self.keys = key_list self.list = [] self.verbose = verbose def return_key(self, key): ...
0.438304
0.112356
import logging from typing import Optional, Tuple from wiki_music.gui_lib.qt_importer import ( QBuffer, QByteArray, QEvent, QImage, QIODevice, QLabel, QPixmap, QPoint, QRect, QRubberBand, QSize, QSizePolicy, QStyleFactory, Qt, Signal) logging.getLogger(__name__) __all__ = ["ResizablePixmap", "SelectablePixm...
wiki_music/gui_lib/custom_classes/pictures.py
import logging from typing import Optional, Tuple from wiki_music.gui_lib.qt_importer import ( QBuffer, QByteArray, QEvent, QImage, QIODevice, QLabel, QPixmap, QPoint, QRect, QRubberBand, QSize, QSizePolicy, QStyleFactory, Qt, Signal) logging.getLogger(__name__) __all__ = ["ResizablePixmap", "SelectablePixm...
0.929444
0.373904
import cv2 import pickle import random import numpy as np def load_images_data(img_ids, images_data): filenames = [] captions = [] for img_id in img_ids: filenames.append(images_data[img_id]['file_name']) captions.append(images_data[img_id]['captions']) return (filenames, captions) ...
dataset/utils.py
import cv2 import pickle import random import numpy as np def load_images_data(img_ids, images_data): filenames = [] captions = [] for img_id in img_ids: filenames.append(images_data[img_id]['file_name']) captions.append(images_data[img_id]['captions']) return (filenames, captions) ...
0.586641
0.495972
from flask import Blueprint, jsonify, request from flask_cors import cross_origin from battleship import db from battleship.helpers import OK_REQUEST, BAD_REQUEST, CREATED, \ UNAUTHORIZED, \ add_then_commit from battleship.models import Account, Coords, Game # Create new flask blueprint game = Blueprint('game', __n...
battleship/game/views.py
from flask import Blueprint, jsonify, request from flask_cors import cross_origin from battleship import db from battleship.helpers import OK_REQUEST, BAD_REQUEST, CREATED, \ UNAUTHORIZED, \ add_then_commit from battleship.models import Account, Coords, Game # Create new flask blueprint game = Blueprint('game', __n...
0.377082
0.077274
from django.shortcuts import render from django.views.generic.list import ListView from mainApp.models import Faculty import teachers, rooms, lesson def index(request): return render(request, 'mainApp/index.html') def instruments(request): instruemnts_name = request.GET.get('name') or [] facultys = Facul...
mainApp/views.py
from django.shortcuts import render from django.views.generic.list import ListView from mainApp.models import Faculty import teachers, rooms, lesson def index(request): return render(request, 'mainApp/index.html') def instruments(request): instruemnts_name = request.GET.get('name') or [] facultys = Facul...
0.254972
0.140189
import numpy as np import matplotlib import os import glob from tensorflow.keras.preprocessing import image import PIL import matplotlib.pyplot as plt PIL.Image.MAX_IMAGE_PIXELS = 933120000 masks_folder = "F:/Datasets/DigestPath/masks" images_folder = "F:/Datasets/DigestPath/images" outfolder = "F:/Datasets/DigestPat...
DigestPath/collect_masks_optimized.py
import numpy as np import matplotlib import os import glob from tensorflow.keras.preprocessing import image import PIL import matplotlib.pyplot as plt PIL.Image.MAX_IMAGE_PIXELS = 933120000 masks_folder = "F:/Datasets/DigestPath/masks" images_folder = "F:/Datasets/DigestPath/images" outfolder = "F:/Datasets/DigestPat...
0.206094
0.441492
from datetime import datetime, timedelta from rx.concurrency import Scheduler, CurrentThreadScheduler def test_currentthread_now(): res = Scheduler.now() - datetime.utcnow() assert res < timedelta(milliseconds=1000) def test_currentthread_scheduleaction(): scheduler = CurrentThreadScheduler() ran = F...
tests/test_currentthreadscheduler.py
from datetime import datetime, timedelta from rx.concurrency import Scheduler, CurrentThreadScheduler def test_currentthread_now(): res = Scheduler.now() - datetime.utcnow() assert res < timedelta(milliseconds=1000) def test_currentthread_scheduleaction(): scheduler = CurrentThreadScheduler() ran = F...
0.639849
0.410756
import argparse import json import mqttClient as mqc import time def on_login(users): convertedUsers = [] for user in users: loggedInUser = loggedInUsers.get(user) if loggedInUser is None: loggedInUser = {"count":0,"ids":[]} ...
tools/mqttMessageAggregator.py
import argparse import json import mqttClient as mqc import time def on_login(users): convertedUsers = [] for user in users: loggedInUser = loggedInUsers.get(user) if loggedInUser is None: loggedInUser = {"count":0,"ids":[]} ...
0.106667
0.050191
import docker import subprocess import time from app.config_const import * #SETUP sul SERVER DOCKER: # rimuovi il docker pid: sudo rm /var/run/docker.pid # stoppa il servizio docker: sudo systemctl stop docker # starta il demone docker sulla tua porta: sudo dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock...
app/setup_docker_client.py
import docker import subprocess import time from app.config_const import * #SETUP sul SERVER DOCKER: # rimuovi il docker pid: sudo rm /var/run/docker.pid # stoppa il servizio docker: sudo systemctl stop docker # starta il demone docker sulla tua porta: sudo dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock...
0.047459
0.061115
import RPi.GPIO as GPIO import os import time from datetime import datetime GPIO.setmode(GPIO.BCM) #do not use #PIN_FACTORY_RESET_17 = 17 # factory reset #PIN_UPS_PICO_1 = 27 #PIN_UPS_PICO_2 = 22 PIN_COM = 25 PIN_POWER_PRESENT = 22 #GPIO_10 True if SpectrooUPS installed PIN_ID=10 GPIO.setwarnings(False) GPIO.setup(...
spectroo_ups.py
import RPi.GPIO as GPIO import os import time from datetime import datetime GPIO.setmode(GPIO.BCM) #do not use #PIN_FACTORY_RESET_17 = 17 # factory reset #PIN_UPS_PICO_1 = 27 #PIN_UPS_PICO_2 = 22 PIN_COM = 25 PIN_POWER_PRESENT = 22 #GPIO_10 True if SpectrooUPS installed PIN_ID=10 GPIO.setwarnings(False) GPIO.setup(...
0.047272
0.084682
import datetime from typing import Dict, List, Optional from pydantic import constr, Field, root_validator, StrictStr, validator from aspen.api.schemas.base import BaseRequest, BaseResponse from aspen.database.models import TreeType # What kinds of ondemand nextstrain builds do we support? PHYLO_TREE_TYPES = [ T...
src/backend/aspen/api/schemas/phylo_runs.py
import datetime from typing import Dict, List, Optional from pydantic import constr, Field, root_validator, StrictStr, validator from aspen.api.schemas.base import BaseRequest, BaseResponse from aspen.database.models import TreeType # What kinds of ondemand nextstrain builds do we support? PHYLO_TREE_TYPES = [ T...
0.870886
0.323727
from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.utils.tzinfo import LocalTimezone from woodstock.models import EventPart from woodstock import settings import icalendar import datetime import random import hashlib def _event_part_ics(event_parts): cal = icalendar....
woodstock/views/ics.py
from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.utils.tzinfo import LocalTimezone from woodstock.models import EventPart from woodstock import settings import icalendar import datetime import random import hashlib def _event_part_ics(event_parts): cal = icalendar....
0.367384
0.089614
import argparse import pandas as pd from tqdm import tqdm from PIL import Image import numpy as np from contextualized_topic_models.datasets.dataset import CTMDataset from sklearn.metrics.pairwise import cosine_similarity from utils import load_model from sentence_transformers import SentenceTransformer, util import pi...
make_submission.py
import argparse import pandas as pd from tqdm import tqdm from PIL import Image import numpy as np from contextualized_topic_models.datasets.dataset import CTMDataset from sklearn.metrics.pairwise import cosine_similarity from utils import load_model from sentence_transformers import SentenceTransformer, util import pi...
0.144752
0.155463
from cam_status import cputemp from cam_status import temp_sensor import time from datetime import timedelta from uptime import uptime import os import psutil import subprocess import re import shutil def time_string(include_timezone): if include_timezone: return time.strftime('%Y-%m-%d %H:%M:%S %Z') else: ...
cam_pi/cam_status/cam_status.py
from cam_status import cputemp from cam_status import temp_sensor import time from datetime import timedelta from uptime import uptime import os import psutil import subprocess import re import shutil def time_string(include_timezone): if include_timezone: return time.strftime('%Y-%m-%d %H:%M:%S %Z') else: ...
0.253122
0.108566
# In[10]: import numpy as np import pandas as pd loandata = pd.DataFrame(pd.read_excel('D:\data analysis\Data capture\loandata.xlsx')) # In[11]: loandata # In[31]: loandata.duplicated().value_counts() # In[13]: loandata.drop_duplicates() # In[14]: loandata['loan_amnt'].isnull().value_counts() # In[...
LoanStats.py
# In[10]: import numpy as np import pandas as pd loandata = pd.DataFrame(pd.read_excel('D:\data analysis\Data capture\loandata.xlsx')) # In[11]: loandata # In[31]: loandata.duplicated().value_counts() # In[13]: loandata.drop_duplicates() # In[14]: loandata['loan_amnt'].isnull().value_counts() # In[...
0.343232
0.766862