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 os
import sys
from IPython import embed
from IPython.core import ultratb
from utility.common import make_dir, dump, load_knowledge
from utility.logging import Logger
from dataset.question_dataset.utils import misc
from dataset.question_dataset.build_questions.question_configs import \
register_builders
fro... | scripts/build_dataset.py |
import os
import sys
from IPython import embed
from IPython.core import ultratb
from utility.common import make_dir, dump, load_knowledge
from utility.logging import Logger
from dataset.question_dataset.utils import misc
from dataset.question_dataset.build_questions.question_configs import \
register_builders
fro... | 0.336549 | 0.1941 |
from django.core.files.base import File
from perma.templatetags.repeat import repeat as perma_repeat
from perma.templatetags.carousel import set_carousel_partners
from perma.models import Registrar
from .utils import PermaTestCase
from io import StringIO, BytesIO
from PIL import Image
class TemplateTagsTestCase(Per... | perma_web/perma/tests/test_templatetags.py | from django.core.files.base import File
from perma.templatetags.repeat import repeat as perma_repeat
from perma.templatetags.carousel import set_carousel_partners
from perma.models import Registrar
from .utils import PermaTestCase
from io import StringIO, BytesIO
from PIL import Image
class TemplateTagsTestCase(Per... | 0.517327 | 0.491883 |
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from rayml.automl.engine.engine_base import (
EngineBase,
EngineComputation,
evaluate_pipeline,
score_pipeline,
train_pipeline,
)
class CFClient:
"""Custom CFClient API to match Dask's CFClient and allow context management... | rayml/automl/engine/cf_engine.py | from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from rayml.automl.engine.engine_base import (
EngineBase,
EngineComputation,
evaluate_pipeline,
score_pipeline,
train_pipeline,
)
class CFClient:
"""Custom CFClient API to match Dask's CFClient and allow context management... | 0.94732 | 0.346237 |
import uuid
import pytest
from datetime import timedelta
from temporal.api.common.v1 import WorkflowExecution
from temporal.api.enums.v1 import EventType
from temporal.api.workflowservice.v1 import GetWorkflowExecutionHistoryRequest
from temporal.workflow import workflow_method, WorkflowClient, Workflow
from temporal... | tests/test_activity_method_activity_options.py | import uuid
import pytest
from datetime import timedelta
from temporal.api.common.v1 import WorkflowExecution
from temporal.api.enums.v1 import EventType
from temporal.api.workflowservice.v1 import GetWorkflowExecutionHistoryRequest
from temporal.workflow import workflow_method, WorkflowClient, Workflow
from temporal... | 0.674372 | 0.166574 |
from __future__ import annotations # noqa: T484
import copy
from pydantic import BaseModel, Field
from arango.exceptions import DatabaseCreateError, EdgeDefinitionCreateError
from arango.cursor import Cursor
from arango.collection import StandardCollection
from multinet import util
from multinet.types import EdgeTab... | multinet/db/models/workspace.py | from __future__ import annotations # noqa: T484
import copy
from pydantic import BaseModel, Field
from arango.exceptions import DatabaseCreateError, EdgeDefinitionCreateError
from arango.cursor import Cursor
from arango.collection import StandardCollection
from multinet import util
from multinet.types import EdgeTab... | 0.753739 | 0.288588 |
import socket
import threading
import time
class FakeESLServer(object):
def __init__(self, address, port, password):
self._address = address
self._port = port
self._password = password
self._client_socket = None
self._running = False
self.commands = {}
self.... | tests/fakeeslserver.py | import socket
import threading
import time
class FakeESLServer(object):
def __init__(self, address, port, password):
self._address = address
self._port = port
self._password = password
self._client_socket = None
self._running = False
self.commands = {}
self.... | 0.206814 | 0.047825 |
import os
import argparse
from typing import List
PATH = os.path.dirname(os.path.realpath(__file__))
LEVEL_SYMBOLS = {
1: '-',
2: '*',
3: '+'
}
def get_content(path: str = PATH) -> List[str]:
lines = []
for item in sorted(os.listdir(path)):
full_path = os.path.join(path, item)
... | toc_generator.py | import os
import argparse
from typing import List
PATH = os.path.dirname(os.path.realpath(__file__))
LEVEL_SYMBOLS = {
1: '-',
2: '*',
3: '+'
}
def get_content(path: str = PATH) -> List[str]:
lines = []
for item in sorted(os.listdir(path)):
full_path = os.path.join(path, item)
... | 0.442155 | 0.100348 |
from databricks_cli.configure.provider import DatabricksConfig, DEFAULT_SECTION, \
update_and_persist_config, get_config_for_profile
TEST_HOST = 'https://test.cloud.databricks.com'
TEST_USER = '<EMAIL>'
TEST_PASSWORD = '<PASSWORD>' # NOQA
TEST_TOKEN = '<PASSWORD>'
TEST_PROFILE = 'testing-profile'
def test_update... | tests/configure/test_provider.py | from databricks_cli.configure.provider import DatabricksConfig, DEFAULT_SECTION, \
update_and_persist_config, get_config_for_profile
TEST_HOST = 'https://test.cloud.databricks.com'
TEST_USER = '<EMAIL>'
TEST_PASSWORD = '<PASSWORD>' # NOQA
TEST_TOKEN = '<PASSWORD>'
TEST_PROFILE = 'testing-profile'
def test_update... | 0.456894 | 0.438304 |
from __future__ import (absolute_import, division, generators, unicode_literals, print_function, nested_scopes,
with_statement)
import logging as log
import re
import time
import requests
from .common import MIME_JSON, CertField, ZoneConfig, Policy, KeyType
from .connection_tpp_abstract impo... | vcert/connection_tpp.py |
from __future__ import (absolute_import, division, generators, unicode_literals, print_function, nested_scopes,
with_statement)
import logging as log
import re
import time
import requests
from .common import MIME_JSON, CertField, ZoneConfig, Policy, KeyType
from .connection_tpp_abstract impo... | 0.574634 | 0.059757 |
"""
Events:
-------
xmlgen_before_import_spec
xmlgen_after_import_spec
xmlgen_before_write
xmlgen_after_write
"""
from hydratk.core.masterhead import MasterHead
from hydratk.core import event
from suds.client import Client, TypeNotFound
from lxml.etree import Element, SubElement, tostring
from os import path
from re ... | src/hydratk/extensions/datagen/xmlgen.py | """
Events:
-------
xmlgen_before_import_spec
xmlgen_after_import_spec
xmlgen_before_write
xmlgen_after_write
"""
from hydratk.core.masterhead import MasterHead
from hydratk.core import event
from suds.client import Client, TypeNotFound
from lxml.etree import Element, SubElement, tostring
from os import path
from re ... | 0.556159 | 0.103658 |
import sys
sys.path.append(r'./') # 为了能找到自写函数
from scipy.sparse import data
from sklearn import tree
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import sklearn
from sklearn.model_selection import train_test_split
from utils.getdata import getdata
# define converts(字典)
def hit_... | src/dorapy/ml/decision_tree.py | import sys
sys.path.append(r'./') # 为了能找到自写函数
from scipy.sparse import data
from sklearn import tree
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import sklearn
from sklearn.model_selection import train_test_split
from utils.getdata import getdata
# define converts(字典)
def hit_... | 0.169991 | 0.437643 |
from os.path import join
from logilab.common.testlib import TestCase, unittest_main
from logilab.common.pytest import *
class ModuleFunctionTC(TestCase):
def test_this_is_testdir(self):
self.assertTrue(this_is_a_testdir("test"))
self.assertTrue(this_is_a_testdir("tests"))
self.assertTrue(th... | vimfiles/bundle/vim-python/pymode/libs/logilab-common-1.4.1/test/unittest_pytest.py | from os.path import join
from logilab.common.testlib import TestCase, unittest_main
from logilab.common.pytest import *
class ModuleFunctionTC(TestCase):
def test_this_is_testdir(self):
self.assertTrue(this_is_a_testdir("test"))
self.assertTrue(this_is_a_testdir("tests"))
self.assertTrue(th... | 0.319546 | 0.743959 |
data = (
'Xiao ', # 0x00
'Suo ', # 0x01
'Li ', # 0x02
'Zheng ', # 0x03
'Chu ', # 0x04
'Guo ', # 0x05
'Gao ', # 0x06
'Tie ', # 0x07
'Xiu ', # 0x08
'Cuo ', # 0x09
'Lue ', # 0x0a
'Feng ', # 0x0b
'Xin ', # 0x0c
'Liu ', # 0x0d
'Kai ', # 0x0e
'Jian ', # 0x0f
'R... | third_party/unidecode/x095.py | data = (
'Xiao ', # 0x00
'Suo ', # 0x01
'Li ', # 0x02
'Zheng ', # 0x03
'Chu ', # 0x04
'Guo ', # 0x05
'Gao ', # 0x06
'Tie ', # 0x07
'Xiu ', # 0x08
'Cuo ', # 0x09
'Lue ', # 0x0a
'Feng ', # 0x0b
'Xin ', # 0x0c
'Liu ', # 0x0d
'Kai ', # 0x0e
'Jian ', # 0x0f
'R... | 0.056496 | 0.050307 |
import threading
import numpy as np
import tensorflow as tf
from google.protobuf import empty_pb2
from elasticdl.proto import elasticdl_pb2, elasticdl_pb2_grpc
from elasticdl.python.common.file_helper import copy_if_not_exists
from elasticdl.python.common.log_util import default_logger as logger
from elasticdl.python... | elasticdl/python/master/servicer.py | import threading
import numpy as np
import tensorflow as tf
from google.protobuf import empty_pb2
from elasticdl.proto import elasticdl_pb2, elasticdl_pb2_grpc
from elasticdl.python.common.file_helper import copy_if_not_exists
from elasticdl.python.common.log_util import default_logger as logger
from elasticdl.python... | 0.522689 | 0.230779 |
import numpy as np
import collections
from random import randint
from core.evaluation.labels import PositiveLabel, NegativeLabel, NeutralLabel
from sample import Sample
from extracted_relations import ExtractedRelation
class BagsCollection:
def __init__(self,
relations,
bag_size... | networks/context/processing/bags.py | import numpy as np
import collections
from random import randint
from core.evaluation.labels import PositiveLabel, NegativeLabel, NeutralLabel
from sample import Sample
from extracted_relations import ExtractedRelation
class BagsCollection:
def __init__(self,
relations,
bag_size... | 0.619932 | 0.559711 |
import math
from ..utils import select_from, select_random
class Selector:
"""
Handles selection of genomes for breeding
:param selection_strategy: parameters for selecting a breeding pool and sets of parents; see :ref:`selection-strategy`
:raises ValueError: if any of ``top``, ``mid``, ``bottom``,... | holland/evolution/selection.py | import math
from ..utils import select_from, select_random
class Selector:
"""
Handles selection of genomes for breeding
:param selection_strategy: parameters for selecting a breeding pool and sets of parents; see :ref:`selection-strategy`
:raises ValueError: if any of ``top``, ``mid``, ``bottom``,... | 0.871256 | 0.516108 |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse_lazy
from django.views.generic import TemplateView, View
from djang... | rankings/views.py |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse_lazy
from django.views.generic import TemplateView, View
from djang... | 0.716318 | 0.093885 |
import utils.utils
import utils.primitive_pipeline_utils
import utils.train_utils
import executors.Executor
from experimental.lstm_predictor.LSTMPredictWorker import LSTM_filter
import random
import json
MAX_TRIAL = 10
class SklearnStackedLSTMExecutor(executors.Executor.Executor):
"""
Executor that processes ... | Stanford-D3M-Full/executors/SklearnStackedLSTMExecutor.py | import utils.utils
import utils.primitive_pipeline_utils
import utils.train_utils
import executors.Executor
from experimental.lstm_predictor.LSTMPredictWorker import LSTM_filter
import random
import json
MAX_TRIAL = 10
class SklearnStackedLSTMExecutor(executors.Executor.Executor):
"""
Executor that processes ... | 0.590543 | 0.292185 |
import cv2
import numpy as np
from .colors import label_color
def draw_box(image, box, color=(255, 0, 0), thickness=2):
""" Draws a box on an image with a given color.
# Arguments
image : The image to draw on.
box : A list of 4 elements (x1, y1, x2, y2).
color : The colo... | dataset_tools/utils/visualization.py | import cv2
import numpy as np
from .colors import label_color
def draw_box(image, box, color=(255, 0, 0), thickness=2):
""" Draws a box on an image with a given color.
# Arguments
image : The image to draw on.
box : A list of 4 elements (x1, y1, x2, y2).
color : The colo... | 0.84039 | 0.772745 |
import doomrl
import json
import os
import shutil
import subprocess
import sys
import tty
from commands import Command
from os.path import exists,lexists,islink
from stat import S_IRUSR,S_IWUSR
from syslog import syslog as log
from ttyrec import TTYRec
class PlayCommand(Command):
"""play <name> -- start or continue... | commands/play.py | import doomrl
import json
import os
import shutil
import subprocess
import sys
import tty
from commands import Command
from os.path import exists,lexists,islink
from stat import S_IRUSR,S_IWUSR
from syslog import syslog as log
from ttyrec import TTYRec
class PlayCommand(Command):
"""play <name> -- start or continue... | 0.255344 | 0.082438 |
import argparse
class TestOptions():
def __init__(self):
self.parser = argparse.ArgumentParser()
# data loader related
self.parser.add_argument('--input_name', type=str, default='../data/SYN/5.png', help='path of the style image')
self.parser.add_argument('--model_task', type=str, ... | src/options.py | import argparse
class TestOptions():
def __init__(self):
self.parser = argparse.ArgumentParser()
# data loader related
self.parser.add_argument('--input_name', type=str, default='../data/SYN/5.png', help='path of the style image')
self.parser.add_argument('--model_task', type=str, ... | 0.694717 | 0.113949 |
from colorama import Fore
class Challenge:
"""Challenge object"""
headers = ["mn_al", "mn_tcl", "mn_il", "mn_lg"]
mnlg_headers = [
"mn_abck", "mn_rts", "mn_psn", "mn_cc", "mn_cd",
"m = mn_cd + mn_mc_indx", "n = rand_toString(16)", "mn_cc + m + n",
"mn_s(r)", "mn_rt", "mn_wt", "get... | challenge.py | from colorama import Fore
class Challenge:
"""Challenge object"""
headers = ["mn_al", "mn_tcl", "mn_il", "mn_lg"]
mnlg_headers = [
"mn_abck", "mn_rts", "mn_psn", "mn_cc", "mn_cd",
"m = mn_cd + mn_mc_indx", "n = rand_toString(16)", "mn_cc + m + n",
"mn_s(r)", "mn_rt", "mn_wt", "get... | 0.362405 | 0.409103 |
import json
import urllib.request
from pprint import pprint
import textgraph
import requests
from datetime import *
# Local modules
def test1():
# Constructing more specific searches seems to require authorisation
url = 'https://api.energidataservice.dk/datastore_search?resource_id=elspotprices'
fileobj ... | energidata.py | import json
import urllib.request
from pprint import pprint
import textgraph
import requests
from datetime import *
# Local modules
def test1():
# Constructing more specific searches seems to require authorisation
url = 'https://api.energidataservice.dk/datastore_search?resource_id=elspotprices'
fileobj ... | 0.256273 | 0.196479 |
import logging
import pandas as pd
from .preprocessingUtils import get_downloads_csv_path
from .import_utils import (
add_or_update_persons_from_dataframe,
update_person_subject_areas,
update_person_keywords,
update_person_orcids,
update_person_status_to,
comma_separated_column_to_map,
no... | peerscout/preprocessing/importEarlyCareerResearchersCsv.py | import logging
import pandas as pd
from .preprocessingUtils import get_downloads_csv_path
from .import_utils import (
add_or_update_persons_from_dataframe,
update_person_subject_areas,
update_person_keywords,
update_person_orcids,
update_person_status_to,
comma_separated_column_to_map,
no... | 0.416322 | 0.114839 |
import numpy as np
from keras import backend as K
from keras.preprocessing.sequence import pad_sequences
from keras.optimizers import Adam,SGD
from keras.utils import to_categorical, plot_model
from keras.models import Sequential, Model, load_model
from keras.layers import Embedding, Dense, Input, Dropout, Reshape, Ba... | ChineseTextualInference/lstm_train.py |
import numpy as np
from keras import backend as K
from keras.preprocessing.sequence import pad_sequences
from keras.optimizers import Adam,SGD
from keras.utils import to_categorical, plot_model
from keras.models import Sequential, Model, load_model
from keras.layers import Embedding, Dense, Input, Dropout, Reshape, Ba... | 0.600071 | 0.270943 |
from pazy_wing_model import PazyWing
import numpy as np
import configobj
import os
def run_coupled_bending_simulation(case_id, tip_load, skin_on, case_root='./cases/', output_folder='./output/'):
# uses a dummy StaticCoupled solution in order to use the num_load_steps feature which has no effect
# on gravity ... | 03a_DeformedModal/test_generate_deformed_modal_linear_follower_force.py | from pazy_wing_model import PazyWing
import numpy as np
import configobj
import os
def run_coupled_bending_simulation(case_id, tip_load, skin_on, case_root='./cases/', output_folder='./output/'):
# uses a dummy StaticCoupled solution in order to use the num_load_steps feature which has no effect
# on gravity ... | 0.363421 | 0.287305 |
import argparse
import os
import numpy as np
import pandas as pd
import cv2
from math import atan, tan, pi
from tqdm import tqdm
import itertools
img_ext = ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG']
def read_calib(calib_path, img_path):
"""
Read in the camera intrinsics and return FOV
:param calib_pat... | depth_to_pointcloud.py | import argparse
import os
import numpy as np
import pandas as pd
import cv2
from math import atan, tan, pi
from tqdm import tqdm
import itertools
img_ext = ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG']
def read_calib(calib_path, img_path):
"""
Read in the camera intrinsics and return FOV
:param calib_pat... | 0.689096 | 0.314761 |
#importa bibliotecas
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import funcs as f1
print('1) Faça o gráfico de dispersão do tamanho do pé (FootLen) em função da altura da pessoa (Height). Calcule (e mostre na tela) a correlação e plote a reta de regressão entre esses dados.')
print()
expe... | footxheight.py | #importa bibliotecas
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import funcs as f1
print('1) Faça o gráfico de dispersão do tamanho do pé (FootLen) em função da altura da pessoa (Height). Calcule (e mostre na tela) a correlação e plote a reta de regressão entre esses dados.')
print()
expe... | 0.223377 | 0.608536 |
from pathlib import Path
from typing import Dict
import PIL.Image # type: ignore
from PIL.ExifTags import TAGS, GPSTAGS # type: ignore
Exif = Dict
# TODO PIL.ExifTags.TAGS
class ExifTags:
DATETIME = "DateTimeOriginal"
LAT = "GPSLatitude"
LAT_REF = "GPSLatitudeRef"
LON = "GPSLongitude"
... | my/photos/utils.py | from pathlib import Path
from typing import Dict
import PIL.Image # type: ignore
from PIL.ExifTags import TAGS, GPSTAGS # type: ignore
Exif = Dict
# TODO PIL.ExifTags.TAGS
class ExifTags:
DATETIME = "DateTimeOriginal"
LAT = "GPSLatitude"
LAT_REF = "GPSLatitudeRef"
LON = "GPSLongitude"
... | 0.331552 | 0.259626 |
from unittest import TestCase
from pathlib import Path
from veniq.utils.utils import flatten
from veniq.ast_framework import AST, ASTNodeType
from veniq.ast_framework.java_class_decomposition import decompose_java_class
from veniq.utils.ast_builder import build_ast
from veniq.metrics.ncss.ncss import NCSSMetric
clas... | test/ast_framework/test_java_class_decomposition.py | from unittest import TestCase
from pathlib import Path
from veniq.utils.utils import flatten
from veniq.ast_framework import AST, ASTNodeType
from veniq.ast_framework.java_class_decomposition import decompose_java_class
from veniq.utils.ast_builder import build_ast
from veniq.metrics.ncss.ncss import NCSSMetric
clas... | 0.73307 | 0.279545 |
from django.db import connections
from django.http import HttpResponse
from django.shortcuts import render
from Admin.dbOperations import Event, Notice, Committee
def approveEvents(request):
event = Event()
return render(request, 'myapp/ApproveEventAdmin.html',
{'mode': 1, 'context': event.g... | unscript/Admin/views.py | from django.db import connections
from django.http import HttpResponse
from django.shortcuts import render
from Admin.dbOperations import Event, Notice, Committee
def approveEvents(request):
event = Event()
return render(request, 'myapp/ApproveEventAdmin.html',
{'mode': 1, 'context': event.g... | 0.267887 | 0.053999 |
#@title MIT License
#
# Copyright (c) 2017 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify,... | src/tf1.x/_03_IMDB/_01_IMDB.py | #@title MIT License
#
# Copyright (c) 2017 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify,... | 0.713631 | 0.197386 |
from __future__ import absolute_import, division, print_function
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
print(tf.__version__)
(train_images, train_labels), (test_images, test_labels) = keras.datas... | 17tensorflow/tf2/101image_classification.py | from __future__ import absolute_import, division, print_function
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
print(tf.__version__)
(train_images, train_labels), (test_images, test_labels) = keras.datas... | 0.879587 | 0.55911 |
import sys
import os
import logging
import json
import socket
import signal
import threading
from multiprocessing import Process, Event
from collections import defaultdict
import urllib2
import uuid
import argparse
repo_root = os.path.abspath(os.path.split(__file__)[0])
service_doc_root = os.path.join(repo_root, "wts"... | wts-serve.py | import sys
import os
import logging
import json
import socket
import signal
import threading
from multiprocessing import Process, Event
from collections import defaultdict
import urllib2
import uuid
import argparse
repo_root = os.path.abspath(os.path.split(__file__)[0])
service_doc_root = os.path.join(repo_root, "wts"... | 0.31563 | 0.076408 |
import logging
import itertools
from collections import deque
from typing import List, Dict, Union, Any, Optional, Deque
from aiostomp.frame import Frame
logger = logging.getLogger("aiostomp.protocol")
class Stomp:
V1_0 = '1.0'
V1_1 = '1.1'
V1_2 = '1.2'
class StompProtocol:
HEART_BEAT = b'\n'
... | aiostomp/protocol.py | import logging
import itertools
from collections import deque
from typing import List, Dict, Union, Any, Optional, Deque
from aiostomp.frame import Frame
logger = logging.getLogger("aiostomp.protocol")
class Stomp:
V1_0 = '1.0'
V1_1 = '1.1'
V1_2 = '1.2'
class StompProtocol:
HEART_BEAT = b'\n'
... | 0.726037 | 0.160759 |
import sys
import os
from FPSim2 import FPSim2Engine
import sqlite3
import pandas as pd
from tqdm import tqdm
from docopt import docopt
def get_assay_data(con, mol_id):
sql = f"""select smiles, name from mols where id = {mol_id}"""
return pd.read_sql(sql, con)
do_input = docopt(__doc__)
query_filename = do_... | search_fpsim2.py | import sys
import os
from FPSim2 import FPSim2Engine
import sqlite3
import pandas as pd
from tqdm import tqdm
from docopt import docopt
def get_assay_data(con, mol_id):
sql = f"""select smiles, name from mols where id = {mol_id}"""
return pd.read_sql(sql, con)
do_input = docopt(__doc__)
query_filename = do_... | 0.11181 | 0.089177 |
from optimizers import GradientDescent
from utils.misc_utils import generate_weights
from utils.decision_tree_utils import partition, find_best_split
from utils.decision_tree_utils import Leaf, Decision_Node
from utils .knn_utils import get_neighbours
from utils.naive_bayes_utils import make_likelihood_table
import num... | MLlib/models.py | from optimizers import GradientDescent
from utils.misc_utils import generate_weights
from utils.decision_tree_utils import partition, find_best_split
from utils.decision_tree_utils import Leaf, Decision_Node
from utils .knn_utils import get_neighbours
from utils.naive_bayes_utils import make_likelihood_table
import num... | 0.721743 | 0.474266 |
import warnings
from typing import List
import click
from xcube.constants import LOG
from xcube.cli.common import (cli_option_quiet,
cli_option_verbosity,
configure_cli_output)
from xcube.webapi.defaults import (DEFAULT_PORT,
... | xcube/cli/serve.py |
import warnings
from typing import List
import click
from xcube.constants import LOG
from xcube.cli.common import (cli_option_quiet,
cli_option_verbosity,
configure_cli_output)
from xcube.webapi.defaults import (DEFAULT_PORT,
... | 0.652574 | 0.086401 |
from __future__ import print_function, division
import sys
import argparse
from os.path import join, exists
from os import mkdir, rename
from math import log10
from dark.reads import (addFASTACommandLineOptions,
parseFASTACommandLineOptions)
parser = argparse.ArgumentParser(
formatter_cl... | bin/fasta-split-by-id.py |
from __future__ import print_function, division
import sys
import argparse
from os.path import join, exists
from os import mkdir, rename
from math import log10
from dark.reads import (addFASTACommandLineOptions,
parseFASTACommandLineOptions)
parser = argparse.ArgumentParser(
formatter_cl... | 0.443359 | 0.122917 |
import multiprocessing as mp
import numpy as np
mp = mp.get_context("spawn")
class TrainingProxy:
def __init__(self, verbose=False):
self._verbose = verbose
def start_training(self, autoencoders, training_batch_size=4096, gpu_devices=[]):
""" call this method from a top-level process """
... | cheatmeal/training_proxy.py | import multiprocessing as mp
import numpy as np
mp = mp.get_context("spawn")
class TrainingProxy:
def __init__(self, verbose=False):
self._verbose = verbose
def start_training(self, autoencoders, training_batch_size=4096, gpu_devices=[]):
""" call this method from a top-level process """
... | 0.520009 | 0.168925 |
import os
from enum import Enum
from pathlib import Path
from os.path import join, exists
import argparse
import pathlib
import click
import numpy as np
import pandas as pd
import download_data
import dataframe
import plotter
from matplotlib import pyplot as plt
import seaborn as sns
import dataframe
import plotter... | plotting/paper_subsample_classes.py | import os
from enum import Enum
from pathlib import Path
from os.path import join, exists
import argparse
import pathlib
import click
import numpy as np
import pandas as pd
import download_data
import dataframe
import plotter
from matplotlib import pyplot as plt
import seaborn as sns
import dataframe
import plotter... | 0.473657 | 0.204878 |
from abc import ABCMeta
from typing import Optional, Union, Tuple
import torch
import torch.nn.functional as F
from torch.distributions import Gumbel
from torch.nn import Sequential
def set_temperature(m: torch.nn.Module, temp: torch.Tensor):
if isinstance(m, MixedModule):
m.gumbel_temperature.copy_(temp... | search/arch_search.py | from abc import ABCMeta
from typing import Optional, Union, Tuple
import torch
import torch.nn.functional as F
from torch.distributions import Gumbel
from torch.nn import Sequential
def set_temperature(m: torch.nn.Module, temp: torch.Tensor):
if isinstance(m, MixedModule):
m.gumbel_temperature.copy_(temp... | 0.941345 | 0.434761 |
import os
import shutil
import json
import common
def import_content_page(
page_id,
page_descriptor,
input_page_dir,
output_page_dir):
# If a pdf file is specified in the page descriptor then copy it inside
# the pdf directory, which is in turn bundled into the app resources.... | app/scripts/contents_importer.py |
import os
import shutil
import json
import common
def import_content_page(
page_id,
page_descriptor,
input_page_dir,
output_page_dir):
# If a pdf file is specified in the page descriptor then copy it inside
# the pdf directory, which is in turn bundled into the app resources.... | 0.397821 | 0.079032 |
from numba import jit, f8
from numpy import sqrt, array, cos, sin
"""
Derivative of co-planarity potential wrt vi
"""
@jit( f8[:](f8[:], f8[:], f8[:]), cache=True, nopython=True )
def Dphi_pDvi(vi, xi, xj):
u0,u1,u2 = vi
x0,x1,x2 = xi
y0,y1,y2 = xj
vi_mag_sqr = u0**2 + u1**2 + u2**2
vi_mag = sqrt(... | src/lib/JacPotV.py | from numba import jit, f8
from numpy import sqrt, array, cos, sin
"""
Derivative of co-planarity potential wrt vi
"""
@jit( f8[:](f8[:], f8[:], f8[:]), cache=True, nopython=True )
def Dphi_pDvi(vi, xi, xj):
u0,u1,u2 = vi
x0,x1,x2 = xi
y0,y1,y2 = xj
vi_mag_sqr = u0**2 + u1**2 + u2**2
vi_mag = sqrt(... | 0.323166 | 0.487551 |
from collections import defaultdict
import numpy as np
import sys
import itertools
if "../" not in sys.path:
sys.path.append("../")
from libs.envs.windy_gridworld import WindyGridworldEnv
from libs.plot import plot_result, compare_plots
from ch6_TD.sarsa import Sarsa
from ch6_TD.q_learning import Q_learning
de... | examples/Sutton_RL_Intro/ch6_TD/double_q_learning.py |
from collections import defaultdict
import numpy as np
import sys
import itertools
if "../" not in sys.path:
sys.path.append("../")
from libs.envs.windy_gridworld import WindyGridworldEnv
from libs.plot import plot_result, compare_plots
from ch6_TD.sarsa import Sarsa
from ch6_TD.q_learning import Q_learning
de... | 0.508788 | 0.364014 |
from PIL import Image
import numpy as np
import logging
import primes.visualisation.generic as generic
from primes.visualisation.gl_base import Canvas
logger = logging.getLogger(__name__)
class PlainComplex(generic.Generic):
"""For simply displaying complex numbers on complex coordinates.
Note:
T... | primes/visualisation/plaincomplex/plaincomplex.py | from PIL import Image
import numpy as np
import logging
import primes.visualisation.generic as generic
from primes.visualisation.gl_base import Canvas
logger = logging.getLogger(__name__)
class PlainComplex(generic.Generic):
"""For simply displaying complex numbers on complex coordinates.
Note:
T... | 0.58059 | 0.275038 |
from configs import LearningConfigs
from modules.Snake import Snake
from modules.Food import Food
from modules.Render import Render
from modules.Observer import Observer
class Game:
def __init__(self, screen = None):
self.screen = screen
self.snake = Snake()
self.food = Food(self.snake)
... | modules/Game.py | from configs import LearningConfigs
from modules.Snake import Snake
from modules.Food import Food
from modules.Render import Render
from modules.Observer import Observer
class Game:
def __init__(self, screen = None):
self.screen = screen
self.snake = Snake()
self.food = Food(self.snake)
... | 0.680985 | 0.258037 |
from datetime import datetime, timedelta
from src.base import BaseDevice, SwitchableDevice, PWMDevice
from RPi.GPIO import assert_output, assert_duty_cycle, HIGH, LOW
def test_base_device():
BaseDevice()
def test_switchable_device_on_off_methods():
switchable = SwitchableDevice(1)
assert switchable.is_... | tests/test_base.py | from datetime import datetime, timedelta
from src.base import BaseDevice, SwitchableDevice, PWMDevice
from RPi.GPIO import assert_output, assert_duty_cycle, HIGH, LOW
def test_base_device():
BaseDevice()
def test_switchable_device_on_off_methods():
switchable = SwitchableDevice(1)
assert switchable.is_... | 0.767516 | 0.693834 |
from lxml import html
from string import ascii_lowercase
import web
import logging
logger = logging.getLogger('phenny')
def shorten_num(n):
if n < 1000:
return '{:,}'.format(n)
elif n < 1000000:
return '{}K'.format(str(round(n/1000, 1)).rstrip('0').rstrip('.'))
elif n < 1000000000:
... | modules/ethnologue.py | from lxml import html
from string import ascii_lowercase
import web
import logging
logger = logging.getLogger('phenny')
def shorten_num(n):
if n < 1000:
return '{:,}'.format(n)
elif n < 1000000:
return '{}K'.format(str(round(n/1000, 1)).rstrip('0').rstrip('.'))
elif n < 1000000000:
... | 0.2414 | 0.110856 |
__author__ = 'isparks'
import requests
import datetime
import hmac
import hashlib
import base64
from six.moves.urllib.parse import urlencode
SECONDS_IN_24_HOURS = 24 * 60 * 60
def isodatetime(dt):
"""Takes a date, returns ISO8601 date/time format"""
return dt.strftime('%Y-%m-%dT%H:%M:%S')
def isodate(dt):
... | actigraph/client.py | __author__ = 'isparks'
import requests
import datetime
import hmac
import hashlib
import base64
from six.moves.urllib.parse import urlencode
SECONDS_IN_24_HOURS = 24 * 60 * 60
def isodatetime(dt):
"""Takes a date, returns ISO8601 date/time format"""
return dt.strftime('%Y-%m-%dT%H:%M:%S')
def isodate(dt):
... | 0.666714 | 0.110543 |
import base64
from rest_framework import serializers
from ..models import Project, Snapshot, Value
class ValueSerializer(serializers.ModelSerializer):
attribute = serializers.CharField(source='attribute.uri', default=None, read_only=True)
option = serializers.CharField(source='option.uri', default=None, re... | rdmo/projects/serializers/export.py | import base64
from rest_framework import serializers
from ..models import Project, Snapshot, Value
class ValueSerializer(serializers.ModelSerializer):
attribute = serializers.CharField(source='attribute.uri', default=None, read_only=True)
option = serializers.CharField(source='option.uri', default=None, re... | 0.625209 | 0.180793 |
import os
import re
import setuptools
import shutil
import sys
if not sys.version_info >= (3, 5):
exit("Sorry, Python's version must be later than 3.5.")
# constants
COMMAND_NAME = "shakyo"
README_BASENAME = "README"
RST_EXT = "rst"
MD_EXT = "md"
# functions
def warn(*text):
print("WARNING:", *text, file=... | setup.py |
import os
import re
import setuptools
import shutil
import sys
if not sys.version_info >= (3, 5):
exit("Sorry, Python's version must be later than 3.5.")
# constants
COMMAND_NAME = "shakyo"
README_BASENAME = "README"
RST_EXT = "rst"
MD_EXT = "md"
# functions
def warn(*text):
print("WARNING:", *text, file=... | 0.188511 | 0.086208 |
from django.contrib.auth import SESSION_KEY
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import gettext_lazy as _
class Event(models.Model):
class Meta:
db_table = "core_event"
user = models.ForeignKey(
User,
null=False, blank... | apps/core/models.py | from django.contrib.auth import SESSION_KEY
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import gettext_lazy as _
class Event(models.Model):
class Meta:
db_table = "core_event"
user = models.ForeignKey(
User,
null=False, blank... | 0.474144 | 0.091911 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ray.rllib.agents.trainer import Trainer, with_common_config
from ray.rllib.agents.marwil.marwil_policy_graph import MARWILPolicyGraph
from ray.rllib.optimizers import SyncBatchReplayOptimizer
from ray.rlli... | python/ray/rllib/agents/marwil/marwil.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ray.rllib.agents.trainer import Trainer, with_common_config
from ray.rllib.agents.marwil.marwil_policy_graph import MARWILPolicyGraph
from ray.rllib.optimizers import SyncBatchReplayOptimizer
from ray.rlli... | 0.880193 | 0.254133 |
"""Numpy-related utilities."""
import numpy as np
from tensorflow.python.util.tf_export import keras_export
@keras_export('keras.utils.to_categorical')
def to_categorical(y, num_classes=None, dtype='float32'):
"""Converts a class vector (integers) to binary class matrix.
E.g. for use with `categorical_crossentr... | keras/utils/np_utils.py | """Numpy-related utilities."""
import numpy as np
from tensorflow.python.util.tf_export import keras_export
@keras_export('keras.utils.to_categorical')
def to_categorical(y, num_classes=None, dtype='float32'):
"""Converts a class vector (integers) to binary class matrix.
E.g. for use with `categorical_crossentr... | 0.968871 | 0.703779 |
import pandas as pd
from math import sin, cos, sqrt, asin, radians
import ibm_db
def cal_dist(lon1, lat1, lon2, lat2):
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
c = 2 * as... | Recommendation/attr_bnb_distance.py | import pandas as pd
from math import sin, cos, sqrt, asin, radians
import ibm_db
def cal_dist(lon1, lat1, lon2, lat2):
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
c = 2 * as... | 0.134463 | 0.274762 |
from flask_sqlalchemy import sqlalchemy
from flask_migrate import Migrate
from sqlalchemy import func
from sqlalchemy.orm import relationship
from config import db
# id, State, Order Number, COffice, created_at , updated_at
class OfficeModel(db.Model):
__tablename__ = "offices"
usa_state = db.Column(db.String... | models.py | from flask_sqlalchemy import sqlalchemy
from flask_migrate import Migrate
from sqlalchemy import func
from sqlalchemy.orm import relationship
from config import db
# id, State, Order Number, COffice, created_at , updated_at
class OfficeModel(db.Model):
__tablename__ = "offices"
usa_state = db.Column(db.String... | 0.529507 | 0.069415 |
import json
import copy
import jsonschema
from scrapi import registry
from scrapi.util import json_without_bytes
def strip_empty(document, required=tuple()):
''' Removes empty fields from the processed schema
'''
new_doc = {}
for k, v in document.items():
if k in required:
new_do... | scrapi/linter/document.py | import json
import copy
import jsonschema
from scrapi import registry
from scrapi.util import json_without_bytes
def strip_empty(document, required=tuple()):
''' Removes empty fields from the processed schema
'''
new_doc = {}
for k, v in document.items():
if k in required:
new_do... | 0.705785 | 0.176849 |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import time
total_FLOPs = 0
i=0
def prune(a, index):
# a (1,4,2,2)
# b (4)
return a[:,np.nonzero(index).squeeze(1),:,:]
def prune_n(a, len):
return a[:,:len, :,:]
def default_conv(in_channels, out_chan... | FDSR_f_x4/src/model/common.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import time
total_FLOPs = 0
i=0
def prune(a, index):
# a (1,4,2,2)
# b (4)
return a[:,np.nonzero(index).squeeze(1),:,:]
def prune_n(a, len):
return a[:,:len, :,:]
def default_conv(in_channels, out_chan... | 0.834137 | 0.374076 |
import os
import argparse
import csv
from rp2paths.pyEMSv2.reaction import StrReaction
from rp2paths.ImgMaker import ImgMaker
class ImgHandler(object):
"""Handling computation of pictures."""
def __init__(self, pathsfile, cmpdfile, imgdir,
cmpdnamefile=None,
width=400, heigh... | rp2paths/ImgHandler.py | import os
import argparse
import csv
from rp2paths.pyEMSv2.reaction import StrReaction
from rp2paths.ImgMaker import ImgMaker
class ImgHandler(object):
"""Handling computation of pictures."""
def __init__(self, pathsfile, cmpdfile, imgdir,
cmpdnamefile=None,
width=400, heigh... | 0.52342 | 0.114517 |
import argparse
import math
import numpy as np
# x, y, degrees
COMMANDS_TO_TRANSFORMS = {
"N": (0, 1, 0),
"S": (0, -1, 0),
"E": (1, 0, 0),
"W": (-1, 0, 0),
"L": (0, 0, 1),
"R": (0, 0, -1),
}
DEGREES_TO_DIRECTION = {
0: "E",
90: "N",
180: "W",
270: "S",
}
def apply_transform... | 12/day12.py | import argparse
import math
import numpy as np
# x, y, degrees
COMMANDS_TO_TRANSFORMS = {
"N": (0, 1, 0),
"S": (0, -1, 0),
"E": (1, 0, 0),
"W": (-1, 0, 0),
"L": (0, 0, 1),
"R": (0, 0, -1),
}
DEGREES_TO_DIRECTION = {
0: "E",
90: "N",
180: "W",
270: "S",
}
def apply_transform... | 0.433981 | 0.331039 |
__author__ = '<NAME>'
__copyright__ = 'Copyright (C) 2018, Nokia'
__email__ = '<EMAIL>'
import threading
import time
import pytest
from moler.connection_observer import ConnectionObserver
def test_can_submit_connection_observer_into_background(connection_observer,
... | test/integration/test_thread_based_runner.py | __author__ = '<NAME>'
__copyright__ = 'Copyright (C) 2018, Nokia'
__email__ = '<EMAIL>'
import threading
import time
import pytest
from moler.connection_observer import ConnectionObserver
def test_can_submit_connection_observer_into_background(connection_observer,
... | 0.543106 | 0.211824 |
import os
from itertools import repeat, takewhile
from typing import Sequence
import pandas as pd
def count_file_lines(filepath: str, buffer_size: int = 1024 * 1024) -> int:
"""
Count lines in a file without persisting it in memory.
Args:
filepath (str): path to the file.
buffer_size (in... | pytoda/files.py | import os
from itertools import repeat, takewhile
from typing import Sequence
import pandas as pd
def count_file_lines(filepath: str, buffer_size: int = 1024 * 1024) -> int:
"""
Count lines in a file without persisting it in memory.
Args:
filepath (str): path to the file.
buffer_size (in... | 0.831588 | 0.270793 |
from pyspark.ml.classification import MultilayerPerceptronClassifier
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *
from pyspark.sql.window import Window
from pathlib import Path
from pyspark.sq... | sparkFiles/multilayer_perceptron_classification.py | from pyspark.ml.classification import MultilayerPerceptronClassifier
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *
from pyspark.sql.window import Window
from pathlib import Path
from pyspark.sq... | 0.49292 | 0.334535 |
import argparse
class BadSequenceLength(Exception):
"""Base class for other exception """
class BadNucleotideSequence(Exception):
"""Base class for other exception """
class BadNumberSequences(Exception):
"""Base class for other exception """
# --------------------------------------------------
def ... | bioinformatics_stronghold/hamm.py | import argparse
class BadSequenceLength(Exception):
"""Base class for other exception """
class BadNucleotideSequence(Exception):
"""Base class for other exception """
class BadNumberSequences(Exception):
"""Base class for other exception """
# --------------------------------------------------
def ... | 0.712932 | 0.31106 |
adaptive_card = {
"type": "AdaptiveCard",
"body": [
{
"type": "ColumnSet",
"columns": [
{
"type": "Column",
"items": [
{
"type": "Image",
"style... | adaptive_card.py | adaptive_card = {
"type": "AdaptiveCard",
"body": [
{
"type": "ColumnSet",
"columns": [
{
"type": "Column",
"items": [
{
"type": "Image",
"style... | 0.622689 | 0.430925 |
import sys
import re
import PyQt5.QtWidgets as qt
from pathlib import Path
from PyQt5 import QtCore
from PyQt5.QtGui import QPixmap
class PredictDXA(qt.QWidget):
'''
GUI to predict.py
'''
def __init__(self):
super().__init__()
self.init_ui()
self.in_folder = '.'
self.leg... | src/gui2.py | import sys
import re
import PyQt5.QtWidgets as qt
from pathlib import Path
from PyQt5 import QtCore
from PyQt5.QtGui import QPixmap
class PredictDXA(qt.QWidget):
'''
GUI to predict.py
'''
def __init__(self):
super().__init__()
self.init_ui()
self.in_folder = '.'
self.leg... | 0.187504 | 0.118029 |
from __future__ import unicode_literals
from usernames import is_safe_username
def test_max_lenght():
assert is_safe_username("u" * 10, max_length=10)
assert not is_safe_username("u" * 11, max_length=10)
def test_blacklist():
assert not is_safe_username("helo", blacklist=["helo"])
assert not is_saf... | tests/test_usernames.py | from __future__ import unicode_literals
from usernames import is_safe_username
def test_max_lenght():
assert is_safe_username("u" * 10, max_length=10)
assert not is_safe_username("u" * 11, max_length=10)
def test_blacklist():
assert not is_safe_username("helo", blacklist=["helo"])
assert not is_saf... | 0.609524 | 0.291627 |
"""Tests for kfp.v2.google.client.runtime_config_builder."""
import frozendict
import unittest
from kfp.v2.google.client import runtime_config_builder
class RuntimeConfigBuilderTest(unittest.TestCase):
SAMPLE_JOB_SPEC = frozendict.frozendict({
'pipelineSpec': {
'root': {
'inputDefin... | sdk/python/kfp/v2/google/client/runtime_config_builder_test.py | """Tests for kfp.v2.google.client.runtime_config_builder."""
import frozendict
import unittest
from kfp.v2.google.client import runtime_config_builder
class RuntimeConfigBuilderTest(unittest.TestCase):
SAMPLE_JOB_SPEC = frozendict.frozendict({
'pipelineSpec': {
'root': {
'inputDefin... | 0.744749 | 0.20836 |
import json
import flask
from werkzeug.exceptions import HTTPException, InternalServerError
class APIError(HTTPException):
"""An exception indicating an error that should be reported to the user.
i.e. If such an error occurs in a rest API call, it should be reported as
part of the HTTP response.
"""
... | haas/errors.py | import json
import flask
from werkzeug.exceptions import HTTPException, InternalServerError
class APIError(HTTPException):
"""An exception indicating an error that should be reported to the user.
i.e. If such an error occurs in a rest API call, it should be reported as
part of the HTTP response.
"""
... | 0.666497 | 0.195498 |
import sys
import re
from westtools import WESTTool, WESTDataReader
import numpy, h5py, operator, time
import westpa
from westpa import h5io
from west import Segment
from west.states import InitialState
from west.data_manager import (weight_dtype, n_iter_dtype, seg_id_dtype, utime_dtype, vstr_dtype,
... | lib/west_tools/w_trace.py | import sys
import re
from westtools import WESTTool, WESTDataReader
import numpy, h5py, operator, time
import westpa
from westpa import h5io
from west import Segment
from west.states import InitialState
from west.data_manager import (weight_dtype, n_iter_dtype, seg_id_dtype, utime_dtype, vstr_dtype,
... | 0.456652 | 0.41478 |
from netapp.netapp_object import NetAppObject
class IscsiTransmittedStatsInfo(NetAppObject):
"""
Counts for PDUs transmitted.
"""
_nop_in = None
@property
def nop_in(self):
"""
Count of NOP In.
"""
return self._nop_in
@nop_in.setter
def nop_in(self, ... | generated-libraries/python/netapp/iscsi/iscsi_transmitted_stats_info.py | from netapp.netapp_object import NetAppObject
class IscsiTransmittedStatsInfo(NetAppObject):
"""
Counts for PDUs transmitted.
"""
_nop_in = None
@property
def nop_in(self):
"""
Count of NOP In.
"""
return self._nop_in
@nop_in.setter
def nop_in(self, ... | 0.589598 | 0.122025 |
from collections import namedtuple
from collections import defaultdict
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from mpl_toolkits.mplot3d import axes3d
# Source: https://www.blackjackinfo.com/dealer-outcome-probabilities/#TIDS17
dealer_prob = [[.3536, .3739, .3945, .4164, .4232,... | main.py | from collections import namedtuple
from collections import defaultdict
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from mpl_toolkits.mplot3d import axes3d
# Source: https://www.blackjackinfo.com/dealer-outcome-probabilities/#TIDS17
dealer_prob = [[.3536, .3739, .3945, .4164, .4232,... | 0.428712 | 0.146026 |
import pickle
import pytest
from praw.exceptions import ClientException
from praw.models import Submission
from ... import UnitTest
class TestSubmission(UnitTest):
def test_equality(self):
submission1 = Submission(self.reddit, _data={"id": "dummy1", "n": 1})
submission2 = Submission(self.reddit... | tests/unit/models/reddit/test_submission.py | import pickle
import pytest
from praw.exceptions import ClientException
from praw.models import Submission
from ... import UnitTest
class TestSubmission(UnitTest):
def test_equality(self):
submission1 = Submission(self.reddit, _data={"id": "dummy1", "n": 1})
submission2 = Submission(self.reddit... | 0.634317 | 0.592195 |
import base64
import io
import numpy as np
import PIL.ExifTags
import PIL.Image
import PIL.ImageOps
def img_b64_to_arr(img_b64):
f = io.BytesIO()
f.write(base64.b64decode(img_b64))
img_arr = np.array(PIL.Image.open(f))
return img_arr
def img_arr_to_b64(img_arr):
img_pil = PIL.Image.fromarray(im... | labelme2coco/image_utils.py | import base64
import io
import numpy as np
import PIL.ExifTags
import PIL.Image
import PIL.ImageOps
def img_b64_to_arr(img_b64):
f = io.BytesIO()
f.write(base64.b64decode(img_b64))
img_arr = np.array(PIL.Image.open(f))
return img_arr
def img_arr_to_b64(img_arr):
img_pil = PIL.Image.fromarray(im... | 0.398289 | 0.265586 |
from model import Model
from query import Query
from config import FOOD_TYPES
class View(object):
query = None
def __init__(self, model):
assert isinstance(model, Model), 'Type mismatch! model must be of type Model.'
self.query = Query(model)
def remove_artefacts(self, records, testfield):... | view.py | from model import Model
from query import Query
from config import FOOD_TYPES
class View(object):
query = None
def __init__(self, model):
assert isinstance(model, Model), 'Type mismatch! model must be of type Model.'
self.query = Query(model)
def remove_artefacts(self, records, testfield):... | 0.534127 | 0.343424 |
import pydiffvg
import torch
import os
import matplotlib.pyplot as plt
import random
import argparse
import math
import errno
from tqdm import tqdm
from torch.optim.lr_scheduler import CosineAnnealingLR
from torch.nn.functional import adaptive_avg_pool2d
pydiffvg.set_print_timing(False)
gamma = 1.0
def parse_args():
... | pair/Layerwise/check_init_points.py | import pydiffvg
import torch
import os
import matplotlib.pyplot as plt
import random
import argparse
import math
import errno
from tqdm import tqdm
from torch.optim.lr_scheduler import CosineAnnealingLR
from torch.nn.functional import adaptive_avg_pool2d
pydiffvg.set_print_timing(False)
gamma = 1.0
def parse_args():
... | 0.27914 | 0.19569 |
from numpy import zeros
# Enthought library imports.
from traits.api import Any, Bool, Float, Instance, Property, Tuple
# Local relative imports
from image_plot import ImagePlot
from abstract_colormap import AbstractColormap
from speedups import apply_selection_fade
class CMapImagePlot(ImagePlot):
""" Colormap... | chaco/cmap_image_plot.py |
from numpy import zeros
# Enthought library imports.
from traits.api import Any, Bool, Float, Instance, Property, Tuple
# Local relative imports
from image_plot import ImagePlot
from abstract_colormap import AbstractColormap
from speedups import apply_selection_fade
class CMapImagePlot(ImagePlot):
""" Colormap... | 0.575111 | 0.551091 |
from abaqusConstants import *
class DamageEvolution:
"""The DamageEvolution object specifies material properties to define the evolution of
damage.
Notes
-----
This object can be accessed by:
.. code-block:: python
import material
mdb.models[name].materials[name... | src/abaqus/Material/ProgressiveDamageFailure/DamageEvolution.py | from abaqusConstants import *
class DamageEvolution:
"""The DamageEvolution object specifies material properties to define the evolution of
damage.
Notes
-----
This object can be accessed by:
.. code-block:: python
import material
mdb.models[name].materials[name... | 0.886334 | 0.377914 |
"""Mesh data utilities."""
import matplotlib.pyplot as plt
import modules
from mpl_toolkits import mplot3d # pylint: disable=unused-import
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import networkx as nx
import numpy as np
import six
from six.moves import range
import tensorflow.compat.v1 as tf
import te... | Polygen/data_utils.py |
"""Mesh data utilities."""
import matplotlib.pyplot as plt
import modules
from mpl_toolkits import mplot3d # pylint: disable=unused-import
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import networkx as nx
import numpy as np
import six
from six.moves import range
import tensorflow.compat.v1 as tf
import te... | 0.765155 | 0.513668 |
from chargebee.compat import json
from chargebee.models import *
class Result(object):
def __init__(self, response):
self._response = response
self._response_obj = {}
@property
def subscription(self):
subscription = self._get('subscription', Subscription)
return subscript... | chargebee/result.py | from chargebee.compat import json
from chargebee.models import *
class Result(object):
def __init__(self, response):
self._response = response
self._response_obj = {}
@property
def subscription(self):
subscription = self._get('subscription', Subscription)
return subscript... | 0.798187 | 0.119871 |
import os
import argparse
from utils import check_directories, initialize_script, end_script
from loader import get_fov_names
import bigfish.stack as stack
import bigfish.detection as detection
import bigfish.plot as plot
if __name__ == "__main__":
print()
# parse arguments
parser = argparse.ArgumentPar... | bigfish_scripts/detect_rna.py | import os
import argparse
from utils import check_directories, initialize_script, end_script
from loader import get_fov_names
import bigfish.stack as stack
import bigfish.detection as detection
import bigfish.plot as plot
if __name__ == "__main__":
print()
# parse arguments
parser = argparse.ArgumentPar... | 0.450118 | 0.151843 |
import torch
import numpy as np
import logging
import os
from torch.utils.data import DataLoader
from cormorant.data.dataset_kaggle import KaggleTrainDataset
from cormorant.data.prepare import prepare_dataset
def init_nmr_kaggle_dataset(args, datadir, file_name='targets_train.npz', trim=True, additional_atom_featur... | solutions/12/src/cormorant/data/utils_kaggle.py | import torch
import numpy as np
import logging
import os
from torch.utils.data import DataLoader
from cormorant.data.dataset_kaggle import KaggleTrainDataset
from cormorant.data.prepare import prepare_dataset
def init_nmr_kaggle_dataset(args, datadir, file_name='targets_train.npz', trim=True, additional_atom_featur... | 0.639511 | 0.557905 |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import model_managers.home_model_manager
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Agent... | teamcat_service/docker_build/target/one_step_build/teamcat/doraemon/home/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import model_managers.home_model_manager
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Agent... | 0.583678 | 0.204044 |
import tensorflow as tf
from utils import *
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, recall_score
from numpy import argmax
from word2vec import *
from sklearn.metrics import confusion_matrix
CONTINUE_TRAIN = False
y_train_dir = './bins/y_train.npy'
x_... | Homework/2019/Task5/4/code/lstm.py | import tensorflow as tf
from utils import *
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, recall_score
from numpy import argmax
from word2vec import *
from sklearn.metrics import confusion_matrix
CONTINUE_TRAIN = False
y_train_dir = './bins/y_train.npy'
x_... | 0.506103 | 0.269153 |
from scytale.ciphers import Fleissner
from scytale.exceptions import ScytaleError
import pytest
def test_from_worksheet():
cipher = Fleissner(key="<KEY>")
ciphertext = cipher.encrypt("WELCOME TO VILLIERS PARK")
assert cipher.compare("WEXEXRXSXXL CXXXOPXXMEA XXXRXXXKXTXOXXX XXXXVXXXIXLXXXLIXXXXXXXX", cip... | tests/test_fleissner.py | from scytale.ciphers import Fleissner
from scytale.exceptions import ScytaleError
import pytest
def test_from_worksheet():
cipher = Fleissner(key="<KEY>")
ciphertext = cipher.encrypt("WELCOME TO VILLIERS PARK")
assert cipher.compare("WEXEXRXSXXL CXXXOPXXMEA XXXRXXXKXTXOXXX XXXXVXXXIXLXXXLIXXXXXXXX", cip... | 0.666497 | 0.505676 |
from pathlib import Path
import os
import io
import environ
import google.auth
from google.cloud import secretmanager
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
env = environ.... | server/medperf/settings.py | from pathlib import Path
import os
import io
import environ
import google.auth
from google.cloud import secretmanager
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
env = environ.... | 0.327561 | 0.102305 |
import threading
from decouple import config
from django.conf import settings
from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import render_to_string
class EmailThread(threading.Thread):
def __init__(self, subject, body, from_email, recipient_list, fail_silently, html, rep... | api/MailSender.py | import threading
from decouple import config
from django.conf import settings
from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import render_to_string
class EmailThread(threading.Thread):
def __init__(self, subject, body, from_email, recipient_list, fail_silently, html, rep... | 0.339828 | 0.074433 |
from main.models import FiltroCuentas, FiltroMovimientos
import datetime
from fixtures_views import *
class TestCambiarOrden():
@pytest.fixture
def create_filter_cuentas(self):
# Create filter with default values (all blanks)
return FiltroCuentas.objects.create()
@pytest.fixture
def ... | conta/main/tests/views/test_cambiar_orden.py | from main.models import FiltroCuentas, FiltroMovimientos
import datetime
from fixtures_views import *
class TestCambiarOrden():
@pytest.fixture
def create_filter_cuentas(self):
# Create filter with default values (all blanks)
return FiltroCuentas.objects.create()
@pytest.fixture
def ... | 0.305179 | 0.306851 |
import torch
import numpy as np
from tacotron2_stft import STFT
from librosa.filters import mel as librosa_mel_fn
def dynamic_range_compression(x, C=1, clip_val=1e-5):
"""
PARAMS
------
C: compression factor
"""
return torch.log(torch.clamp(x, min=clip_val) * C)
def dynamic_range_decompressi... | tacotron2_layers.py | import torch
import numpy as np
from tacotron2_stft import STFT
from librosa.filters import mel as librosa_mel_fn
def dynamic_range_compression(x, C=1, clip_val=1e-5):
"""
PARAMS
------
C: compression factor
"""
return torch.log(torch.clamp(x, min=clip_val) * C)
def dynamic_range_decompressi... | 0.942493 | 0.670716 |
from setuptools import setup
import os
packages = []
root_dir = os.path.dirname(__file__)
if root_dir:
os.chdir(root_dir)
for dirpath, dirnames, filenames in os.walk('lcopt'):
# Ignore dirnames that start with '.'
if '__init__.py' in filenames:
pkg = dirpath.replace(os.path.sep, '.')
if os... | setup.py | from setuptools import setup
import os
packages = []
root_dir = os.path.dirname(__file__)
if root_dir:
os.chdir(root_dir)
for dirpath, dirnames, filenames in os.walk('lcopt'):
# Ignore dirnames that start with '.'
if '__init__.py' in filenames:
pkg = dirpath.replace(os.path.sep, '.')
if os... | 0.357119 | 0.065306 |
from lxml import etree as ET
import numpy as np
class URDFType(object):
"""Abstract base class for all URDF types.
This has useful class methods for automatic parsing/unparsing
of XML trees.
There are three overridable class variables:
- ``_ATTRIBS`` - This is a dictionary mapping attribute name... | urdfpy/urdf/base.py | from lxml import etree as ET
import numpy as np
class URDFType(object):
"""Abstract base class for all URDF types.
This has useful class methods for automatic parsing/unparsing
of XML trees.
There are three overridable class variables:
- ``_ATTRIBS`` - This is a dictionary mapping attribute name... | 0.877464 | 0.426381 |
from queue import Queue
from .property_tree import PropertyTree
from .errors import *
class Filter(object):
"""
Base class for filters.
"""
def __init__(self, name, context):
if not self.__validate():
raise InvalidFilterDefinitionError(self)
self.name = name
self... | src/visitpy/visit_flow/flow/src/core/filter_graph.py | from queue import Queue
from .property_tree import PropertyTree
from .errors import *
class Filter(object):
"""
Base class for filters.
"""
def __init__(self, name, context):
if not self.__validate():
raise InvalidFilterDefinitionError(self)
self.name = name
self... | 0.729231 | 0.145388 |
import numpy as np
import os, cv2
from tqdm import tqdm
def rotateImage(img,deg):
rows,cols,depth = img.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2),deg,1)
return cv2.warpAffine(img,M,(cols,rows))
def scaleImage(img):
return cv2.resize(img,None,fx=2, fy=2, interpolation = cv2.INTER_CUBIC)
def fo... | processData.py | import numpy as np
import os, cv2
from tqdm import tqdm
def rotateImage(img,deg):
rows,cols,depth = img.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2),deg,1)
return cv2.warpAffine(img,M,(cols,rows))
def scaleImage(img):
return cv2.resize(img,None,fx=2, fy=2, interpolation = cv2.INTER_CUBIC)
def fo... | 0.177276 | 0.351826 |
import torch
import torch.nn as nn
from supar.modules.dropout import SharedDropout
from torch.nn.modules.rnn import apply_permutation
from torch.nn.utils.rnn import PackedSequence
class LSTM(nn.Module):
r"""
LSTM is an variant of the vanilla bidirectional LSTM adopted by Biaffine Parser
with the only dif... | supar/modules/lstm.py |
import torch
import torch.nn as nn
from supar.modules.dropout import SharedDropout
from torch.nn.modules.rnn import apply_permutation
from torch.nn.utils.rnn import PackedSequence
class LSTM(nn.Module):
r"""
LSTM is an variant of the vanilla bidirectional LSTM adopted by Biaffine Parser
with the only dif... | 0.952042 | 0.576721 |
class ActiveSequence:
def __init__(self, num_spectra: int, window_size: float, p_vlm: float):
self.num_spectra = num_spectra
self.window_size = window_size
self.p_vlm = p_vlm
self._the_list = []
self.mz_avg = 0.0
self.mz_lb = -50
self._spectra_present = [Fa... | pymsvlm/msAlign/ActiveSequence.py | class ActiveSequence:
def __init__(self, num_spectra: int, window_size: float, p_vlm: float):
self.num_spectra = num_spectra
self.window_size = window_size
self.p_vlm = p_vlm
self._the_list = []
self.mz_avg = 0.0
self.mz_lb = -50
self._spectra_present = [Fa... | 0.57069 | 0.395601 |
import json
import torch
from main_our_v2 import Model as our_model
def convert2str_random(dic):
tag = ''.join(dic['tag'])
gender = '男' if dic['gender'] == 'male' else '女'
loc = ';'.join(dic['loc'].split())
res = '性别: ' + gender + ',地域: ' + loc + ',标签: ' + tag
return res
def convert2str_biased(dic... | generate_our_sample.py | import json
import torch
from main_our_v2 import Model as our_model
def convert2str_random(dic):
tag = ''.join(dic['tag'])
gender = '男' if dic['gender'] == 'male' else '女'
loc = ';'.join(dic['loc'].split())
res = '性别: ' + gender + ',地域: ' + loc + ',标签: ' + tag
return res
def convert2str_biased(dic... | 0.33644 | 0.3534 |
from datetime import datetime
import json
import re
import httplib2
from leapfrog.models import Object, Account, Person, Media
def account_for_twitter_user(userdata, person=None):
try:
account = Account.objects.get(service='twitter.com', ident=str(userdata['id']))
except Account.DoesNotExist:
... | leapfrog/poll/twitter.py | from datetime import datetime
import json
import re
import httplib2
from leapfrog.models import Object, Account, Person, Media
def account_for_twitter_user(userdata, person=None):
try:
account = Account.objects.get(service='twitter.com', ident=str(userdata['id']))
except Account.DoesNotExist:
... | 0.159054 | 0.04798 |
import argparse
from pathlib import Path
import sys
import os
p = (Path(__file__) / ".." / "..").resolve()
sys.path.append(str(p))
from deeppavlov.core.commands.train import train_evaluate_model_from_config
from deeppavlov.core.commands.infer import interact_model, predict_on_stream
from deeppavlov.core.common.log im... | deeppavlov/deep.py | import argparse
from pathlib import Path
import sys
import os
p = (Path(__file__) / ".." / "..").resolve()
sys.path.append(str(p))
from deeppavlov.core.commands.train import train_evaluate_model_from_config
from deeppavlov.core.commands.infer import interact_model, predict_on_stream
from deeppavlov.core.common.log im... | 0.394667 | 0.089137 |
import json
import discord
from discord.ext import commands
class Moderation(commands.Cog):
"""Typical moderation commands."""
def __init__(self, bot):
self.bot = bot
self.blue = discord.Color.blue()
self.user_conv = commands.UserConverter()
async def create_muted_role(self, gui... | cogs/moderation.py |
import json
import discord
from discord.ext import commands
class Moderation(commands.Cog):
"""Typical moderation commands."""
def __init__(self, bot):
self.bot = bot
self.blue = discord.Color.blue()
self.user_conv = commands.UserConverter()
async def create_muted_role(self, gui... | 0.606848 | 0.111628 |