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 torch
from torch import nn
from torch.nn import functional as F
import nics_fix_pt as nfp
import nics_fix_pt.nn_fix as nnf
import numpy as np
def _generate_default_fix_cfg(names, scale=0, bitwidth=8, method=0,
range_method=nfp.RangeMethod.RANGE_MAX):
return {
n: {
... | examples/cifar10/net.py | import torch
from torch import nn
from torch.nn import functional as F
import nics_fix_pt as nfp
import nics_fix_pt.nn_fix as nnf
import numpy as np
def _generate_default_fix_cfg(names, scale=0, bitwidth=8, method=0,
range_method=nfp.RangeMethod.RANGE_MAX):
return {
n: {
... | 0.828106 | 0.323113 |
import logging
import os
from urllib.error import HTTPError
from urllib.request import urlopen
import yaml
from ubiquerg import expandpath, is_url
from .const import CONFIG_KEY
_LOGGER = logging.getLogger(__name__)
def copy(obj):
def copy(self):
"""
Copy self to a new object.
"""
... | peppy/utils.py |
import logging
import os
from urllib.error import HTTPError
from urllib.request import urlopen
import yaml
from ubiquerg import expandpath, is_url
from .const import CONFIG_KEY
_LOGGER = logging.getLogger(__name__)
def copy(obj):
def copy(self):
"""
Copy self to a new object.
"""
... | 0.544317 | 0.216985 |
import os
import pickle
import datetime
import numpy as np
import tensorflow as tf
from utils import ops
from tflearn.layers import dropout
from tensorflow.contrib.tensorboard.plugins import projector
from tensorflow.contrib.rnn import stack_bidirectional_rnn
from models.model import Model
class BLSTMAcner(Model):
... | models/blstm_acner.py | import os
import pickle
import datetime
import numpy as np
import tensorflow as tf
from utils import ops
from tflearn.layers import dropout
from tensorflow.contrib.tensorboard.plugins import projector
from tensorflow.contrib.rnn import stack_bidirectional_rnn
from models.model import Model
class BLSTMAcner(Model):
... | 0.746324 | 0.270809 |
import re #modulo de expressoes regulares (regular expressions)
class Cliente:
def __init__(self, nome = None, cpf = None, endereco = None, bairro = None, email = None, fone = None, categoria = None):
self.nome = nome
self.cpf = cpf
self.endereco = endereco
self.bairro = bairro
... | mercado_poo/entidades/cliente.py | import re #modulo de expressoes regulares (regular expressions)
class Cliente:
def __init__(self, nome = None, cpf = None, endereco = None, bairro = None, email = None, fone = None, categoria = None):
self.nome = nome
self.cpf = cpf
self.endereco = endereco
self.bairro = bairro
... | 0.469277 | 0.204064 |
import debug
from tech import drc
import design
from vector import vector
from sram_factory import factory
from globals import OPTS
class tri_gate_array(design.design):
"""
Dynamically generated tri gate array of all bitlines. words_per_row
"""
def __init__(self, columns, word_size, name):
""... | compiler/modules/tri_gate_array.py | import debug
from tech import drc
import design
from vector import vector
from sram_factory import factory
from globals import OPTS
class tri_gate_array(design.design):
"""
Dynamically generated tri gate array of all bitlines. words_per_row
"""
def __init__(self, columns, word_size, name):
""... | 0.440469 | 0.21597 |
from openhpi_baselib.HpiDataTypes import *
#**********************************************************
# HPI Utility Functions (auto-generated)
#**********************************************************
#**********************************************************
# Check Functions for HPI Complex Data Types
#******... | baselibs/python/openhpi_baselib/HpiUtilGen.py |
from openhpi_baselib.HpiDataTypes import *
#**********************************************************
# HPI Utility Functions (auto-generated)
#**********************************************************
#**********************************************************
# Check Functions for HPI Complex Data Types
#******... | 0.352648 | 0.14885 |
import re
import misc_methods
class PlatformResponseMissmatch(Exception):
def __init__(self, message):
# Call the base class constructor with the parameters it needs
super(PlatformResponseMissmatch, self).__init__(message + ' is not available for given platform state and data.\nPlease make sure t... | scripts/automation/regression/CShowParser.py |
import re
import misc_methods
class PlatformResponseMissmatch(Exception):
def __init__(self, message):
# Call the base class constructor with the parameters it needs
super(PlatformResponseMissmatch, self).__init__(message + ' is not available for given platform state and data.\nPlease make sure t... | 0.351089 | 0.270447 |
from pathlib import Path
from django.http import HttpResponse
from rest_framework import viewsets, permissions
from rest_framework.authentication import BasicAuthentication, SessionAuthentication, TokenAuthentication
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from ... | file_storage/views.py | from pathlib import Path
from django.http import HttpResponse
from rest_framework import viewsets, permissions
from rest_framework.authentication import BasicAuthentication, SessionAuthentication, TokenAuthentication
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from ... | 0.330363 | 0.089574 |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
import processTweets as pt
from nltk.stem.lancaster import LancasterStemmer
def plotScoreHistogram():
scores = pt.getTweetScoresFromFile("score.txt")
plt.hist(scores)
plt.title("Score Histogram")
plt.xlabel("Value")
plt.ylabel(... | dataAnalysis.py |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
import processTweets as pt
from nltk.stem.lancaster import LancasterStemmer
def plotScoreHistogram():
scores = pt.getTweetScoresFromFile("score.txt")
plt.hist(scores)
plt.title("Score Histogram")
plt.xlabel("Value")
plt.ylabel(... | 0.603581 | 0.360686 |
from pathlib import Path
import click
from dotenv import load_dotenv
from rich import print
from opime_notify.gsheet import GsheetSession
from opime_notify.notify import LineNotifiyer
from opime_notify.realtime.mpadapter import MPAdapter
from opime_notify.schedule import filter_notify_schedule, marge_result_schedule
... | src/opime_notify/main.py | from pathlib import Path
import click
from dotenv import load_dotenv
from rich import print
from opime_notify.gsheet import GsheetSession
from opime_notify.notify import LineNotifiyer
from opime_notify.realtime.mpadapter import MPAdapter
from opime_notify.schedule import filter_notify_schedule, marge_result_schedule
... | 0.271059 | 0.061565 |
import requests
import json
from pathlib import Path
class LabelStudioAPI:
def __init__(self, token, debug=True):
self.token = token
self.debug = debug
def Project(self, title='Demo', labelXML="""""", description='New Task', action='create', projID='1'):
if action == 'update':
... | labelStudioAPI.py | import requests
import json
from pathlib import Path
class LabelStudioAPI:
def __init__(self, token, debug=True):
self.token = token
self.debug = debug
def Project(self, title='Demo', labelXML="""""", description='New Task', action='create', projID='1'):
if action == 'update':
... | 0.253769 | 0.091707 |
import discord
import datetime
from discord import Button, ButtonStyle, SelectMenu, SelectOption
def getTime():
dt_now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9)))
month = str(dt_now.month)
day = str(dt_now.day)
hour = str(dt_now.hour)
minute = str(dt_now.minute)
if ... | dryflower/dryflower.py | import discord
import datetime
from discord import Button, ButtonStyle, SelectMenu, SelectOption
def getTime():
dt_now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9)))
month = str(dt_now.month)
day = str(dt_now.day)
hour = str(dt_now.hour)
minute = str(dt_now.minute)
if ... | 0.300438 | 0.117041 |
import os
from decimal import Decimal
from unittest.mock import patch
import pytest
from freezegun import freeze_time
from prices import Money, MoneyRange
from saleor.account import events as account_events
from saleor.product import models
from saleor.product.filters import filter_products_by_attributes_values
from ... | tests/test_product.py | import os
from decimal import Decimal
from unittest.mock import patch
import pytest
from freezegun import freeze_time
from prices import Money, MoneyRange
from saleor.account import events as account_events
from saleor.product import models
from saleor.product.filters import filter_products_by_attributes_values
from ... | 0.706089 | 0.501343 |
import numpy as np
from numpy.random import exponential as expo
from random import randint,sample
from Bio import SeqIO
from argparse import ArgumentParser
from bisect import bisect_left, bisect_right
parser = ArgumentParser()
parser.add_argument("contigfile", help="Contig File")
parser.add_argument("--lenfile", help... | simulate_read_distribution.py | import numpy as np
from numpy.random import exponential as expo
from random import randint,sample
from Bio import SeqIO
from argparse import ArgumentParser
from bisect import bisect_left, bisect_right
parser = ArgumentParser()
parser.add_argument("contigfile", help="Contig File")
parser.add_argument("--lenfile", help... | 0.276691 | 0.242755 |
# Contains routines for optimizer construction that wrap the C++ and python versions --
# since those have different arguments / logic
# stdlib
from enum import Enum
# local
from nonrigid_opt.slavcheva.data_term import DataTermMethod
from nonrigid_opt.slavcheva.slavcheva_optimizer2d import ComputeMethod, SlavchevaOp... | experiment/build_slavcheva_optimizer_helper.py |
# Contains routines for optimizer construction that wrap the C++ and python versions --
# since those have different arguments / logic
# stdlib
from enum import Enum
# local
from nonrigid_opt.slavcheva.data_term import DataTermMethod
from nonrigid_opt.slavcheva.slavcheva_optimizer2d import ComputeMethod, SlavchevaOp... | 0.801936 | 0.260246 |
class Rotor:
""" Emulate a single rotor. """
def step(self):
""" Step the rotor forwards. """
self.position = (self.position + 1) % len(self.pins)
def backstep(self):
""" Step the rotor backwards. """
self.position = (self.position - 1) % len(self.pins)
def state(self)... | lorenz/rotor.py | class Rotor:
""" Emulate a single rotor. """
def step(self):
""" Step the rotor forwards. """
self.position = (self.position + 1) % len(self.pins)
def backstep(self):
""" Step the rotor backwards. """
self.position = (self.position - 1) % len(self.pins)
def state(self)... | 0.875035 | 0.819641 |
import Common
class MifLine(object):
Comment = {
"altera" : "--",
"cadence" : "//"
}
def __init__(self, data=None, address = None, comment = "", instruction = None):
self.Address = address
self.Data = data
self.Comment = comment
self.Instruction = instruction
def GetAddressAsInt(self):
try:
... | Mif.py | import Common
class MifLine(object):
Comment = {
"altera" : "--",
"cadence" : "//"
}
def __init__(self, data=None, address = None, comment = "", instruction = None):
self.Address = address
self.Data = data
self.Comment = comment
self.Instruction = instruction
def GetAddressAsInt(self):
try:
... | 0.102647 | 0.203351 |
from os.path import dirname, abspath
from os.path import join
from warnings import warn
from scipy.cluster.hierarchy import linkage, leaves_list
from scipy.spatial.distance import squareform
import numpy as np
import nimfa
try:
from matplotlib.pyplot import savefig, imshow, set_cmap
except ImportError as exc:
... | nimfa/examples/medulloblastoma.py | from os.path import dirname, abspath
from os.path import join
from warnings import warn
from scipy.cluster.hierarchy import linkage, leaves_list
from scipy.spatial.distance import squareform
import numpy as np
import nimfa
try:
from matplotlib.pyplot import savefig, imshow, set_cmap
except ImportError as exc:
... | 0.650356 | 0.516291 |
import itertools
import random
from typing import Callable, Iterable
import cirq
import cirq.google as cg
def generate_supremacy_circuit(device: cg.XmonDevice, cz_depth: int,
seed: int = None, measure: bool = True,
) -> cirq.Circuit:
randint = rando... | examples/supremacy.py |
import itertools
import random
from typing import Callable, Iterable
import cirq
import cirq.google as cg
def generate_supremacy_circuit(device: cg.XmonDevice, cz_depth: int,
seed: int = None, measure: bool = True,
) -> cirq.Circuit:
randint = rando... | 0.737536 | 0.396448 |
import json
import logging
import os
import subprocess
import time
from tpu_survival import TPUSurvival
from experiments import experiments
project = ''
location = 'us-central1-f'
logger = logging.getLogger()
logger.setLevel(logging.INFO)
fh = logging.FileHandler('logs/overrunner.log')
fh.setLevel(logging.INFO)
sh ... | experimental/overrunner.py | import json
import logging
import os
import subprocess
import time
from tpu_survival import TPUSurvival
from experiments import experiments
project = ''
location = 'us-central1-f'
logger = logging.getLogger()
logger.setLevel(logging.INFO)
fh = logging.FileHandler('logs/overrunner.log')
fh.setLevel(logging.INFO)
sh ... | 0.247805 | 0.068071 |
from bioCanon import __main__
import os
def test_tree_path():
group_info = "none"
tree_file = os.path.join(os.getcwd(), "tests", "examples", "testing.nwk")
case = __main__.path_check(group_info, tree_file)
compare = ({'Q': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
'R': [1, 1, 1, 1, 1, 1, 1... | tests/test_path_check.py | from bioCanon import __main__
import os
def test_tree_path():
group_info = "none"
tree_file = os.path.join(os.getcwd(), "tests", "examples", "testing.nwk")
case = __main__.path_check(group_info, tree_file)
compare = ({'Q': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
'R': [1, 1, 1, 1, 1, 1, 1... | 0.266071 | 0.554048 |
from selenium import webdriver
from bs4 import BeautifulSoup
import json
import time
from selenium.webdriver.common.by import By
import csv
browser = webdriver.Chrome()
pageurl = "https://www.linkedin.com/uas/login?session_redirect=https%3A%2F%2Fwww%2Elinkedin%2Ecom%2Fsearch%2Fresults%2Fpeople%2F%3Fnetwork%3D%255B%25... | Python/Linkedin_Connection_Scrapper/main.py | from selenium import webdriver
from bs4 import BeautifulSoup
import json
import time
from selenium.webdriver.common.by import By
import csv
browser = webdriver.Chrome()
pageurl = "https://www.linkedin.com/uas/login?session_redirect=https%3A%2F%2Fwww%2Elinkedin%2Ecom%2Fsearch%2Fresults%2Fpeople%2F%3Fnetwork%3D%255B%25... | 0.461502 | 0.165088 |
import numpy as np
import pandas as pd
from .utils import get_drift, get_offset, signed_series, verify_series
from .momentum import roc
from .overlap import hl2, hlc3, ema
def ad(high, low, close, volume, open_=None, offset=None, **kwargs):
"""Indicator: Accumulation/Distribution (AD)"""
# Validate Arguments... | ta/volume.py | import numpy as np
import pandas as pd
from .utils import get_drift, get_offset, signed_series, verify_series
from .momentum import roc
from .overlap import hl2, hlc3, ema
def ad(high, low, close, volume, open_=None, offset=None, **kwargs):
"""Indicator: Accumulation/Distribution (AD)"""
# Validate Arguments... | 0.726814 | 0.384797 |
import logging
from dataclasses import dataclass, field
from typing import Any, Generator, Optional, Type, TypeVar
from thenewboston_node.core.utils.dataclass import cover_docstring, revert_docstring
from thenewboston_node.core.utils.misc import if_none
from thenewboston_node.core.utils.types import hexstr
from .acco... | thenewboston_node/business_logic/models/blockchain_state.py | import logging
from dataclasses import dataclass, field
from typing import Any, Generator, Optional, Type, TypeVar
from thenewboston_node.core.utils.dataclass import cover_docstring, revert_docstring
from thenewboston_node.core.utils.misc import if_none
from thenewboston_node.core.utils.types import hexstr
from .acco... | 0.706596 | 0.250798 |
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import ANY
from urllib.parse import parse_qs, urlparse
import pytest
from tests.support.logging import parse_log
if TYPE_CHECKING:
from _pytest.logging import LogCaptureFixture
from tests.support.setup import SetupTest
... | tests/handlers/login_oidc_test.py |
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import ANY
from urllib.parse import parse_qs, urlparse
import pytest
from tests.support.logging import parse_log
if TYPE_CHECKING:
from _pytest.logging import LogCaptureFixture
from tests.support.setup import SetupTest
... | 0.83128 | 0.466481 |
import sys, weakref
from whoosh import query
from whoosh.qparser.common import get_single_text, QueryParserError, attach
class SyntaxNode(object):
"""Base class for nodes that make up the abstract syntax tree (AST) of a
parsed user query string. The AST is an intermediate step, generated
from the query ... | vendor-local/lib/python/whoosh/qparser/syntax.py |
import sys, weakref
from whoosh import query
from whoosh.qparser.common import get_single_text, QueryParserError, attach
class SyntaxNode(object):
"""Base class for nodes that make up the abstract syntax tree (AST) of a
parsed user query string. The AST is an intermediate step, generated
from the query ... | 0.669529 | 0.263949 |
import os
import arcpy
import sys
import traceback
try:
from . import Utilities
from . import VisibilityUtilities
except ImportError:
import Utilities
import VisibilityUtilities
class AddLinearLineOfSightFields(object):
'''
Adds an OFFSET field and user-defined/default value to
an input ... | tools/militarytools/esri/toolboxes/scripts/VisTools.py | import os
import arcpy
import sys
import traceback
try:
from . import Utilities
from . import VisibilityUtilities
except ImportError:
import Utilities
import VisibilityUtilities
class AddLinearLineOfSightFields(object):
'''
Adds an OFFSET field and user-defined/default value to
an input ... | 0.730482 | 0.26314 |
import argparse
import torch
import numpy as np
from numpy import *
# compute rollout between attention layers
def compute_rollout_attention(all_layer_matrices, start_layer=0):
# adding residual consideration- code adapted from https://github.com/samiraabnar/attention_flow
num_tokens = all_layer_matrices[0].sh... | baselines/ViT/ViT_explanation_generator.py | import argparse
import torch
import numpy as np
from numpy import *
# compute rollout between attention layers
def compute_rollout_attention(all_layer_matrices, start_layer=0):
# adding residual consideration- code adapted from https://github.com/samiraabnar/attention_flow
num_tokens = all_layer_matrices[0].sh... | 0.750278 | 0.569613 |
from django.db.models import Q
def build_query_to_datatable(query_set, asorting_cols, custom_search,
searchable_columns, start_record, end_record):
"""
Build query using params received
"""
if asorting_cols is not None and len(asorting_cols) > 0:
# Ordering data
... | networkapi/infrastructure/datatable.py | from django.db.models import Q
def build_query_to_datatable(query_set, asorting_cols, custom_search,
searchable_columns, start_record, end_record):
"""
Build query using params received
"""
if asorting_cols is not None and len(asorting_cols) > 0:
# Ordering data
... | 0.687735 | 0.42471 |
from __future__ import print_function
import os
from rapidfuzz import fuzz
from . import debug
class PidgenElement():
"""
Base level PidgenElement class.
Provides low-level functionality inherited by all higher classes
"""
BASIC_KEYS = [
"name",
"title",
"comment",... | pidgen/element.py |
from __future__ import print_function
import os
from rapidfuzz import fuzz
from . import debug
class PidgenElement():
"""
Base level PidgenElement class.
Provides low-level functionality inherited by all higher classes
"""
BASIC_KEYS = [
"name",
"title",
"comment",... | 0.770076 | 0.212559 |
import os
import pytz
from datetime import datetime
from sys import byteorder
from array import array
from struct import pack
import pyaudio
import wave
from django.conf import settings
CHANNELS = 2
SAMPLE_RATE = 44100
THRESHOLD = 500
CHUNK_SIZE = 2048
FORMAT = pyaudio.paInt16
TEMP_PATH = getattr(settings, 'BOOTH_R... | soundbooth/apps/booth/utils.py | import os
import pytz
from datetime import datetime
from sys import byteorder
from array import array
from struct import pack
import pyaudio
import wave
from django.conf import settings
CHANNELS = 2
SAMPLE_RATE = 44100
THRESHOLD = 500
CHUNK_SIZE = 2048
FORMAT = pyaudio.paInt16
TEMP_PATH = getattr(settings, 'BOOTH_R... | 0.310485 | 0.240117 |
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_core_components as dcc
from domestic_violence import domestic_violence_tab, domestic_violence_learn_more
from domestic_work import domestic_work_tab
from employment import employment_tab
from map_graph.draw_map import map_graph
fr... | layout.py | import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_core_components as dcc
from domestic_violence import domestic_violence_tab, domestic_violence_learn_more
from domestic_work import domestic_work_tab
from employment import employment_tab
from map_graph.draw_map import map_graph
fr... | 0.38885 | 0.249647 |
import numpy as np
from random import sample
import os
import pickle
def save_pickle(data, path):
with open(path, 'wb') as f:
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
print ('Saved %s..' % path)
def remover(x): return ''.join([i for i in x if not i.isdigit()])
def get_celeb_dict(path):
... | prepro.py | import numpy as np
from random import sample
import os
import pickle
def save_pickle(data, path):
with open(path, 'wb') as f:
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
print ('Saved %s..' % path)
def remover(x): return ''.join([i for i in x if not i.isdigit()])
def get_celeb_dict(path):
... | 0.16654 | 0.175256 |
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import pickle
st.title("Data from Japanese Restaurants")
url = r"https://raw.githubusercontent.com/JonathanBechtel/dat-11-15/main/ClassMaterial/Unit1/data/master.csv"
num_rows = st.sidebar.number_input('Select Number of Rows to... | app.py | import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import pickle
st.title("Data from Japanese Restaurants")
url = r"https://raw.githubusercontent.com/JonathanBechtel/dat-11-15/main/ClassMaterial/Unit1/data/master.csv"
num_rows = st.sidebar.number_input('Select Number of Rows to... | 0.433022 | 0.278974 |
from encoder.data_objects.random_cycler import RandomCycler
from encoder.data_objects.speaker_batch import SpeakerBatch
from encoder.data_objects.speaker import Speaker
from encoder.params_data import partials_n_frames
from torch.utils.data import Dataset, DataLoader
from pathlib import Path
import glob
import os
# TO... | encoder/data_objects/speaker_verification_dataset.py | from encoder.data_objects.random_cycler import RandomCycler
from encoder.data_objects.speaker_batch import SpeakerBatch
from encoder.data_objects.speaker import Speaker
from encoder.params_data import partials_n_frames
from torch.utils.data import Dataset, DataLoader
from pathlib import Path
import glob
import os
# TO... | 0.463201 | 0.171442 |
from csp_rej import parse_args, parse_config, print_float
from obtain_predictor_intervals import get_predictors_intersections, get_interval_best_predictor, merge_intervals
def print_output(rho, predictors, merged_intervals):
merged_intervals.update({predictor: 0 for predictor in predictors if predictor not in mer... | csp/csp_norej.py | from csp_rej import parse_args, parse_config, print_float
from obtain_predictor_intervals import get_predictors_intersections, get_interval_best_predictor, merge_intervals
def print_output(rho, predictors, merged_intervals):
merged_intervals.update({predictor: 0 for predictor in predictors if predictor not in mer... | 0.68437 | 0.301227 |
import json
import re
from typing import List, Optional
from pydantic import BaseModel
from ..collection import MsgTypes
from ..model import GroupMsg
# at
class UserExtItem(BaseModel):
QQNick: str
QQUid: int
class AT(BaseModel):
Content: str
UserExt: List[UserExtItem]
UserID: List[int]
def a... | botoy/parser/group.py | import json
import re
from typing import List, Optional
from pydantic import BaseModel
from ..collection import MsgTypes
from ..model import GroupMsg
# at
class UserExtItem(BaseModel):
QQNick: str
QQUid: int
class AT(BaseModel):
Content: str
UserExt: List[UserExtItem]
UserID: List[int]
def a... | 0.456652 | 0.253896 |
import io
from typing import BinaryIO, Optional
from .base import CIOType, CFixedType
from .buffer import c_buffer
from ..encoding import auto_decode
__all__ = [
'CStringType',
'c_str',
'CSizedStringType',
'c_sized_str',
]
def _auto_encode(s: str, encoding) -> bytes:
return s.encode(encoding if ... | hbutils/binary/str.py | import io
from typing import BinaryIO, Optional
from .base import CIOType, CFixedType
from .buffer import c_buffer
from ..encoding import auto_decode
__all__ = [
'CStringType',
'c_str',
'CSizedStringType',
'c_sized_str',
]
def _auto_encode(s: str, encoding) -> bytes:
return s.encode(encoding if ... | 0.818954 | 0.212212 |
from __future__ import absolute_import, division, print_function
from collections import namedtuple
from cryptography import utils
from cryptography.exceptions import (
UnsupportedAlgorithm, InvalidTag, InternalError
)
from cryptography.hazmat.backends.interfaces import (
HashBackend, HMACBackend, CipherBack... | cryptography/hazmat/backends/commoncrypto/backend.py |
from __future__ import absolute_import, division, print_function
from collections import namedtuple
from cryptography import utils
from cryptography.exceptions import (
UnsupportedAlgorithm, InvalidTag, InternalError
)
from cryptography.hazmat.backends.interfaces import (
HashBackend, HMACBackend, CipherBack... | 0.843895 | 0.167866 |
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from .base_arch import BaseArch
from ..build import META_ARCH_REGISTRY
@META_ARCH_REGISTRY.register()
class SingleScalePlainCNN(BaseArch):
def __init__(self, cfg):
super().__init__()
self.cfg = copy.deepcopy(cfg)
... | simdeblur/model/meta_arch/plain_cnn.py | import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from .base_arch import BaseArch
from ..build import META_ARCH_REGISTRY
@META_ARCH_REGISTRY.register()
class SingleScalePlainCNN(BaseArch):
def __init__(self, cfg):
super().__init__()
self.cfg = copy.deepcopy(cfg)
... | 0.900939 | 0.387951 |
import os
from PIL import Image
import pickle
import numpy as np
from torch.utils.data import Dataset
class Dataloader():
def __init__(self, datafile, num_classes, img_width, img_height, dataset_save_path=None):
self.datafile = datafile
self.num_classes = num_classes
self.data_save_path =... | detection/RCNN_pytorch/data_loader.py | import os
from PIL import Image
import pickle
import numpy as np
from torch.utils.data import Dataset
class Dataloader():
def __init__(self, datafile, num_classes, img_width, img_height, dataset_save_path=None):
self.datafile = datafile
self.num_classes = num_classes
self.data_save_path =... | 0.549157 | 0.279868 |
import os
DATA = [
("invisible", "true", "advanced", "true"),
("invisible", "false", "advanced", "false"),
("invisible", "false", "advanced", "true"),
('invisible', "true", "advanced", "false"),
]
TYPES = (
"string",
"password",
"integer",
"text",
'boolean',
'float',
'option... | tests/ui_tests/test_ro_fields_ui_options_data/config_generator.py | import os
DATA = [
("invisible", "true", "advanced", "true"),
("invisible", "false", "advanced", "false"),
("invisible", "false", "advanced", "true"),
('invisible', "true", "advanced", "false"),
]
TYPES = (
"string",
"password",
"integer",
"text",
'boolean',
'float',
'option... | 0.433022 | 0.278318 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import cv2
def flip_back(output_flipped, matched_parts):
'''
ouput_flipped: numpy.ndarray(batch_size, num_joints, height, width)
'''
assert output_flipped.ndim == 4,\
... | lib/utils/transforms.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import cv2
def flip_back(output_flipped, matched_parts):
'''
ouput_flipped: numpy.ndarray(batch_size, num_joints, height, width)
'''
assert output_flipped.ndim == 4,\
... | 0.760295 | 0.417568 |
import logging
import os
import numpy as np
import pandas as pd
import xarray as xr
from src.hyde.algorithm.settings.model.rfarm.lib_rfarm_args import time_format, logger_name
log_stream = logging.getLogger(logger_name)
# Debug
import matplotlib.pylab as plt
# ---------------------------------------------------------... | src/hyde/algorithm/io/model/rfarm/lib_rfarm_io_json.py | import logging
import os
import numpy as np
import pandas as pd
import xarray as xr
from src.hyde.algorithm.settings.model.rfarm.lib_rfarm_args import time_format, logger_name
log_stream = logging.getLogger(logger_name)
# Debug
import matplotlib.pylab as plt
# ---------------------------------------------------------... | 0.429549 | 0.170957 |
import os
import numpy as np
import copy
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Normal
from tensorboardX import SummaryWriter
from buffer import ReplayBuffer
'''
Soft actor critic with automated temperature
Original pape... | Char09 SAC/SAC_v1.py | import os
import numpy as np
import copy
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Normal
from tensorboardX import SummaryWriter
from buffer import ReplayBuffer
'''
Soft actor critic with automated temperature
Original pape... | 0.920057 | 0.55266 |
import udi_interface
import sys
import time
from nodes import iaq
LOGGER = udi_interface.LOGGER
Custom = udi_interface.Custom
'''
Controller is interfacing with both Polyglot and the device. In this
case the device is just a count that has two values, the count and the count
multiplied by a user defined multiplier. T... | nodes/pp_ctl.py | import udi_interface
import sys
import time
from nodes import iaq
LOGGER = udi_interface.LOGGER
Custom = udi_interface.Custom
'''
Controller is interfacing with both Polyglot and the device. In this
case the device is just a count that has two values, the count and the count
multiplied by a user defined multiplier. T... | 0.274546 | 0.451508 |
import os
import numpy as np
from netCDF4 import Dataset
import pytest
from desc.equilibrium import Equilibrium, EquilibriaFamily
from desc.grid import Grid, LinearGrid
from desc.utils import area_difference
from desc.__main__ import main
def test_compute_geometry(DSHAPE):
"""Test computation of plasma geometric... | tests/test_equilibrium.py | import os
import numpy as np
from netCDF4 import Dataset
import pytest
from desc.equilibrium import Equilibrium, EquilibriaFamily
from desc.grid import Grid, LinearGrid
from desc.utils import area_difference
from desc.__main__ import main
def test_compute_geometry(DSHAPE):
"""Test computation of plasma geometric... | 0.756088 | 0.509154 |
"""Cloud function to request builds."""
import concurrent.futures
import logging
import json
import sys
import os
import google.auth
from googleapiclient.discovery import build
import googleapiclient.errors
from google.cloud import ndb
from google.cloud import storage
import build_and_run_coverage
import build_lib
im... | infra/build/build_status/update_build_status.py | """Cloud function to request builds."""
import concurrent.futures
import logging
import json
import sys
import os
import google.auth
from googleapiclient.discovery import build
import googleapiclient.errors
from google.cloud import ndb
from google.cloud import storage
import build_and_run_coverage
import build_lib
im... | 0.465145 | 0.113211 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from . import _utilities, _tables
__all__ = ['PortVlanAttachment']
class PortVlanAttachment(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Op... | sdk/python/pulumi_equinix_metal/port_vlan_attachment.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from . import _utilities, _tables
__all__ = ['PortVlanAttachment']
class PortVlanAttachment(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Op... | 0.805441 | 0.272779 |
import os
import sys
import logging
import time
import yaml
import argparse
import threading
from client import tts
from client import stt
from client import dingdangpath
from client import diagnose
from client.wxbot import WXBot
from client.conversation import Conversation
from client.tts import SimpleMp3Player
# Add... | xiaoroubao.py |
import os
import sys
import logging
import time
import yaml
import argparse
import threading
from client import tts
from client import stt
from client import dingdangpath
from client import diagnose
from client.wxbot import WXBot
from client.conversation import Conversation
from client.tts import SimpleMp3Player
# Add... | 0.19521 | 0.053206 |
from collections import defaultdict
import pysam
from viridian_workflow.primers import AmpliconSet, set_tags
def score(matches):
"""Assign winning amplicon set id based on match stats"""
# naive: take max of all bins
m = 0
winner = None
for k, v in matches.items():
if v >= m:
... | viridian_workflow/detect_primers.py | from collections import defaultdict
import pysam
from viridian_workflow.primers import AmpliconSet, set_tags
def score(matches):
"""Assign winning amplicon set id based on match stats"""
# naive: take max of all bins
m = 0
winner = None
for k, v in matches.items():
if v >= m:
... | 0.466603 | 0.340184 |
import random
from threading import Thread
import math
import rospy
import time
from std_msgs.msg import Float64
from sensor_msgs.msg import JointState
from geometry_msgs.msg import Twist
class Darwin:
"""
Client ROS class for manipulating Darwin OP in Gazebo
"""
def __init__(self,ns="/darwin/"):... | src/darwin_gazebo/darwin.py | import random
from threading import Thread
import math
import rospy
import time
from std_msgs.msg import Float64
from sensor_msgs.msg import JointState
from geometry_msgs.msg import Twist
class Darwin:
"""
Client ROS class for manipulating Darwin OP in Gazebo
"""
def __init__(self,ns="/darwin/"):... | 0.31279 | 0.131759 |
import math
from Instrucciones.TablaSimbolos.Instruccion import Instruccion
from Instrucciones.TablaSimbolos.Tipo import Tipo_Dato, Tipo
from Instrucciones.Excepcion import Excepcion
class Acosd(Instruccion):
def __init__(self, valor, strGram, linea, columna):
Instruccion.__init__(self,Tipo(Tipo_Dato.DOUBL... | parser/fase2/team04/Tytus/Instrucciones/FunctionTrigonometric/Acosd.py | import math
from Instrucciones.TablaSimbolos.Instruccion import Instruccion
from Instrucciones.TablaSimbolos.Tipo import Tipo_Dato, Tipo
from Instrucciones.Excepcion import Excepcion
class Acosd(Instruccion):
def __init__(self, valor, strGram, linea, columna):
Instruccion.__init__(self,Tipo(Tipo_Dato.DOUBL... | 0.326271 | 0.262653 |
from expects.matchers import Matcher
__all__ = [] # disable * imports
class StatefulMatcher(Matcher):
def __init__(self, expected, parent=None):
self._expected = expected
self._parent = parent
self._matched = []
self._matcher_name = self.__class__.__name__[8:]
self._match... | pytest_salt_formula/matchers.py | from expects.matchers import Matcher
__all__ = [] # disable * imports
class StatefulMatcher(Matcher):
def __init__(self, expected, parent=None):
self._expected = expected
self._parent = parent
self._matched = []
self._matcher_name = self.__class__.__name__[8:]
self._match... | 0.804483 | 0.312947 |
import os
import numpy as np
import pandas as pd
import _pickle as cPickle
from collections import OrderedDict, defaultdict
import tensorflow as tf
from data_structure import Instance
flags = tf.app.flags
flags.DEFINE_string('input_path', 'data/sports_df.pkl', 'path of output data')
flags.DEFINE_string('output_pat... | preprocess_data.py | import os
import numpy as np
import pandas as pd
import _pickle as cPickle
from collections import OrderedDict, defaultdict
import tensorflow as tf
from data_structure import Instance
flags = tf.app.flags
flags.DEFINE_string('input_path', 'data/sports_df.pkl', 'path of output data')
flags.DEFINE_string('output_pat... | 0.475362 | 0.251234 |
import os
import sys
import logging
import datetime
AMM_LOGGER_BASENAME = "automatminer"
AMM_LOG_FIT_STR = "fitting"
AMM_LOG_TRANSFORM_STR = "transforming"
AMM_LOG_PREDICT_STR = "predicting"
def initialize_logger(name, filepath='.', filebase=None,
level=None) -> logging.Logger:
"""Initializ... | automatminer/utils/log.py | import os
import sys
import logging
import datetime
AMM_LOGGER_BASENAME = "automatminer"
AMM_LOG_FIT_STR = "fitting"
AMM_LOG_TRANSFORM_STR = "transforming"
AMM_LOG_PREDICT_STR = "predicting"
def initialize_logger(name, filepath='.', filebase=None,
level=None) -> logging.Logger:
"""Initializ... | 0.608827 | 0.068725 |
import dataclasses
import sys
import re
from jsonasobj2 import JsonObj, as_dict
from typing import Optional, List, Union, Dict, ClassVar, Any
from dataclasses import dataclass
from linkml_runtime.linkml_model.meta import EnumDefinition, PermissibleValue, PvFormulaOptions
from linkml_runtime.utils.slot import Slot
fro... | examples/tutorial/tutorial05/personinfo.py |
import dataclasses
import sys
import re
from jsonasobj2 import JsonObj, as_dict
from typing import Optional, List, Union, Dict, ClassVar, Any
from dataclasses import dataclass
from linkml_runtime.linkml_model.meta import EnumDefinition, PermissibleValue, PvFormulaOptions
from linkml_runtime.utils.slot import Slot
fro... | 0.641647 | 0.112844 |
import asyncio
import aiohttp_jinja2
import jinja2
from aiohttp import web
from .handlers import ApiHandler, PagesHandler, WSstatsHandler, WSChatHandler
@web.middleware
async def cors_mw(request, handler):
resp = await handler(request)
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers['Acce... | deeppavlov_agent/http_api/api.py | import asyncio
import aiohttp_jinja2
import jinja2
from aiohttp import web
from .handlers import ApiHandler, PagesHandler, WSstatsHandler, WSChatHandler
@web.middleware
async def cors_mw(request, handler):
resp = await handler(request)
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers['Acce... | 0.196286 | 0.040579 |
from dataclasses import dataclass
from typing import Optional, Type, TypeVar, Union
from more_properties.class_property import ClassProperty, StaticProperty
from more_properties.types import Deleter
from more_properties.util_properties import NamedProperty
__all__ = [
"cached_property",
"cached_class_property... | more_properties/cached_property.py | from dataclasses import dataclass
from typing import Optional, Type, TypeVar, Union
from more_properties.class_property import ClassProperty, StaticProperty
from more_properties.types import Deleter
from more_properties.util_properties import NamedProperty
__all__ = [
"cached_property",
"cached_class_property... | 0.870108 | 0.1532 |
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import SuspiciousOperation
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.utils import translation
from django.views.decorators.cache import cache_page
from django.utils.translation import... | server/main/entity.py |
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import SuspiciousOperation
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.utils import translation
from django.views.decorators.cache import cache_page
from django.utils.translation import... | 0.542379 | 0.087369 |
import quickle
from django.db.models import Q
from accounts.forms import User
from centers.models import Center
from oils.models import Oil_Pattern
from tournaments.models import Tournament
def get_list_of_all_bowlers():
users = User.objects.all()
temp = {}
for user in users:
data = []
dat... | prolink/prolink_requests.py | import quickle
from django.db.models import Q
from accounts.forms import User
from centers.models import Center
from oils.models import Oil_Pattern
from tournaments.models import Tournament
def get_list_of_all_bowlers():
users = User.objects.all()
temp = {}
for user in users:
data = []
dat... | 0.212968 | 0.160825 |
import os
import unittest
import numpy as np
import pandas as pd
from nimbusml import Pipeline, FileDataStream
from nimbusml.datasets import get_dataset
from nimbusml.feature_extraction.categorical import OneHotVectorizer
from nimbusml.linear_model import LogisticRegressionBinaryClassifier, OnlineGradientDescentRegres... | src/python/nimbusml/tests/pipeline/test_pipeline_split_models.py | import os
import unittest
import numpy as np
import pandas as pd
from nimbusml import Pipeline, FileDataStream
from nimbusml.datasets import get_dataset
from nimbusml.feature_extraction.categorical import OneHotVectorizer
from nimbusml.linear_model import LogisticRegressionBinaryClassifier, OnlineGradientDescentRegres... | 0.717309 | 0.603143 |
from typing import Dict
from datetime import datetime
from os.path import join
from decimal import Decimal
from collections import namedtuple, defaultdict
from functools import lru_cache
from pytezos.encoding import forge_public_key, forge_address, forge_base58
from pytezos.michelson.formatter import micheline_to_mich... | pytezos/michelson/micheline.py | from typing import Dict
from datetime import datetime
from os.path import join
from decimal import Decimal
from collections import namedtuple, defaultdict
from functools import lru_cache
from pytezos.encoding import forge_public_key, forge_address, forge_base58
from pytezos.michelson.formatter import micheline_to_mich... | 0.664649 | 0.206114 |
import unittest
from src.AutoMLpy import RandomHpSearch
# Pytorch
from tests.objective_functions.objective_function import ObjectiveFuncHpOptimizer
from tests.objective_functions.vectorized_objective_function import VectorizedObjectiveFuncHpOptimizer
from tests.pytorch_items.pytorch_datasets import get_torch_MNIST_X_y... | tests/random_optimizer_test.py | import unittest
from src.AutoMLpy import RandomHpSearch
# Pytorch
from tests.objective_functions.objective_function import ObjectiveFuncHpOptimizer
from tests.objective_functions.vectorized_objective_function import VectorizedObjectiveFuncHpOptimizer
from tests.pytorch_items.pytorch_datasets import get_torch_MNIST_X_y... | 0.641647 | 0.55917 |
import rospy
from diagnostic_msgs.msg import DiagnosticStatus
from python_qt_binding.QtCore import QMutex, QMutexLocker, QSize, QTimer, Signal
from rqt_robot_monitor.robot_monitor import RobotMonitorWidget
from rqt_robot_dashboard.icon_tool_button import IconToolButton
class MonitorDashWidget(IconToolButton):
""... | chris_turtlebot_dashboard/src/chris_turtlebot_dashboard/monitor_dash_widget.py |
import rospy
from diagnostic_msgs.msg import DiagnosticStatus
from python_qt_binding.QtCore import QMutex, QMutexLocker, QSize, QTimer, Signal
from rqt_robot_monitor.robot_monitor import RobotMonitorWidget
from rqt_robot_dashboard.icon_tool_button import IconToolButton
class MonitorDashWidget(IconToolButton):
""... | 0.358465 | 0.085061 |
"""Command-line interface to gruut"""
import argparse
import csv
import dataclasses
import itertools
import json
import logging
import os
import shutil
import sys
import tempfile
import typing
from collections import Counter
from pathlib import Path
import jsonlines
import pydash
import yaml
import gruut_ipa
from . ... | gruut/__main__.py | """Command-line interface to gruut"""
import argparse
import csv
import dataclasses
import itertools
import json
import logging
import os
import shutil
import sys
import tempfile
import typing
from collections import Counter
from pathlib import Path
import jsonlines
import pydash
import yaml
import gruut_ipa
from . ... | 0.351979 | 0.125627 |
from os import environ, getcwd
from os.path import exists, join
if not exists("ninchat/api/spec/json"):
raise Exception("ninchat-api submodule not found")
if not exists("go/src/github.com/ninchat/ninchat-go/include"):
raise Exception("ninchat-go submodule not found")
try:
import setuptools
import sy... | setup.py |
from os import environ, getcwd
from os.path import exists, join
if not exists("ninchat/api/spec/json"):
raise Exception("ninchat-api submodule not found")
if not exists("go/src/github.com/ninchat/ninchat-go/include"):
raise Exception("ninchat-go submodule not found")
try:
import setuptools
import sy... | 0.291687 | 0.127598 |
import numpy as np
from copy import deepcopy
from xicsrt.tools.xicsrt_doc import dochelper
from xicsrt.optics._TraceObject import TraceObject
from xicsrt.tools import xicsrt_math as xm
@dochelper
class ShapeObject(TraceObject):
"""
The base class for intersections of rays with surfaces in XICSRT.
This b... | xicsrt/optics/_ShapeObject.py | import numpy as np
from copy import deepcopy
from xicsrt.tools.xicsrt_doc import dochelper
from xicsrt.optics._TraceObject import TraceObject
from xicsrt.tools import xicsrt_math as xm
@dochelper
class ShapeObject(TraceObject):
"""
The base class for intersections of rays with surfaces in XICSRT.
This b... | 0.820037 | 0.697596 |
import json
import mock
from django.test import TestCase
from elasticsearch import TransportError
from django_elasticsearch.managers import es_client
from test_app.models import TestModel
class EsViewTestCase(TestCase):
def setUp(self):
# auto index is disabled for tests so we do it manually
T... | django_elasticsearch/tests/test_views.py | import json
import mock
from django.test import TestCase
from elasticsearch import TransportError
from django_elasticsearch.managers import es_client
from test_app.models import TestModel
class EsViewTestCase(TestCase):
def setUp(self):
# auto index is disabled for tests so we do it manually
T... | 0.380414 | 0.130341 |
import re
from datetime import datetime, timedelta
from dateutil import tz
from dcicutils import (
es_utils,
)
from dcicutils.misc_utils import Retry
BUILD_INDICES_REGEX = re.compile('^[0-9]') # build indices are prefixed by numbers
def wipe_build_indices(es_url, check):
""" Wipes all number-prefixed indic... | foursight_core/checks/helpers/sys_utils.py | import re
from datetime import datetime, timedelta
from dateutil import tz
from dcicutils import (
es_utils,
)
from dcicutils.misc_utils import Retry
BUILD_INDICES_REGEX = re.compile('^[0-9]') # build indices are prefixed by numbers
def wipe_build_indices(es_url, check):
""" Wipes all number-prefixed indic... | 0.428233 | 0.206734 |
from django.contrib.auth.models import User
# from captcha.fields import ReCaptchaField
from django import forms
from accounts.models import UserProfile
from captcha.fields import CaptchaField
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
... | imgigi/accounts/forms.py | from django.contrib.auth.models import User
# from captcha.fields import ReCaptchaField
from django import forms
from accounts.models import UserProfile
from captcha.fields import CaptchaField
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
... | 0.567577 | 0.074838 |
import pytest
from hashtable import HashTable, BLANK
@pytest.fixture
def hash_table():
sample_data = HashTable(capacity=100)
sample_data["hola"] = "hello"
sample_data[98.6] = 37
sample_data[False] = True
return sample_data
def test_should_create_hashtable():
assert HashTable(capacity=100) ... | hashtable/01_hashtable_prototype/04_delete_a_key_value_pair/test_hashtable.py |
import pytest
from hashtable import HashTable, BLANK
@pytest.fixture
def hash_table():
sample_data = HashTable(capacity=100)
sample_data["hola"] = "hello"
sample_data[98.6] = 37
sample_data[False] = True
return sample_data
def test_should_create_hashtable():
assert HashTable(capacity=100) ... | 0.734786 | 0.642376 |
from typing import Any
import subprocess
import traceback
from . import error
def debug(func):
"""A decorator to trace function calls
"""
def closure(*args, **kwargs):
try:
self = func.__self__
method = func.__name__
self_text = f"{type(self).__name__}.{method}... | dltb/util/debug.py | from typing import Any
import subprocess
import traceback
from . import error
def debug(func):
"""A decorator to trace function calls
"""
def closure(*args, **kwargs):
try:
self = func.__self__
method = func.__name__
self_text = f"{type(self).__name__}.{method}... | 0.644784 | 0.165593 |
from django import forms
from django.conf import settings
from netbox.config import get_config, PARAMS
__all__ = (
'ConfigRevisionForm',
)
EMPTY_VALUES = ('', None, [], ())
class FormMetaclass(forms.models.ModelFormMetaclass):
def __new__(mcs, name, bases, attrs):
# Emulate a declared field for ... | netbox/extras/forms/config.py | from django import forms
from django.conf import settings
from netbox.config import get_config, PARAMS
__all__ = (
'ConfigRevisionForm',
)
EMPTY_VALUES = ('', None, [], ())
class FormMetaclass(forms.models.ModelFormMetaclass):
def __new__(mcs, name, bases, attrs):
# Emulate a declared field for ... | 0.600774 | 0.076615 |
# pyre-strict
import asyncio
import logging
import math
from typing import Any, DefaultDict, Dict, List, Optional
from fbpcp.entity.mpc_instance import MPCInstance, MPCInstanceStatus, MPCParty
from fbpcp.service.mpc import MPCService
from fbpcp.service.onedocker import OneDockerService
from fbpcp.service.storage imp... | fbpmp/private_attribution/service/private_attribution.py |
# pyre-strict
import asyncio
import logging
import math
from typing import Any, DefaultDict, Dict, List, Optional
from fbpcp.entity.mpc_instance import MPCInstance, MPCInstanceStatus, MPCParty
from fbpcp.service.mpc import MPCService
from fbpcp.service.onedocker import OneDockerService
from fbpcp.service.storage imp... | 0.774413 | 0.065725 |
import os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0, parentdir)
import logging
import math
import gym
from gym import spaces
from gym.utils import seeding
import numpy as np
import time
i... | examples/pybullet/gym/pybullet_envs/deep_mimic/gym_env/deep_mimic_env.py | import os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0, parentdir)
import logging
import math
import gym
from gym import spaces
from gym.utils import seeding
import numpy as np
import time
i... | 0.31342 | 0.298099 |
import os
import logging
from timeit import default_timer as timer
from metax import __version__
from metax import Logging
from metax import Exceptions
from metax import Utilities
from metax.predixcan import PrediXcanAssociation
from metax.predixcan import Utilities as PrediXcanUtilities
def run(args):
start = ... | software/PrediXcan.py | import os
import logging
from timeit import default_timer as timer
from metax import __version__
from metax import Logging
from metax import Exceptions
from metax import Utilities
from metax.predixcan import PrediXcanAssociation
from metax.predixcan import Utilities as PrediXcanUtilities
def run(args):
start = ... | 0.377196 | 0.170266 |
from datetime import datetime, timedelta
from os.path import join, exists
import pickle
import random
import numpy as np
from numpy.testing import assert_array_equal
import pytest
from pysteps.blending.clim import save_skill, calc_clim_skill
random.seed(12356)
n_cascade_levels = 7
model_names = ["alaro13", "arome... | pysteps/tests/test_blending_clim.py |
from datetime import datetime, timedelta
from os.path import join, exists
import pickle
import random
import numpy as np
from numpy.testing import assert_array_equal
import pytest
from pysteps.blending.clim import save_skill, calc_clim_skill
random.seed(12356)
n_cascade_levels = 7
model_names = ["alaro13", "arome... | 0.678327 | 0.350421 |
import logging
import os
from pathlib import Path
from shutil import copyfile, which
import click
from snowshu.configs import IS_IN_DOCKER
from snowshu.core.replica.replica_factory import ReplicaFactory
from snowshu.core.replica.replica_manager import ReplicaManager
from snowshu.logger import Logger
# Always check f... | snowshu/core/main.py | import logging
import os
from pathlib import Path
from shutil import copyfile, which
import click
from snowshu.configs import IS_IN_DOCKER
from snowshu.core.replica.replica_factory import ReplicaFactory
from snowshu.core.replica.replica_manager import ReplicaManager
from snowshu.logger import Logger
# Always check f... | 0.500977 | 0.095729 |
from mock import patch
import pytest
@patch("pkgutil.get_importer")
def test_load_from_pyinstaller(pkgutil_get_importer):
sample_toc = set(["pyexcel_io", "pyexcel_xls", "blah", "test.dot.module"])
pkgutil_get_importer.return_value.toc = sample_toc
from lml.loader import scan_from_pyinstaller
module_n... | tests/test_plugin_loader.py | from mock import patch
import pytest
@patch("pkgutil.get_importer")
def test_load_from_pyinstaller(pkgutil_get_importer):
sample_toc = set(["pyexcel_io", "pyexcel_xls", "blah", "test.dot.module"])
pkgutil_get_importer.return_value.toc = sample_toc
from lml.loader import scan_from_pyinstaller
module_n... | 0.614625 | 0.52409 |
from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
from .models.project import Project
from .models.subnet import Subnet
from .models.vm import VM
import chardet
# Create your views here.
@csrf_exempt
def project(request):
inpu... | Server/LB/views.py | from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
from .models.project import Project
from .models.subnet import Subnet
from .models.vm import VM
import chardet
# Create your views here.
@csrf_exempt
def project(request):
inpu... | 0.122431 | 0.059921 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = [
'GetRouteResponseResult',
'AwaitableGetRouteResponseResult',
'get_route_response',
'get_route_response_output',
]
@pulumi.output_type
class Ge... | sdk/python/pulumi_aws_native/apigatewayv2/get_route_response.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = [
'GetRouteResponseResult',
'AwaitableGetRouteResponseResult',
'get_route_response',
'get_route_response_output',
]
@pulumi.output_type
class Ge... | 0.792785 | 0.056522 |
from config import application, middleware, storage
from masonite.autoload import Autoload
from masonite.commands import (AuthCommand, CommandCommand, ControllerCommand,
DownCommand, InfoCommand, InstallCommand,
JobCommand, KeyCommand, MakeMigrationCommand... | masonite/providers/AppProvider.py |
from config import application, middleware, storage
from masonite.autoload import Autoload
from masonite.commands import (AuthCommand, CommandCommand, ControllerCommand,
DownCommand, InfoCommand, InstallCommand,
JobCommand, KeyCommand, MakeMigrationCommand... | 0.417509 | 0.038214 |
import sys
# possible transformations
def split(args):
"""INPUT Splits string into a list of elements
If not argument is given then the white characters are used
"""
if args.strip() == 'split':
return lambda input: input.split()
return lambda input: input.split(args.split()[1])
def con... | strans.py | import sys
# possible transformations
def split(args):
"""INPUT Splits string into a list of elements
If not argument is given then the white characters are used
"""
if args.strip() == 'split':
return lambda input: input.split()
return lambda input: input.split(args.split()[1])
def con... | 0.402744 | 0.456955 |
from collections import OrderedDict
from functools import wraps
from flask import _request_ctx_stack, current_app, jsonify, request
from werkzeug.local import LocalProxy
from cognitojwt import CognitoJWTException, decode as cognito_jwt_decode
from jose.exceptions import JWTError
import logging
log = logging.getLogger(... | flask_cognito.py | from collections import OrderedDict
from functools import wraps
from flask import _request_ctx_stack, current_app, jsonify, request
from werkzeug.local import LocalProxy
from cognitojwt import CognitoJWTException, decode as cognito_jwt_decode
from jose.exceptions import JWTError
import logging
log = logging.getLogger(... | 0.590425 | 0.085327 |
import argparse
import boto3
from datetime import datetime
import gevent.monkey
gevent.monkey.patch_all()
import gevent
import gevent.pool
import os
import sys
import time
client = boto3.client('batch')
STATUSES = [
'SUBMITTED', 'PENDING', 'RUNNABLE', 'STARTING',
'RUNNING', 'SUCCEEDED', 'FAILED'
]
# -------... | batch.py | import argparse
import boto3
from datetime import datetime
import gevent.monkey
gevent.monkey.patch_all()
import gevent
import gevent.pool
import os
import sys
import time
client = boto3.client('batch')
STATUSES = [
'SUBMITTED', 'PENDING', 'RUNNABLE', 'STARTING',
'RUNNING', 'SUCCEEDED', 'FAILED'
]
# -------... | 0.239794 | 0.087798 |
import argparse
import json
import logging
import logging.handlers
import nagios_configurator
import os
import subprocess
from os import listdir
from os.path import isfile, join
ICINGA_BIN = '/usr/sbin/icinga'
ICINGA_CONFIG_PATH = '/etc/icinga/icinga.cfg'
LOG_FORMAT = '%(asctime)s %(levelname)-10s %(message)s'
class ... | nagios_auto_reconfigurator.py | import argparse
import json
import logging
import logging.handlers
import nagios_configurator
import os
import subprocess
from os import listdir
from os.path import isfile, join
ICINGA_BIN = '/usr/sbin/icinga'
ICINGA_CONFIG_PATH = '/etc/icinga/icinga.cfg'
LOG_FORMAT = '%(asctime)s %(levelname)-10s %(message)s'
class ... | 0.358129 | 0.045458 |
from __future__ import unicode_literals
import uuid
from mimetypes import guess_type
from email.mime.base import MIMEBase
from email.encoders import encode_base64
from os.path import basename
from ..compat import urlparse, string_types, to_bytes
from ..utils import fetch_url, encode_header
MIMETYPE_UNKNOWN = 'appli... | emails/store/file.py | from __future__ import unicode_literals
import uuid
from mimetypes import guess_type
from email.mime.base import MIMEBase
from email.encoders import encode_base64
from os.path import basename
from ..compat import urlparse, string_types, to_bytes
from ..utils import fetch_url, encode_header
MIMETYPE_UNKNOWN = 'appli... | 0.511229 | 0.063019 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from . import outputs
__all__ = [
'ApiEntityReferenceResponse',
'NetworkInterfaceResponse',
'NetworkProfileResponse',
'SkuResponse',
]
@pulumi.output_type
... | sdk/python/pulumi_azure_native/hardwaresecuritymodules/outputs.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from . import outputs
__all__ = [
'ApiEntityReferenceResponse',
'NetworkInterfaceResponse',
'NetworkProfileResponse',
'SkuResponse',
]
@pulumi.output_type
... | 0.860442 | 0.071916 |
import FreeCAD, Part, Mesh, math
DOC = FreeCAD.activeDocument()
DOC_NAME = "part_disc_cathode"
def clear_doc():
# Clear the active document deleting all the objects
for obj in DOC.Objects:
DOC.removeObject(obj.Name)
def setview():
# Rearrange View
FreeCAD.Gui.SendMsgToActiveView("ViewFit")... | Brevet_us_4_936_961_water_electrolyser_3/part_disc_cathode.py | import FreeCAD, Part, Mesh, math
DOC = FreeCAD.activeDocument()
DOC_NAME = "part_disc_cathode"
def clear_doc():
# Clear the active document deleting all the objects
for obj in DOC.Objects:
DOC.removeObject(obj.Name)
def setview():
# Rearrange View
FreeCAD.Gui.SendMsgToActiveView("ViewFit")... | 0.327668 | 0.48054 |
from __future__ import annotations
from typing import TYPE_CHECKING, Callable, List, Tuple
from pytest import fixture
from pytest_mock import MockerFixture
from keys_management import (
CryptoTool,
KeysManagement,
OnKeyChangedCallbackErrorStrategy,
StateRepoInterface,
)
from keys_management.secret_key i... | tests/conftest.py | from __future__ import annotations
from typing import TYPE_CHECKING, Callable, List, Tuple
from pytest import fixture
from pytest_mock import MockerFixture
from keys_management import (
CryptoTool,
KeysManagement,
OnKeyChangedCallbackErrorStrategy,
StateRepoInterface,
)
from keys_management.secret_key i... | 0.764232 | 0.221498 |
from inotify import constants
from inotify.adapters import Inotify
from pyln.client import Plugin
from sqlalchemy import create_engine
from sqlalchemy import desc
from sqlalchemy.orm import sessionmaker
from threading import Thread
from common import Base, ChannelAnnouncement, ChannelUpdate, NodeAnnouncement
import log... | historian/historian.py | from inotify import constants
from inotify.adapters import Inotify
from pyln.client import Plugin
from sqlalchemy import create_engine
from sqlalchemy import desc
from sqlalchemy.orm import sessionmaker
from threading import Thread
from common import Base, ChannelAnnouncement, ChannelUpdate, NodeAnnouncement
import log... | 0.415966 | 0.123789 |
import collections
import warnings
import pandas
import numpy
import xarray
from xarray import DataArray, Dataset
from datacube.utils.math import dtype_is_float, valid_mask
FLAGS_ATTR_NAME = 'flags_definition'
def list_flag_names(variable):
"""
Returns the available masking flags for the variable
:pa... | datacube/storage/masking.py | import collections
import warnings
import pandas
import numpy
import xarray
from xarray import DataArray, Dataset
from datacube.utils.math import dtype_is_float, valid_mask
FLAGS_ATTR_NAME = 'flags_definition'
def list_flag_names(variable):
"""
Returns the available masking flags for the variable
:pa... | 0.780495 | 0.584093 |
import json
import unittest
from project.tests.base import BaseTestCase
from project import db
from project.api.models import ItemStatus
status_1 = 'status_1'
status_2 = 'status_2'
status_3 = 'status_3'
def add_item_status(name, value, value_type):
item_status = ItemStatus(name=name, value=value, value_type=va... | project/tests/test_item_statuses.py |
import json
import unittest
from project.tests.base import BaseTestCase
from project import db
from project.api.models import ItemStatus
status_1 = 'status_1'
status_2 = 'status_2'
status_3 = 'status_3'
def add_item_status(name, value, value_type):
item_status = ItemStatus(name=name, value=value, value_type=va... | 0.693161 | 0.31633 |
import numpy as np
import pandas as pd
import math
# Below is a useful site that i used to understand a little bit about evaulating the board.
# https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaGame_TicTacToe_AI.html
def evaluateBoard(board, xEval, oEval):
#intitialization of variables
xRowSum = [0]*3... | Algorithms for Data Science/Homework 1/Homework1_Q3.py | import numpy as np
import pandas as pd
import math
# Below is a useful site that i used to understand a little bit about evaulating the board.
# https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaGame_TicTacToe_AI.html
def evaluateBoard(board, xEval, oEval):
#intitialization of variables
xRowSum = [0]*3... | 0.19521 | 0.554832 |
import http.client
import io
import unittest
from collections import defaultdict
from xml.dom.minidom import parseString
import datetime
from requests import Response
import responses
import pytest
from cumulusci.tests.util import create_project_config
from cumulusci.tests.util import DummyOrgConfig
from cumulusci.co... | cumulusci/salesforce_api/tests/test_metadata.py | import http.client
import io
import unittest
from collections import defaultdict
from xml.dom.minidom import parseString
import datetime
from requests import Response
import responses
import pytest
from cumulusci.tests.util import create_project_config
from cumulusci.tests.util import DummyOrgConfig
from cumulusci.co... | 0.383295 | 0.100304 |
from confspirator import groups
from confspirator import fields
from confspirator import types
DEFAULT_QUOTA_SIZES = {
"small": {
"nova": {
"instances": 10,
"cores": 20,
"ram": 65536,
"floating_ips": 10,
"fixed_ips": 0,
"metadata_ite... | adjutant/config/quota.py |
from confspirator import groups
from confspirator import fields
from confspirator import types
DEFAULT_QUOTA_SIZES = {
"small": {
"nova": {
"instances": 10,
"cores": 20,
"ram": 65536,
"floating_ips": 10,
"fixed_ips": 0,
"metadata_ite... | 0.557845 | 0.39321 |
import os
import sys
import torch
import subprocess
from options.train_options import TrainOptions
from loaders import aligned_data_loader
from models import pix2pix_model
def extract_video(vid_filename):
cmd = [
'ffmpeg',
'-i', vid_filename,
'temp/%06d.png',
'-threads', '4'
]
... | test_videos.py | import os
import sys
import torch
import subprocess
from options.train_options import TrainOptions
from loaders import aligned_data_loader
from models import pix2pix_model
def extract_video(vid_filename):
cmd = [
'ffmpeg',
'-i', vid_filename,
'temp/%06d.png',
'-threads', '4'
]
... | 0.27914 | 0.132627 |
from protodata import datasets
from protodata.reading_ops import DataReader
from protodata.data_ops import DataMode
from protodata.utils import get_data_location
from protodata.image_ops import DataSpec
import tensorflow as tf
import scipy
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level... | examples/read_data.py | from protodata import datasets
from protodata.reading_ops import DataReader
from protodata.data_ops import DataMode
from protodata.utils import get_data_location
from protodata.image_ops import DataSpec
import tensorflow as tf
import scipy
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level... | 0.772531 | 0.246335 |
from twisted.internet import defer
from ._base import BaseHandler
from synapse.api.errors import SynapseError
from synapse.http.client import HttpClient
from synapse.api.events.room import RoomAliasesEvent
import logging
import sqlite3
logger = logging.getLogger(__name__)
class DirectoryHandler(BaseHandler):
... | synapse/handlers/directory.py |
from twisted.internet import defer
from ._base import BaseHandler
from synapse.api.errors import SynapseError
from synapse.http.client import HttpClient
from synapse.api.events.room import RoomAliasesEvent
import logging
import sqlite3
logger = logging.getLogger(__name__)
class DirectoryHandler(BaseHandler):
... | 0.227041 | 0.07088 |